OSDN Git Service

refactoring...
[ti2/ti2.git] / linkpair / collect / agent / commandrunner.py
1 # vim: tabstop=4 shiftwidth=4 softtabstop=4
2 # -*- coding: utf-8 -*-
3 #
4
5 import sys
6 import os
7 import re
8 from subprocess import Popen, PIPE
9 from socket import gethostname
10 import shlex
11 import paramiko as ssh
12 # import ssh
13 from linkpair.utils.common import CommonUtils
14
15
16 class CommandRunner(object):
17
18     '''
19     Command runner
20     '''
21
22     PEER_FOUND = 1
23
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 = {}
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 cmdline in self._command_result_cache:
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 connect_ssh(self):
55         self._ssh_conn = ssh.SSHClient()
56         self._ssh_conn.load_system_host_keys()
57
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)
66         else:
67             print "SSH connections failed"
68             sys.exit(1)
69
70     def _exec_cmd_on_ssh(self, cmdline):
71         stdin, stdout, stderr = self._ssh_conn.exec_command(cmdline)
72         result = stdout.read().splitlines()
73         return result
74
75     def set_remote_sshkey(self, remote_sshkey):
76         self._remote_sshkey = remote_sshkey
77         self._ssh_keyauth = True
78
79     def set_remote_password(self, remote_password):
80         self._remote_password = remote_password
81         self._ssh_passauth = True