-#!/usr/bin/env python
+# vim: tabstop=4 shiftwidth=4 softtabstop=4
# -*- coding: utf-8 -*-
#
-__version__ = '1.1'
-
import sys
import os
import re
from subprocess import Popen, PIPE
from socket import gethostname
import shlex
-# import paramiko as ssh
-import ssh
-from linkpair.commonutils import CommonUtils
+import paramiko as ssh
+# import ssh
+from linkpair.utils.common import CommonUtils
class CommandRunner(object):
+
'''
Command runner
'''
self._remote_sshkey = ""
self._ssh_keyauth = False
self._ssh_passauth = False
+ self._ssh_conne = None
+ self._command_result_cache = {}
''' set parameters '''
- [self._ssh_username, self._ssh_hostname, self._ssh_hostport] = self._u.parse_remote_desc(remote_desc)
+ [self._ssh_username, self._ssh_hostname,
+ self._ssh_hostport] = self._u.parse_remote_desc(remote_desc)
+
+ def exec_cmd(self, cmdline, enable_cache=True):
+ if enable_cache:
+ if cmdline in self._command_result_cache:
+ return self._command_result_cache[cmdline]
- def exec_cmd(self, cmdline):
args = shlex.split(cmdline)
if self._remote_desc is not None:
result = self._exec_cmd_on_ssh(cmdline)
else:
result = Popen(args, stdout=PIPE, stderr=PIPE).stdout.readlines()
+ self._command_result_cache[cmdline] = result
return result
- def _exec_cmd_on_ssh(self, cmdline):
- sshc = ssh.SSHClient()
- sshc.load_system_host_keys()
+ def connect_ssh(self):
+ self._ssh_conn = ssh.SSHClient()
+ self._ssh_conn.load_system_host_keys()
if self._ssh_keyauth == True:
- sshc.connect(self._ssh_hostname, username=self._ssh_username,
- port=self._ssh_hostport, key_filename=self._remote_sshkey)
+ self._ssh_conn.connect(
+ self._ssh_hostname, username=self._ssh_username,
+ port=self._ssh_hostport, key_filename=self._remote_sshkey)
elif self._ssh_passauth == True:
- sshc.connect(self._ssh_hostname, username=self._ssh_username,
- port=self._ssh_hostport, password=self._remote_password)
+ self._ssh_conn.connect(
+ self._ssh_hostname, username=self._ssh_username,
+ port=self._ssh_hostport, password=self._remote_password)
else:
print "SSH connections failed"
sys.exit(1)
- stdin, stdout, stderr = sshc.exec_command(cmdline)
+ def _exec_cmd_on_ssh(self, cmdline):
+ stdin, stdout, stderr = self._ssh_conn.exec_command(cmdline)
result = stdout.read().splitlines()
return result
-
+
def set_remote_sshkey(self, remote_sshkey):
self._remote_sshkey = remote_sshkey
self._ssh_keyauth = True
def set_remote_password(self, remote_password):
self._remote_password = remote_password
self._ssh_passauth = True
-
-
\ No newline at end of file