OSDN Git Service

069eadee3d67b6b08d08f4fdc6a008ce896d1ea1
[ti2/ti2.git] / linkpair / collect / agent / commandrunner.py
1 # vim: tabstop=4 shiftwidth=4 softtabstop=4
2 # -*- coding: utf-8 -*-
3 #
4
5 __version__ = '1.1'
6
7 import sys
8 import os
9 import re
10 from subprocess import Popen, PIPE
11 from socket import gethostname
12 import shlex
13 import paramiko as ssh
14 # import ssh
15 from linkpair.utils.common import CommonUtils
16
17
18 class CommandRunner(object):
19     '''
20     Command runner
21     '''
22
23     PEER_FOUND = 1
24
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 = {}
36
37         ''' set parameters '''
38         [self._ssh_username, self._ssh_hostname,
39             self._ssh_hostport] = self._u.parse_remote_desc(remote_desc)
40
41     def exec_cmd(self, cmdline, enable_cache=True):
42         if enable_cache:
43             if self._command_result_cache.has_key(cmdline):
44                 return self._command_result_cache[cmdline]
45
46         args = shlex.split(cmdline)
47         if self._remote_desc is not None:
48             result = self._exec_cmd_on_ssh(cmdline)
49         else:
50             result = Popen(args, stdout=PIPE, stderr=PIPE).stdout.readlines()
51         self._command_result_cache[cmdline] = result
52         return result
53         
54     def _exec_cmd_on_ssh(self, cmdline):
55         sshc = ssh.SSHClient()
56         sshc.load_system_host_keys()
57
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)
64         else:
65             print "SSH connections failed"
66             sys.exit(1)
67
68         stdin, stdout, stderr = sshc.exec_command(cmdline)
69         result = stdout.read().splitlines()
70         return result
71
72     def set_remote_sshkey(self, remote_sshkey):
73         self._remote_sshkey = remote_sshkey
74         self._ssh_keyauth = True
75
76     def set_remote_password(self, remote_password):
77         self._remote_password = remote_password
78         self._ssh_passauth = True