Last active
December 8, 2017 13:11
-
-
Save wolkenarchitekt/57f7fa6d056eaf6580de8dab95580848 to your computer and use it in GitHub Desktop.
Establish SSH forwarding tunnel in background
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import subprocess | |
logger = logging.getLogger(__name__) | |
def ssh_tunnel(jumphost, remote_server, local_port, remote_port, | |
control_socket='/tmp/ssh_socket'): | |
""" | |
Establish SSH tunnel | |
:param jumphost: jump host | |
:param remote_server: remote server | |
:param local_port: local port | |
:param remote_port: remote port | |
:param control_socket: control socket for SSH tunnel | |
:return: | |
""" | |
if os.path.exists(control_socket): | |
logger.warning("Stopping existing SSH tunnel") | |
subprocess.Popen([ | |
'ssh', | |
'-S', control_socket, | |
'-q', | |
'-O', 'exit', | |
jumphost], | |
stdin=subprocess.PIPE, stdout=subprocess.PIPE) | |
args = [ | |
'/usr/bin/ssh', | |
'-T', # Disable pseudo-terminal allocation | |
'-L', '{0}:{1}:{2}'.format(local_port, remote_server, remote_port), # Specify connection forwarding | |
'-M', # Master mode for connection sharing | |
'-S', control_socket, # Control socket for connection sharing | |
jumphost | |
] | |
logger.info("Establishing SSH tunnel: {}".format(' '.join(args))) | |
subprocess.Popen(args, stdin=subprocess.PIPE, stdout=subprocess.PIPE) | |
time.sleep(2) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment