我如何从客户端更改 python 中的服务器目录?

How can i change server directory in python from client?

我正在尝试做客户端-服务器项目。在这个项目中,我必须从客户端向服务器发送 linux 命令。现在我可以发送一些命令,如 ls、pwd 等,它们是 运行 正确的,我可以在客户端读取输出,但是当我尝试发送 "cd" 命令时,我没有收到任何错误但服务器中的目录没有改变。如果我使用 os.chdir(os.path.abspath(data)) 命令而不是 subprocess.check_output ,它可以更改目录但它是无用的,因为我可以发送其他命令,如 ls、pwd、mkdir 等. 感谢您的帮助

服务器端:

def threaded(c):
    while True:
        # data received from client
        data = c.recv(1024)
        if not data:
            print('Bye')
            break
        try:
            data_o = subprocess.check_output(data, shell=True)
        except subprocess.CalledProcessError as e:
            c.send(b'failed\n')
            print(e.output)

        if(len(data_o) > 0):
            c.send(data_o)
        else:
            c.send(b'There is no terminal output.')

    # connection closed
    c.close()

客户端:

while True: 
 # message sent to server 

        s.send(message.encode('ascii')) 
        # messaga received from server 
        data = s.recv(1024)
   # print the received message 

        print('Received from the server :',str(data.decode('ascii'))) 

        # ask the client whether he wants to continue 

        ans = input('\nDo you want to continue(y/n) :') 
        if ans == 'y':
            message = input("enter message")
            continue
        else: 
            break

    # close the connection 
    s.close() 

您可以检查发送的命令是否等于 cd 并根据此更改运行时行为。

data_spl = data.split()

if data_spl[0] == 'cd':
    data_o = os.chdir(os.path.abspath(data_spl[1]))
else:
    data_o = subprocess.check_output(data, shell=True)