【问题标题】:Changing working directory in a client/server environment in python在 python 中更改客户端/服务器环境中的工作目录
【发布时间】:2019-01-27 21:57:08
【问题描述】:

我试图找出使用服务器脚本中的“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()

【问题讨论】:

  • 如果您想知道,那根本不安全。
  • 不使用加密或本地存储密码的事情?我知道我现在只是测试它。即将发生大量变化
  • 这两个,加上你试图停止kill 命令。如果您运行它,请使用仅限白名单的 sudoers 文件并完全锁定运行 shell 的用户的所有内容,以防万一。但如果他们走到那一步,你就输了。
  • 我对python相当陌生,我使用kill命令关闭shell,这是不好的做法吗?你会怎么做?
  • 我会使用exitlogout,因为kill 是杀死其他进程的程序。我认为通过静默关闭连接来阻止kill 命令的使用是一种微不足道的尝试。

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


【解决方案1】:

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

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

【讨论】:

  • 哇...我没有意识到我正在创建多个 shell 大声笑,我怎样才能把它全部变成一个 shell?
  • @calinative707 我已经更新了答案;这有帮助吗?抱歉耽搁了。
  • 是的,我想我可以做到,感谢您的帮助
  • @calinative707 如果这不起作用,您可以自己重新实现类似 shell 的东西:docs.python.org/3/library/shlex.html#module-shlex
  • 我无法让多个命令在一个 shell 中工作,主要是因为我对如何做到这一点没有深入的了解
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-03-23
  • 1970-01-01
  • 1970-01-01
  • 2021-01-31
  • 2019-02-06
  • 2011-09-02
  • 1970-01-01
相关资源
最近更新 更多