blob: 82f20ad2fbf7e4eaf7f915393f044f5d2aa2acdc [file] [log] [blame]
A R Karthickec1dde02016-10-06 13:52:25 -07001import os, sys
2from paramiko import SSHClient, WarningPolicy, AutoAddPolicy
A R Karthickec1dde02016-10-06 13:52:25 -07003from scapy.all import *
4
5class SSHTestAgent(object):
6 key_file = os.getenv('SSH_KEY_FILE', None)
A R Karthick19aaf5c2016-11-09 17:47:57 -08007 host = os.getenv('CORD_TEST_HOST', '172.17.0.1')
8 hosts_file = os.path.join(os.getenv('HOME'), '.ssh', 'known_hosts')
A R Karthickec1dde02016-10-06 13:52:25 -07009 user = 'ubuntu'
10 password = None
11
A R Karthick9313b762016-11-07 13:14:35 -080012 def __init__(self, host = host, user = user, password = password, port = 22):
13 self.host = host
A R Karthickec1dde02016-10-06 13:52:25 -070014 self.user = user
15 self.password = password
A R Karthick9313b762016-11-07 13:14:35 -080016 self.port = port
A R Karthickec1dde02016-10-06 13:52:25 -070017 self.client = SSHClient()
A R Karthickec1dde02016-10-06 13:52:25 -070018 self.client.set_missing_host_key_policy(AutoAddPolicy())
19
20 def run_cmd(self, cmd, timeout = 5):
21 """Run the command on the test host"""
A R Karthick19aaf5c2016-11-09 17:47:57 -080022 host_remove = 'ssh-keygen -f "%s" -R [%s]:8101' %(self.hosts_file, self.host)
A R Karthickec1dde02016-10-06 13:52:25 -070023 try:
A R Karthick19aaf5c2016-11-09 17:47:57 -080024 os.system(host_remove)
A R Karthickd0a334d2016-11-10 17:47:08 -080025 except: pass
26
27 try:
A R Karthickec1dde02016-10-06 13:52:25 -070028 self.client.connect(self.host, username = self.user, password = self.password,
A R Karthick9313b762016-11-07 13:14:35 -080029 key_filename = self.key_file, timeout=timeout, port = self.port)
A R Karthickec1dde02016-10-06 13:52:25 -070030 except:
31 log.error('Unable to connect to test host %s' %self.host)
32 return False, None
33
34 channel = self.client.get_transport().open_session()
35 channel.exec_command(cmd)
A R Karthick9313b762016-11-07 13:14:35 -080036 if channel.exit_status_ready():
37 status = channel.recv_exit_status()
38 else:
39 status = 0
A R Karthickec1dde02016-10-06 13:52:25 -070040 output = None
41 st = status == 0
42 if st:
43 output = ''
44 while True:
45 data = channel.recv(4096)
46 if data:
47 output += data
48 else:
49 break
50 channel.close()
A R Karthickd0a334d2016-11-10 17:47:08 -080051 self.client.close()
A R Karthickec1dde02016-10-06 13:52:25 -070052 return st, output
53
54if __name__ == '__main__':
55 agent = SSHTestAgent(user = 'ubuntu', password = 'ubuntu')
56 cmds = ('docker images', 'docker ps')
57 for cmd in cmds:
58 st, output = agent.run_cmd(cmd)
59 print('Command \"%s\" returned with status: %s' %(cmd, st))
60 if st:
61 print('%s\n' %output)