I want to write a reverse shell like netcat. Everything works fine, but after several commands typed in, the client machine throws an error. I managed to identify the problem. When I change to the Desktop directory on the server, for example C:/Users/Desktop and I type in the command "dir" the error gets thrown on the client machine.
Note that open_shell is a boolean that I set to True with passing an argument to the program
server code:
'''creates server'''
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.connect((target, port))
print(f"[*] Connecting to client ...", os.linesep)
client_msg = server.recv(buffer_size).decode()
print("[*] current directory: ", client_msg)
# opening a reverse shell to client
if open_shell:
server.send("open shell".encode())
print(server.recv(buffer_size).decode())
while True:
command = input(">>")
if command.lower() == "exit":
print("[*] Closing connection ...")
break
if not command.strip():
continue
else:
server.send(command.encode())
output = server.recv(buffer_size).decode()
print(output)
client code:
'''creates client'''
global target
if not len(target):
target = "0.0.0.0"
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.bind((target, port))
client.listen(5)
client_socket, addr = client.accept()
print("[*] Connected to server ...")
cwd = os.getcwd()
client_socket.send(cwd.encode())
command = client_socket.recv(buffer_size).decode()
if command.lower() == "exit":
print("[*] Connection closed by server ...")
break
if command.lower() == "open shell":
client_socket.send("[*] reverse shell established\n[*] To exit reverse shell type in 'exit'".encode())
while True:
execute = client_socket.recv(buffer_size).decode()
if execute.lower() == "exit":
break
message = run_command(execute) # executes command on client
client_socket.send(message.encode())
The error is located in the process module in the function "communicate" but I can't figure out wants going on.
Error:
Traceback (most recent call last):
File "netcat.py", line 200, in <module>
main()
File "netcat.py", line 195, in main
client_object()
File "netcat.py", line 122, in client_object
message = run_command(execute) # executes command on client
^^^^^^^^^^^^^^^^^^^^
File "netcat.py", line 33, in run_command
output = subprocess.getoutput(command)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "Python\Python311\Lib\subprocess.py", line 689, in getoutput
return getstatusoutput(cmd, encoding=encoding, errors=errors)[1]
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "Python\Python311\Lib\subprocess.py", line 669, in getstatusoutput
data = check_output(cmd, shell=True, text=True, stderr=STDOUT,
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "Python\Python311\Lib\subprocess.py", line 465, in check_output
return run(*popenargs, stdout=PIPE, timeout=timeout, check=True,
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "Python\Python311\Lib\subprocess.py", line 548, in run
stdout, stderr = process.communicate(input, timeout=timeout)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "Python\Python311\Lib\subprocess.py", line 1192, in communicate
stdout = self.stdout.read()
^^^^^^^^^^^^^^^^^^
File "Python\Python311\Lib\encodings\cp1252.py", line 23, in decode
return codecs.charmap_decode(input,self.errors,decoding_table)[0]
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
UnicodeDecodeError: 'charmap' codec can't decode byte 0x81 in position 323: character maps to <undefined>
Before starting Python, set your environment variable PYTHONIOENCODING=utf-8.
Related
I need to perform a remote software update for a Linux device.
I'm able to upload via SSH and SFTP to /tmp/ folder the .bin file and perform the sysupgrade.
I want to do this on multiple device, so I added a for loop in order to do it.
But, when I run the ssh.exec_command("sysupgrade /tmp/myfile.bin"), something stucks.
Here's my code:
import paramiko
# paths to file
local_path="C:/Users/Desktop/myfile.bin"
remote_path="/tmp/myfile.bin"
# IP
ip_list = ["my_ip_1","my_ip_2"]
password_list=["passw_1","passw_2"]
#Start SSH
ssh = paramiko.client.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
# loop for IP and password
for i,n in zip(ip_list,password_list):
print(i,n)
try:
print("Open session in: " + i + "...")
ssh.connect(i, username='root', password=n)
except paramiko.SSHException:
print("Connection Failed")
quit()
# Upload file to /tmp/
print("Uploading file to " + str(i) + " in /tmp/...")
sftp = ssh.open_sftp()
sftp.put(local_path, remote_path)
try:
# Here something stucks
stdin, stdout, stderr = ssh.exec_command("sysupgrade /tmp/myfile.bin", timeout=30)
sysupgrade_response=stdout.readlines()
print(sysupgrade_response)
sftp.close()
ssh.close()
except paramiko.SSHException:
print("Continue with others IP in list...")
sftp.close()
ssh.close()
continue
sftp.close()
ssh.close()
print("\n\n***********************End execution***********************\n\n")
This is the errors I got:
Traceback (most recent call last):
File "C:\Users\AppData\Roaming\Python\Python37\site-packages\paramiko\channel.py", line 699,
in recv
out = self.in_buffer.read(nbytes, self.timeout)
File "C:\Users\AppData\Roaming\Python\Python37\site-packages\paramiko\buffered_pipe.py",
line 164, in read
raise PipeTimeout()
paramiko.buffered_pipe.PipeTimeout
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users\Python Scripts\myscript.py", line 73, in <module>
sysupgrade_response=stdout.readlines()
File "C:\Users\AppData\Roaming\Python\Python37\site-packages\paramiko\file.py", line 349,
in readlines
line = self.readline()
File "C:\Users\AppData\Roaming\Python\Python37\site-packages\paramiko\file.py", line 291,
in readline
new_data = self._read(n)
File "C:\Users\AppData\Roaming\Python\Python37\site-packages\paramiko\channel.py", line 1361,
in _read
return self.channel.recv(size)
File "C:\Users\AppData\Roaming\Python\Python37\site-packages\paramiko\channel.py", line 701,
in recv
raise socket.timeout()
After the "sysupgrade" command, I would like to close the connection with the first ip in the list ( or handling some errors ) and go on with the for loop and connect to the second ip in the list.
Hope is clear enough
I assume that the sysupgrade restarts the machine or at least the SSH server or networking.
I would guess that if you execute sysupgrade in your SSH client, it will also lose the connection, won't it?
Hi I have a problem in my server- client connection
I wrote the 2 codes on windows 10 and they worked perfectly. But when I tried to execute them on ubuntu in a VM I had this error:
Traceback (most recent call last):
File "client3.py", line 9, in <module>
sock.connect(('192.168.1.53', 1234))
File "/usr/lib/python2.7/socket.py", line 228, in meth
return getattr(self._sock,name)(*args)
socket.error: [Errno 111] Connection refused
the server code:
import threading
import SocketServer
import json
import base64
class ThreadedTCPRequestHandler(SocketServer.BaseRequestHandler):
def handle(self):
data = self.request.recv(327680)
data = json.loads(data)
cur_thread = threading.current_thread()
JL= data['Jliste']
for i in range(0,9) :
cel = json.loads(JL[i])
file_name = cel['name']
img = base64.b64decode(cel['img'])
with open(file_name,'wb') as _file:
_file.write(img)
print "image {} Received ".format(i)
response = "images Received "
print response
self.request.sendall(response)
class ThreadedTCPServer(SocketServer.ThreadingMixIn, SocketServer.TCPServer):
pass
if __name__ == "__main__":
server = ThreadedTCPServer(("localhost", 1234), ThreadedTCPRequestHandler)
# Start a thread with the server -- that thread will then start one
# more thread for each request
server_thread = threading.Thread(target=server.serve_forever)
# Exit the server thread when the main thread terminates
server_thread.daemon = True
server_thread.start()
print "Server loop running in thread:", server_thread.name
the client code:
import socket
import json
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect(('localhost', 1234))
try:
def generate_names(count):
return 'User.2.{}.jpg'.format(count)
L = []
for i in range(0,9):
name = generate_names(i+1)
fp = open(name,'rb')
fp = fp.read()
fp = fp.encode('base64')
cel = {}
cel['name'] = name
cel['img'] = fp
jcel = json.dumps(cel)
L.append(jcel)
data = {}
data['Jliste'] = L
s = json.dumps(data)
sock.send(s)
response = sock.recv(1024)
print "Received: {}".format(response)
finally:
sock.close()
the new error i get is:
Exception happened during processing of request from ('127.0.0.1', 60900)
Traceback (most recent call last):
File "/usr/lib/python2.7/SocketServer.py", line 596, in process_request_thread
self.finish_request(request, client_address)
File "/usr/lib/python2.7/SocketServer.py", line 331, in finish_request
self.RequestHandlerClass(request, client_address, self)
File "/usr/lib/python2.7/SocketServer.py", line 652, in __init__
self.handle()
File "server.py", line 12, in handle
data = json.loads(data)
File "/usr/lib/python2.7/json/__init__.py", line 339, in loads
return _default_decoder.decode(s)
File "/usr/lib/python2.7/json/decoder.py", line 364, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/usr/lib/python2.7/json/decoder.py", line 380, in raw_decode
obj, end = self.scan_once(s, idx)
ValueError: Unterminated string starting at: line 1 column 16913 (char 16912)
Not sure why this works on Windows, but when I run your code on Ubuntu, your server just exits - just as it is supposed to. It prints "server loop running..." and then exits. As your thread is set to server_thread.daemon=True, the thread is killed as well. It does not even have time to initialise the socket.
If you change server_thread.daemon=False or add sleep(600) or something like that (you would of course an infinite loop) as the last statement in your main(), it starts listening to the socket and process requests - which is probably what you want.
Currently, I am trying to develop a server framework which passes messages from twitch to other machines on a local network. I have a class called server and below I have a rudimentary example which demonstrates the problem I am running into. The issue is that the twitch_socket is being created twice and bound to the address/port. My expected result is that the socket would be shared between the child processes of the Server class. How can I modify the class, or even get rid of it entirely, so that the Processes would be able to share sockets between them?
import multiprocessing
import socket
import re
from BotPass import PASSWORD
def send_message(socketobj, message):
'Sends a str as bytes through socket'
message = message.encode()
socketobj.sendall(message)
def recv_message(socketobj):
'Receives a str as bytes though socket'
return socketobj.recv(2048).decode()
class Server:
'Handles receiving messages from twitch and directs messages from clients'
twitch_socket = socket.socket()
twitch_socket.connect(('irc.chat.twitch.tv', 6667))
send_message(twitch_socket, 'PASS %s\r\n' % (PASSWORD))
send_message(twitch_socket, 'NICK %s\r\n' % ('squid_coin_bot'))
send_message(twitch_socket, 'JOIN #jtv\r\n')
send_message(twitch_socket, 'CAP REQ :twitch.tv/commands\r\n')
server_socket = socket.socket()
server_socket.bind(('', 9999))
work_queue = multiprocessing.Queue()
#Queue of messages from twitch
worker_queue = multiprocessing.Queue()
#Queue of free client socket objects
result_queue = multiprocessing.Queue()
#Queue of what to send back to twitch
def start():
accept_process = multiprocessing.Process(target=Server.accept_connections)
# *This is most likely where the issue is occurring*
accept_process.daemon = True
accept_process.start()
def accept_connections():
''
Server.server_socket.listen(10)
while 1:
(clientsocket, clientaddr) = Server.server_socket.accept()
# What I believe I am referencing here is the server socket which is inherent to the Server class
if re.match(r'192\.168\.\d{1,3}\.\d{1,3}', clientaddr[0])\
or clientaddr[0] == '127.0.0.1':
Server.worker_queue.put(clientsocket)
else:
clientsocket.close()
Server.start()
input()
Output in Console:
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "C:\Program Files\Python36\lib\multiprocessing\spawn.py", line 105, in spawn_main
exitcode = _main(fd)
File "C:\Program Files\Python36\lib\multiprocessing\spawn.py", line 114, in _main
prepare(preparation_data)
File "C:\Program Files\Python36\lib\multiprocessing\spawn.py", line 225, in prepare
_fixup_main_from_path(data['init_main_from_path'])
File "C:\Program Files\Python36\lib\multiprocessing\spawn.py", line 277, in _fixup_main_from_path
run_name="__mp_main__")
File "C:\Program Files\Python36\lib\runpy.py", line 263, in run_path
pkg_name=pkg_name, script_name=fname)
File "C:\Program Files\Python36\lib\runpy.py", line 96, in _run_module_code
mod_name, mod_spec, pkg_name, script_name)
File "C:\Program Files\Python36\lib\runpy.py", line 85, in _run_code
exec(code, run_globals)
File "C:\twitch-market\server.py", line 18, in <module>
class Server:
File "C:\twitch-market\server.py", line 27, in Server
server_socket.bind(('', 9999))
OSError: [WinError 10048] Only one usage of each socket address (protocol/network address/port) is normally permitted
Add this socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
This is because the previous execution has left the socket in a TIME_WAIT state, and can’t be immediately reused.the SO_REUSEADDR flag tells the kernel to reuse a local socket in TIME_WAIT state, without waiting for its natural timeout to expire.
I wrote this code that functions properly on Windows but gives a few errors on my Ubuntu 12.04. Although the code performs well its intended function but its given some errors which I don't want.. Kindly help me in this regard..
from socket import *
from threading import Thread
from Crypto.Cipher import AES
import os
import base64
import timeit
# Receiveing + Decoding the Information, symmetrical key isi
def clientHandler():
conn, addr = s.accept()
print addr, "is connected"
while 1:
data = conn.recv(1024)
if not data:
break
print "Metering Data Received: Processing..."
#creating decoding unpadding
PADDING ="{"
DecodeAES = lambda c, e: c.decrypt(base64.b64decode(e)).rstrip(PADDING)
#creating a default key
obj2 = AES.new('This is a key123', AES.MODE_CBC, 'This is an IV456')
decrypted_data = DecodeAES(obj2,data)
print decrypted_data
HOST = "" #localhost
PORT = 12000
s = socket(AF_INET, SOCK_STREAM)
s.bind((HOST, PORT))
s.listen(4)
print "Server is runnig"
#Thread(target=clientHandler).start()
#Thread(target=clientHandler).start()
#Thread(target=clientHandler).start()
for i in range(4):
Thread(target=clientHandler).start()
s.close()
And this is what appears on the terminal of Ubuntu but not on Windows based...
Server is runnig
Exception in thread Thread-4:
Traceback (most recent call last):
File "/usr/lib/python2.7/threading.py", line 551, in __bootstrap_inner
self.run()
File "/usr/lib/python2.7/threading.py", line 504, in run
self.__target(*self.__args, **self.__kwargs)
File "chat_encrypt.py", line 10, in clientHandler
conn, addr = s.accept()
File "/usr/lib/python2.7/socket.py", line 202, in accept
sock, addr = self._sock.accept()
File "/usr/lib/python2.7/socket.py", line 170, in _dummy
raise error(EBADF, 'Bad file descriptor')
error: [Errno 9] Bad file descriptor
for i in range(4):
Thread(target=clientHandler).start()
s.close()
The last line closes the socket ... which each thread then tries to 'accept'.
The following receiveFile() function reads a filename and file data from the socket and splits it using the delimiter $.
But I am unable to close the socket and a Bad file descriptor error is raised. If I comment out the self.server_socket.close() statement then there is no error but the socket is listening forever.
Code:-
def listen(self):
self.server_socket.listen(10)
while True:
client_socket, address = self.server_socket.accept()
print 'connected to', address
self.receiveFile(client_socket)
def receiveFile(self,sock):
data = sock.recv(1024)
data = data.split("$");
print 'filename', data[0]
f = open(data[0], "wb")
#data = sock.recv(1024)
print 'the data is', data[1]
f.write(data[1])
data = sock.recv(1024)
while (data):
f.write(data)
data=sock.recv(1024)
f.close()
self.server_socket.close()
print 'the data is', data
print "File Downloaded"
Traceback:-
Traceback (most recent call last):
File "server.py", line 45, in <module>
a = Server(1111)
File "server.py", line 15, in __init__
self.listen()
File "server.py", line 20, in listen
client_socket, address = self.server_socket.accept()
File "c:\Python27\lib\socket.py", line 202, in accept
sock, addr = self._sock.accept()
File "c:\Python27\lib\socket.py", line 170, in _dummy
raise error(EBADF, 'Bad file descriptor')
socket.error: [Errno 9] Bad file descriptor
You are closing the server's listening socket, and after that calling again accept() on it.
To finish receiving one file you should close client connection's socket (sock in function receiveFile).
in this code i am trying to shut down the server once file is received
What you'll need is something to break out of the while True loop when you want to shut down the server. A simple solution would be to exploit the exception generated when you close the server socket...
def listen(self):
self.server_socket.listen(10)
while True:
try:
client_socket, address = self.server_socket.accept()
except socket.error:
break
print 'connected to', address
self.receiveFile(client_socket)
print 'shutting down'