blob: 4cd7666e612466c1816aa8bbf19e754746669c48 [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 Karthickec1dde02016-10-06 13:52:25 -070025 self.client.connect(self.host, username = self.user, password = self.password,
A R Karthick9313b762016-11-07 13:14:35 -080026 key_filename = self.key_file, timeout=timeout, port = self.port)
A R Karthickec1dde02016-10-06 13:52:25 -070027 except:
28 log.error('Unable to connect to test host %s' %self.host)
29 return False, None
30
31 channel = self.client.get_transport().open_session()
32 channel.exec_command(cmd)
A R Karthick9313b762016-11-07 13:14:35 -080033 if channel.exit_status_ready():
34 status = channel.recv_exit_status()
35 else:
36 status = 0
A R Karthickec1dde02016-10-06 13:52:25 -070037 output = None
38 st = status == 0
39 if st:
40 output = ''
41 while True:
42 data = channel.recv(4096)
43 if data:
44 output += data
45 else:
46 break
47 channel.close()
48 return st, output
49
50if __name__ == '__main__':
51 agent = SSHTestAgent(user = 'ubuntu', password = 'ubuntu')
52 cmds = ('docker images', 'docker ps')
53 for cmd in cmds:
54 st, output = agent.run_cmd(cmd)
55 print('Command \"%s\" returned with status: %s' %(cmd, st))
56 if st:
57 print('%s\n' %output)