I have a code where i am executing a command on remote Linux machine and reading the output using Paramiko. The code def looks like this:
ssh = paramiko.SSHC
To have paramiko commands behave like a subprocess.call you may use this piece of code (tested with python-3.5 and paramiko-2.1.1):
#!/usr/bin/env /usr/bin/python3
import os
import sys
from paramiko import SSHClient, AutoAddPolicy
from socket import getfqdn
class SecureSHell(object):
reuser = os.environ['USER']
remote = ''
def __init__(self, *args, **kwargs):
for arg in args:
if hasattr(self, arg):
setattr(self, arg, True)
for (key, val) in kwargs.items():
if hasattr(self, key):
setattr(self, key, val)
@staticmethod
def _ssh_(remote, reuser, port=22):
if '@' in remote:
_reuser, remote = remote.split('@')
_fqdn = getfqdn(remote)
remote = _fqdn if _fqdn else remote
ssh = SSHClient()
ssh.set_missing_host_key_policy(AutoAddPolicy())
ssh.connect(remote, int(port), username=reuser)
return ssh
def call(self, cmd, remote=None, reuser=None):
remote = remote if remote else self.remote
reuser = reuser if reuser else self.reuser
ssh = self._ssh_(remote, reuser)
chn = ssh.get_transport().open_session()
chn.settimeout(10800)
chn.exec_command(cmd)
while not chn.exit_status_ready():
if chn.recv_ready():
och = chn.recv(1024)
while och:
sys.stdout.write(och.decode())
och = chn.recv(1024)
if chn.recv_stderr_ready():
ech = chn.recv_stderr(1024)
while ech:
sys.stderr.write(och.decode())
ech = chn.recv_stderr(1024)
return int(chn.recv_exit_status())
ssh = SecureSHell(remote='example.com', user='d0n')
ssh.call('find')