I have two files: client.py and server.py that when run are connected by socket.
When I send a command to the client from the server, for example a simple ls
, I use a function (in the client) called subprocess.Popen
to execute it in the shell. However, the error bytes object has no attribute 'read'
appears to me.
Is there any other way to execute a command other than the subprocess module?
Am I running subprocess correctly with the following call:
command = subprocess.Popen (args, shell = True, stdout = subprocess.PIPE, stderr = subprocess.PIPE)
Below I attached the code of the two programs.
The server code is as follows:
#!/usr/bin/python3
# -*- coding: utf-8 -*-
import socket
def main():
try:
servidor = socket.socket()
servidor.bind(('localhost',7777))
servidor.listen(1)
while True:
client, direccion = servidor.accept()
print('[+] Conexion de: {}'.format(direccion))
while True:
comando = input("<server>: ")
client.send(comando.encode())
result = client.recv(4096)
print(result.decode())
except Exception as e:
print (e)
if __name__ == '__main__' :
try:
main()
except KeyboardInterrupt:
exit()
The client code is as follows:
#!/usr/bin/python3
# -*- coding: utf-8 -*-
import socket
import subprocess
import shlex
def main():
try:
client = socket.socket()
client.connect(('localhost', 7777))
while True:
datos = client.recv(4096)
args = shlex.split(datos)
comando = subprocess.Popen(args, shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
if comando.stderr.read() != "":
client.send("[-] Error de comando")
else:
cliente.send(comando.stdout.read())
except Exception as e:
print (e)
if __name__ == '__main__' :
try:
main()
except KeyboardInterrupt:
exit()
args = shlex.split(datos)
datos is of type bytes
, but shlex.split
expects a str
.
args = shlex.split(datos.encode())
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.