first draft to clean up TestSsh, but bug not fixed for remote qemu nodes -a sigh
[tests.git] / system / TestSsh.py
1 #this class is  used for any ssh command and
2 #also for any remote or a local command independently
3 #on which box this must be done.
4
5 import os.path
6 import utils
7
8 class TestSsh:
9     
10     # inserts a backslash before each occurence of the following chars
11     # \ " ' < > & | ; ( ) $ * ~ 
12     @staticmethod
13     def backslash_shell_specials (command):
14         result=''
15         for char in command:
16             if char in "\\\"'<>&|;()$*~":
17                 result +='\\'+char
18             else:
19                 result +=char
20         return result
21
22     # check main IP address against the provided hostname
23     @staticmethod
24     def is_local_hostname (hostname):
25         if hostname == "localhost":
26             return True
27         import socket
28         try:
29             local_ip = socket.gethostbyname(socket.gethostname())
30             remote_ip = socket.gethostbyname(hostname)
31             return local_ip==remote_ip
32         except:
33             utils.header("WARNING : something wrong in is_local_hostname with hostname=%s"%hostname)
34             return False
35
36     def __init__(self,hostname,buildname=None,key=None):
37         self.hostname=hostname
38         self.buildname=buildname
39         self.key=key
40
41
42     def is_local(self):
43         return TestSsh.is_local_hostname(self.hostname)
44      
45     # command gets run on the right box
46     def to_host(self,command):
47         if self.is_local():
48             return command
49         else:
50             return "ssh %s %s"%(self.hostname,TestSsh.backslash_shell_specials(command))
51
52     def clean_dir (self,dirname):
53         if self.is_local():
54             return 0
55         return utils.system(self.to_host("rm -rf %s"%dirname))
56
57     def mkdir (self,dirname):
58         if self.is_local():
59             return 0
60         return utils.system(self.to_host("mkdir %s"%dirname))
61
62     def run_in_buildname (self,command):
63         if self.is_local():
64             return utils.system(command)
65         ssh_command="ssh "
66         if self.key:
67             ssh_command += "-i %s.rsa "%(self.key)
68         ssh_command += "%s %s/%s"%(self.hostname,self.buildname,TestSsh.backslash_shell_specials(command))
69         return utils.system(ssh_command)
70
71     def copy (self,local_file,recursive=False):
72         if self.is_local():
73             return 0
74         command="scp "
75         if recursive: command += "-r "
76         if self.key:
77             command += "-i %s.rsa "
78         command +="%s %s:%s/%s"%(local_file,self.hostname,self.buildname,
79                                  os.path.basename(local_file) or ".")
80         return utils.system(command)
81