Created
June 22, 2012 18:22
-
-
Save rossdylan/2974370 to your computer and use it in GitHub Desktop.
pbs like functionality using paramiko
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 paramiko | |
from functools import partial | |
class SuperParamiko(object): | |
""" | |
usage: | |
>> ssh = SuperParamiko("hostname", "username") | |
>> ssh.ls() | |
>> ssh.git("pull") | |
""" | |
def __init__(self, host, username, password=None, port=22): | |
self.session = paramiko.SSHClient() | |
self.session.set_missing_host_key_policy( | |
paramiko.AutoAddPolicy()) | |
if password == None: | |
self.session.connect(host, username=username, port=port) | |
else: | |
self.session.connect( | |
host, | |
username=username, | |
password=password, | |
port=port | |
) | |
def generate_command_string(self, cmd, *args, **kwargs): | |
command = [cmd,] | |
command.extend(list(args)) | |
for key, arg in kwargs.items(): | |
if arg == None or arg == "": | |
command.append("--{0}".format(key)) | |
else: | |
command.append("--{0} {1}".format(key, arg)) | |
return ' '.join(command) | |
def ssh_func_wrapper(self, cmd, *args, **kwargs): | |
command = self.generate_command_string(cmd, *args, **kwargs) | |
stdin, stdout, stderr = self.session.exec_command(command) | |
errors = stderr.readlines() | |
if errors != []: | |
raise Exception(errors) | |
else: | |
return map(lambda s: s.strip(), stdout.readlines()) | |
def __getattr__(self, name): | |
return partial(self.ssh_func_wrapper, name) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment