Find a random available local port from your shell script e.g. for SSH port forwarding.
#!/usr/bin/env python """ for use from shell, returns on STDOUT a free port number. Yes, there is a slight race condition where between end of this program and start of your shell program, another program could grab this port. Useful for scripts with SSH port forwarding for example, where you have one or more hops before the final host. reference: http://stackoverflow.com/questions/1365265/on-localhost-how-to-pick-a-free-port-number """ from socket import socket s = socket() s.bind(('',0)) print(s.getsockname()) #stdout s.close()