【发布时间】:2015-08-24 17:24:58
【问题描述】:
服务器端代码,处理客户端发送的数据。
#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 ..”之类的命令时,它没有成功,因为据我所知,它会将目录更改为子进程。有没有办法使用客户端更改父目录?
【问题讨论】:
-
你可以用 os.chdir(path) 改变工作目录
-
你应该知道一些shell命令,比如
cd是内置的,但大多数是与shell没有连接的外部程序。外部命令可以使用subprocess运行,内置命令不能。因此,如果您正在编写 shell,请确定哪些是内置的。要在 bash 中找出现有的,请使用type cd、type kill等。您可能需要一个字典,其中键是内置函数的名称,值是每个内置函数的函数。 -
是的。正如 Luciano 所建议的,我真的很喜欢“自定义命令”的想法。根据我的需要,如果我不能拥有它们,我会创建它们。