Skip to content

Instantly share code, notes, and snippets.

@adorsk
Created September 26, 2016 19:10
Show Gist options
  • Save adorsk/d63df7c64f58a05733ceb265cf2f96e8 to your computer and use it in GitHub Desktop.
Save adorsk/d63df7c64f58a05733ceb265cf2f96e8 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
import sys
import os
import string
import random
import subprocess
import multiprocessing
class NotAuthorizedException(Exception): pass
class SshSharedSocketClient():
def __init__(self, host=None, control_socket=None, control_dir=None):
self.host = host
if not control_socket:
if not control_dir:
control_dir = os.path.join(os.environ['HOME'],
'.ssh_control_sockets')
control_dir = self._ensure_dir(control_dir)
socket_id = ''.join([random.choice(string.ascii_letters)
for i in range(10)])
control_socket = os.path.join(control_dir, socket_id)
self.control_socket = control_socket
self.stdout = ''
def _ensure_dir(self, _dir):
if not os.path.isdir(_dir):
os.makedirs(_dir)
return _dir
def connect(self):
if not self._is_authorized():
self.master_ssh_process = multiprocessing.Process(
target=subprocess.run,
args=(['ssh', '-fNMS', self.control_socket, self.host],),
)
self.master_ssh_process.start()
self.master_ssh_process.join()
def _is_authorized(self, check=False):
completed_process = self._run_ssh_control_cmd('check')
return (completed_process.returncode == 0)
def disconnect(self):
if self._is_authorized():
self._run_ssh_control_cmd('exit')
def _run_ssh_control_cmd(self, control_cmd, check=False):
return subprocess.run(
['ssh', '-S', self.control_socket, '-O', control_cmd, 'go'],
stdout=subprocess.PIPE, stderr=subprocess.PIPE, check=check)
def run(self, command):
self._ensure_authorized()
return subprocess.run(
['ssh', '-S', self.control_socket, 'go', command],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE
)
def scp(self, src, dst, flags=''):
self._ensure_authorized()
self.cmd(['scp','-o controlpath=' + self.control_socket,
src, flags, 'go:' + dst])
def _ensure_authorized(self):
self._is_authorized(check=True)
if __name__ == '__main__':
if len(sys.argv)>1:
host=sys.argv[1]
client = SshSharedSocketClient(host)
client.connect()
print(client.run('uptime').stdout)
print(client.run('date').stdout)
client.disconnect()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment