A R Karthick | ec1dde0 | 2016-10-06 13:52:25 -0700 | [diff] [blame] | 1 | import os, sys |
| 2 | from paramiko import SSHClient, WarningPolicy, AutoAddPolicy |
| 3 | from CordTestServer import CORD_TEST_HOST |
| 4 | from scapy.all import * |
| 5 | |
| 6 | class SSHTestAgent(object): |
| 7 | key_file = os.getenv('SSH_KEY_FILE', None) |
| 8 | host = os.getenv('CORD_TEST_HOST', CORD_TEST_HOST) |
| 9 | user = 'ubuntu' |
| 10 | password = None |
| 11 | |
| 12 | def __init__(self, user = user, password = password): |
| 13 | self.user = user |
| 14 | self.password = password |
| 15 | self.client = SSHClient() |
| 16 | self.client.load_system_host_keys() |
| 17 | self.client.set_missing_host_key_policy(AutoAddPolicy()) |
| 18 | |
| 19 | def run_cmd(self, cmd, timeout = 5): |
| 20 | """Run the command on the test host""" |
| 21 | try: |
| 22 | self.client.connect(self.host, username = self.user, password = self.password, |
| 23 | key_filename = self.key_file, timeout=timeout) |
| 24 | except: |
| 25 | log.error('Unable to connect to test host %s' %self.host) |
| 26 | return False, None |
| 27 | |
| 28 | channel = self.client.get_transport().open_session() |
| 29 | channel.exec_command(cmd) |
| 30 | status = channel.recv_exit_status() |
| 31 | output = None |
| 32 | st = status == 0 |
| 33 | if st: |
| 34 | output = '' |
| 35 | while True: |
| 36 | data = channel.recv(4096) |
| 37 | if data: |
| 38 | output += data |
| 39 | else: |
| 40 | break |
| 41 | channel.close() |
| 42 | return st, output |
| 43 | |
| 44 | if __name__ == '__main__': |
| 45 | agent = SSHTestAgent(user = 'ubuntu', password = 'ubuntu') |
| 46 | cmds = ('docker images', 'docker ps') |
| 47 | for cmd in cmds: |
| 48 | st, output = agent.run_cmd(cmd) |
| 49 | print('Command \"%s\" returned with status: %s' %(cmd, st)) |
| 50 | if st: |
| 51 | print('%s\n' %output) |