服务器端代码,用于处理客户端发送的数据。
#receiving data
data = client.recv(1024)
# if it's quit, then break out and close socket
if data.decode("UTF-8") == "quit": break
# do shell command
proc = subprocess.Popen(data.decode("UTF-8"), shell=True, stdout=subprocess.PIPE, \
stderr=subprocess.PIPE, stdin=subprocess.PIPE)
# read output
stdout_value = proc.stdout.read() + proc.stderr.read()
valid = "done"
if stdout_value.decode(sys.stdout.encoding, errors="ignore") == "":
client.send(valid.encode("utf-8")) # for commands like "C:", which print nothing
# send output
client.send(stdout_value)
客户端代码,它发送数据(命令)并打印结果
reply = input()
client.send(reply.encode("UTF-8"))
receive = client.recv(4096)
print(receive.decode(sys.stdout.encoding, errors="ignore")
当我尝试使用诸如" cd .."之类的命令时,它没有成功,因为据我所知,它将目录更改为子进程。有没有办法使用客户端更改父目录?
答案 0 :(得分:0)
是的,你是对的。 “cd”将改变子进程目录。
但是,您可以在执行前分析命令并应用一些特殊行为。
小心,检测到丑陋的代码。
from os import chdir
...
if data.startswith('cd '):
chdir(data[3:]) # Don't execute with Popen
else:
proc = .....