1 # vim: tabstop=4 shiftwidth=4 softtabstop=4
2 # -*- coding: utf-8 -*-
10 from subprocess import Popen, PIPE
11 from socket import gethostname
13 import paramiko as ssh
15 from linkpair.utils.common import CommonUtils
18 class CommandRunner(object):
25 def __init__(self, remote_desc):
26 self._u = CommonUtils()
27 self._remote_desc = remote_desc
28 self._ssh_username = ""
29 self._ssh_hostname = ""
30 self._ssh_hostport = 22
31 self._remote_password = ""
32 self._remote_sshkey = ""
33 self._ssh_keyauth = False
34 self._ssh_passauth = False
35 self._command_result_cache = {}
37 ''' set parameters '''
38 [self._ssh_username, self._ssh_hostname,
39 self._ssh_hostport] = self._u.parse_remote_desc(remote_desc)
41 def exec_cmd(self, cmdline, enable_cache=True):
43 if self._command_result_cache.has_key(cmdline):
44 return self._command_result_cache[cmdline]
46 args = shlex.split(cmdline)
47 if self._remote_desc is not None:
48 result = self._exec_cmd_on_ssh(cmdline)
50 result = Popen(args, stdout=PIPE, stderr=PIPE).stdout.readlines()
51 self._command_result_cache[cmdline] = result
54 def _exec_cmd_on_ssh(self, cmdline):
55 sshc = ssh.SSHClient()
56 sshc.load_system_host_keys()
58 if self._ssh_keyauth == True:
59 sshc.connect(self._ssh_hostname, username=self._ssh_username,
60 port=self._ssh_hostport, key_filename=self._remote_sshkey)
61 elif self._ssh_passauth == True:
62 sshc.connect(self._ssh_hostname, username=self._ssh_username,
63 port=self._ssh_hostport, password=self._remote_password)
65 print "SSH connections failed"
68 stdin, stdout, stderr = sshc.exec_command(cmdline)
69 result = stdout.read().splitlines()
72 def set_remote_sshkey(self, remote_sshkey):
73 self._remote_sshkey = remote_sshkey
74 self._ssh_keyauth = True
76 def set_remote_password(self, remote_password):
77 self._remote_password = remote_password
78 self._ssh_passauth = True