I have a need for a Linux system to listen on a TCP port and dump what it receives to a file and/or stdout. The system does not have netcat installed. I have root permissions, but am not allowed to add new applications to the system for compliance reasons. Is it possible to do this with a simple bash, perl, or python script? The simpler, the better.
1 Answer
To open a random port using Python:
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((socket.gethostname(), 0))
To find out which port you have opened:
s.getsockname()[1]
To close the port:
s.close()
For more information, read the documentation for the socket module, the socket how-to, or a socket tutorial.