1 # vim: tabstop=4 shiftwidth=4 softtabstop=4
2 # -*- coding: utf-8 -*-
8 from subprocess import Popen, PIPE
9 from socket import gethostname
11 import paramiko as ssh
13 from linkpair.utils.common import CommonUtils
16 class CommandRunner(object):
24 def __init__(self, remote_desc):
25 self._u = CommonUtils()
26 self._remote_desc = remote_desc
27 self._ssh_username = ""
28 self._ssh_hostname = ""
29 self._ssh_hostport = 22
30 self._remote_password = ""
31 self._remote_sshkey = ""
32 self._ssh_keyauth = False
33 self._ssh_passauth = False
34 self._ssh_conne = None
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 cmdline in self._command_result_cache:
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 connect_ssh(self):
55 self._ssh_conn = ssh.SSHClient()
56 self._ssh_conn.load_system_host_keys()
58 if self._ssh_keyauth == True:
59 self._ssh_conn.connect(
60 self._ssh_hostname, username=self._ssh_username,
61 port=self._ssh_hostport, key_filename=self._remote_sshkey)
62 elif self._ssh_passauth == True:
63 self._ssh_conn.connect(
64 self._ssh_hostname, username=self._ssh_username,
65 port=self._ssh_hostport, password=self._remote_password)
67 print "SSH connections failed"
70 def _exec_cmd_on_ssh(self, cmdline):
71 stdin, stdout, stderr = self._ssh_conn.exec_command(cmdline)
72 result = stdout.read().splitlines()
75 def set_remote_sshkey(self, remote_sshkey):
76 self._remote_sshkey = remote_sshkey
77 self._ssh_keyauth = True
79 def set_remote_password(self, remote_password):
80 self._remote_password = remote_password
81 self._ssh_passauth = True