【问题标题】:How can i change server directory in python from client?如何从客户端更改 python 中的服务器目录?
【发布时间】:2020-03-27 20:23:36
【问题描述】:

我正在尝试做客户端-服务器项目。在这个项目中,我必须将 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() 

【问题讨论】:

    标签: python linux subprocess client-server


    【解决方案1】:

    您可以检查正在发送的命令是否等于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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-01-27
      • 1970-01-01
      • 1970-01-01
      • 2012-09-25
      • 2019-09-28
      • 1970-01-01
      • 2021-01-31
      • 1970-01-01
      相关资源
      最近更新 更多