view kcl/ssh.py @ 0:0f44ee073173 default tip

fake salt, initial commit
author Jeff Hammel <k0scist@gmail.com>
date Mon, 06 Feb 2017 01:10:22 +0000
parents
children
line wrap: on
line source

"""
crappy python ssh wrapper
"""

# imports
import subprocess

string = (str, unicode)


def call(command, check=True, echo=True, **kwargs):

    cmd_str = command if isinstance(command, string) else subprocess.list2cmdline(command)
    kwargs['shell'] = isinstance(command, string)
    kwargs['stdout'] = subprocess.PIPE
    kwargs['stderr'] = subprocess.PIPE
    if echo:
        print (cmd_str)
    process = subprocess.Popen(command, **kwargs)
    stdout, stderr = process.communicate()
    if check and process.returncode:
        raise subprocess.CalledProcessError(process.returncode, command, stdout)
    return process.returncode, stdout, stderr


class Ssh(object):
    """primative form of ssh session using subprocess"""

    def __init__(self, host, ssh='ssh', scp='scp', verbose=False):
        self.host = host
        self._ssh = ssh
        self._scp = scp
        self.verbose=verbose

    def command(self, command):

        # See:
        # http://unix.stackexchange.com/questions/122616/why-do-i-need-a-tty-to-run-sudo-if-i-can-sudo-without-a-password
        # http://unix.stackexchange.com/a/122618
        return [self._ssh, '-t', self.host, command]

    def sudo_command(self, command):
        return self.command('sudo ' + command)

    def call(self, command):
        returncode, output, _ = call(self.command(command),
                                     echo=self.verbose)
        return (returncode, output)

    def sudo(self, command):
        returncode, output, _ = call(self.sudo_command(command),
                                     echo=self.verbose)
        return (returncode, output)

    def scp(self, src, dest):
        """scp a file to the given host"""

        command = [self._scp,
                   src,
                   '{host}:{dest}'.format(host=self.host, dest=dest)]
        returncode, output, _ = call(command)
        return (returncode, output)