Get available port for shell script

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.

from socket import socket

s = socket()
print(s.getsockname()[1])  #stdout