def test_000_check_time_stamp_from_PTOP_log_and_syslog(self): ptop='' sysl='' ptop_ltst='' client = paramiko.SSHClient() client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) privatekeyfile = os.path.expanduser('~/.ssh/id_rsa') mykey = paramiko.RSAKey.from_private_key_file(privatekeyfile) client.connect(config.grid_vip, username='******', pkey = mykey) data="ls -ltr /var/log/ptop-* \n" stdin, stdout, stderr = client.exec_command(data) stdout=stdout.readlines() print('\n') ptop_ltst=stdout[-1] ptop_ltst=(ptop_ltst.split(' ')[-1]) print("PTOP log: "+ptop_ltst) client.close() client = paramiko.SSHClient() client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) privatekeyfile = os.path.expanduser('~/.ssh/id_rsa') mykey = paramiko.RSAKey.from_private_key_file(privatekeyfile) client.connect(config.grid_vip, username='******', pkey = mykey) data="grep TIME "+ptop_ltst+"\n" stdin, stdout, stderr = client.exec_command(data) res=stdout.readline() hour=res.split(' ')[-1] print("PTOP time stamp: "+res+"->"+res.split(' ')[-2]+"T"+hour.split(':')[-3]) ptop=res.split(' ')[-2]+"T"+hour.split(':')[-3] client.close() client = paramiko.SSHClient() client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) privatekeyfile = os.path.expanduser('~/.ssh/id_rsa') mykey = paramiko.RSAKey.from_private_key_file(privatekeyfile) client.connect(config.grid_vip, username='******', pkey = mykey) data="grep TIME /var/log/messages\n" stdin, stdout, stderr = client.exec_command(data) res=stdout.readlines() hour='' for i in res: if ptop in i: hour=i hours=hour.split(' ')[0] sysl=hours.split(':')[-0] print("Sys time stamp : "+hour+"->"+sysl) client.close() if sysl==ptop: print("Success : The time stamp from PTOP log and syslog matches") assert True else: print("Failure : The time stamp from PTOP log and syslog matches") assert False
def killVLCStream(self): """ Sends a command to the pi to kill streaming """ try: print("Connecting to streaming pi") client = SSHClient() client.set_missing_host_key_policy(AutoAddPolicy) client.connect('192.168.1.69', port=22, username='******', password='******') client.exec_command('pkill vlc') print("Killed pi's vlc stream") except Exception as e: print("Error sending commands to pi: ", str(e))
def test_007_Revert_back_the_changes(self): print("Revert back the changes") client = paramiko.SSHClient() client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) privatekeyfile = os.path.expanduser('~/.ssh/id_rsa') mykey = paramiko.RSAKey.from_private_key_file(privatekeyfile) client.connect(config.grid_vip, username='******', pkey = mykey) data="mount -o remount,rw /" stdin, stdout, stderr = client.exec_command(data) stdout=stdout.read() print(type(stdout)) client.close() child=pexpect.spawn("ssh root@"+config.grid_vip, maxread=4000) try: child.expect("-bash-4.0#",timeout=100) child.sendline("scp root@"+config.client_vip+":/import/qaddi/API_Automation/WAPI_PyTest/suites/customer_bug_automation/fastpath_control /infoblox/one/bin/fastpath_control") child.expect('password:',timeout=100) child.sendline("infoblox") child.expect("-bash-4.0#") child.sendline("exit") print("\nSuccess: Revert back the changes") child.close() assert True except Exception as e: child.close() print (e) print("Failure: Revert back the changes") assert False
def startVLCStream(self): """ Executes the streaming command on the pi and then begins stream """ try: print("Connecting to streaming pi") client = SSHClient() client.set_missing_host_key_policy(AutoAddPolicy) client.connect('192.168.1.69', port=22, username='******', password='******') # If the pi is already streaming, will not start another streaming process client.exec_command( 'if pgrep vlc; then echo "Streaming already started"; else ./vlcTest.sh; fi' ) except Exception as e: print("Error sending commands to pi: ", str(e)) # Delay to allow the streaming to start time.sleep(1) try: # Attempt to start streaming print("Starting VLC stream capture") timenow = datetime.datetime.now().strftime('%m-%w-%y_%H-%M-%S') print('Saving stream to StreamedVideo folder with name: ' + timenow + '.mp4') self.saveStreamThread = threading.Thread(target=lambda: os.system( 'vlc.exe rtsp://' + '192.168.1.69' + ':8080/ --sout=file/mp4:' + 'StreamedVideo\\' # Folder + timenow + '.mp4')) # Filename self.displayStreamThread = threading.Thread( target=lambda: os.system('vlc.exe rtsp://' + '192.168.1.69' + ':8080/')) self.saveStreamThread.start() time.sleep(.1) self.displayStreamThread.start() except Exception as e: print("Error beginning VLC Stream: ", str(e))
def test_000_check_status_of_DCA_and_ATP(self): client = paramiko.SSHClient() client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) privatekeyfile = os.path.expanduser('~/.ssh/id_rsa') mykey = paramiko.RSAKey.from_private_key_file(privatekeyfile) client.connect(config.grid_vip, username='******', pkey = mykey) data="cat /infoblox/var/fastpath_status\n" stdin, stdout, stderr = client.exec_command(data) stdout=stdout.read() print(stdout) if 'dca_status: running' in stdout and 'atp_status: running' in stdout: print("Success : Status of DCA and ATP are rightly updated for fastpath") print("Mount the RP") data="mount -o remount,rw /" stdin, stdout, stderr = client.exec_command(data) stdout=stdout.read() print(type(stdout)) client.close() assert True else: print("Failure : Status of DCA and ATP are rightly updated for fastpath") client.close() assert False
def test_001_validating_sppc_present_in_dns_view(self): client = paramiko.SSHClient() client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) privatekeyfile = os.path.expanduser('~/.ssh/id_rsa') mykey = paramiko.RSAKey.from_private_key_file(privatekeyfile) client.connect(config.grid_vip, username='******', pkey=mykey) data = "cat /infoblox/var/named_conf/dns_cache_acceleration.json" stdin, stdout, stderr = client.exec_command(data) stdout = stdout.read() print(stdout) data = json.loads(stdout) if "sppc" in data["dca_config"]["1"]: print("Success : DNS sppc present in First dns view") assert True else: print("Failed: DNS sppc present in more than one dns views") assert False
def test_005_check_fp_failure_flag(self): client = paramiko.SSHClient() client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) privatekeyfile = os.path.expanduser('~/.ssh/id_rsa') mykey = paramiko.RSAKey.from_private_key_file(privatekeyfile) client.connect(config.grid_vip, username='******', pkey = mykey) stdin, stdout, stderr = client.exec_command("ls /infoblox/var/flags") result=stdout.read() print(len(result)) print(result) if 'fp_failure' in result: print("Success: fp_failure flag is part of /infoblox/var/flags directory") assert True else: print("Failue: fp_failure flag is part of /infoblox/var/flags directory") assert False client.close()
def org(ssh): here = os.path.dirname(__file__) with ssh() as client: sftp = client.open_sftp() sftp.put(os.path.join(here, 'setup_org.py'), '/tmp/setup_org.py') sftp.put( os.path.join(here, '..', 'accounting', 'test', 'swish.crt.pem'), '/tmp/swish.crt.pem') stdin, stdout, stderr = client.exec_command( 'PYTHONPATH=/root/accounting ' '/root/accounting/bin/client.py ' '/tmp/setup_org.py') data = json.load(stdout) return Container(id=data['org'], name=data['orgname'], pgnum=data['pgnum'], payson_provider=data['payson_provider'], swish_provider=data['swish_provider'], product=data['product'])
def test_006_validation(self): ip_list = [] # #print(os.popen("grid_info "+config.grid_vip).readlines()) # for i in range(1,6): # ip_list.append(os.popen("grid_info "+config.grid_vip).readlines()[i].strip().split(' ')[-5]) # ip_list.append((os.popen("grid_info "+config.grid_vip).readlines()[4].split(' '))[-6]) # while("" in ip_list) : # ip_list.remove("") ip_list.append(config.grid_vip) ip_list.append(config.grid_member1_vip) ip_list.append(config.grid_member2_vip) print(ip_list) for i in ip_list: print(i) print("====================") client = paramiko.SSHClient() client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) privatekeyfile = os.path.expanduser('~/.ssh/id_rsa') mykey = paramiko.RSAKey.from_private_key_file(privatekeyfile) client.connect(i, username='******', pkey=mykey) data = "grep -icw 'DTC*initialization' /var/log/messages" stdin, stdout, stderr = client.exec_command(data) stdout = stdout.read() print("output ", stdout) if '0' in stdout: print("Success") client.close() assert True else: print("Failed") client.close() continue assert False
def _gerrit_feedback(_args, _errors, _warnings, _blockage, message): # pylint: disable = too-many-locals import json # work around from https://github.com/paramiko/paramiko/pull/861 # for bug https://github.com/paramiko/paramiko/issues/1068 when # GSSAPI is installed by Ansible sys.modules['gssapi'] = None import paramiko.client if _args.gerrit_from_jenkins: logging.info("Getting gerrit info from Jenkins environment") scheme = os.environ['GERRIT_SCHEME'] if scheme != 'ssh': logging.error('%s: GERRIT_SCHEME unsupported', scheme) host = os.environ['GERRIT_HOST'] port = int(os.environ['GERRIT_PORT']) change_number = int(os.environ['GERRIT_CHANGE_NUMBER']) patchset_number = int(os.environ['GERRIT_PATCHSET_NUMBER']) ssh_user = os.environ['SSH_USER'] else: logging.info("Getting gerrit info from cmdline") host = _args.gerrit_ssh_host port = int(_args.gerrit_ssh_port) change_number = _args.gerrit_change_number patchset_number = _args.gerrit_patchset_number ssh_user = _args.gerrit_ssh_user params = {} if ssh_user: params['username'] = ssh_user client = paramiko.client.SSHClient() client.load_system_host_keys() client.connect(host, port, **params) data = dict(labels={}, ) if _warnings > 0: data['labels']['Code-Review'] = -1 if _errors == 0: data['labels']['Verified'] = 1 else: data['labels']['Verified'] = -1 if _blockage > 0: # No verification if missing tools print(("W: 'Verified %d' vote skipped as some tools are missing " "and can't check it all" % data['labels']['Verified'])) del data['labels']['Verified'] if message and message != "": if _args.url: cut_msg = "...\n<cut oversized report, more at %s>" % _args.url else: cut_msg = "...\n<cut oversized report>" cut_len = len(cut_msg) if len(message) > _args.gerrit_message_limit: message = message[:_args.gerrit_message_limit - cut_len] \ + cut_msg data['message'] = message stdin, stdout, stderr = client.exec_command( 'gerrit review --json %d,%d' % (change_number, patchset_number), bufsize=-1) stdin.write(json.dumps(data)) stdin.flush() stdin.channel.shutdown_write() output = str(stdout.read(), encoding = 'utf-8') \ + str(stderr.read(), encoding = 'utf-8') if output: logging.error("gerrit review output: %s", output)
def run_command(cmd, client): stdin, stdout, stderr = client.exec_command(cmd) ret = stdout.channel.recv_exit_status() return (ret, stdout.readlines(), stderr.readlines())
# cf. https://github.com/PyCQA/bandit/blob/d5f8fa0d89d7b11442fc6ec80ca42953974354c8/examples/paramiko_injection.py import paramiko from paramiko import client client = paramiko.client.SSHClient() # this is safe # ok client.connect('somehost') # this is not safe # ruleid:paramiko-exec-command client.exec_command('something; really; unsafe') client2 = client.SSHClient() client2.connect("somewhere-out-there") # ruleid:paramiko-exec-command client2.exec_command("ls -r /")
current_os = platform.system().lower() if current_os == "windows": param = "-n" output = "\Desktop\output.txt" homedir = os.environ['USERPROFILE'] else: param = "-c" output = "/Desktop/output.txt" homedir = os.environ['HOME'] for ip in dump: print(ip) client = SSHClient() client.set_missing_host_key_policy(AutoAddPolicy()) client.connect(ip, username='******', password='******') stdin, stdout, stderr = client.exec_command(f'ping -c 3 x.x.x.x') res = f'STDOUT: |{ip}| {stdout.read().decode("utf8")}' print(f'STDERR: {stderr.read().decode("utf8")}') file = open(f'hotexamples_com/Desktop/output.txt', 'a') file.write(res) file.close() # Because they are file objects, they need to be closed stdin.close() stdout.close() stderr.close() # Close the client itself client.close()
import sys import Crypto import paramiko.client as client sys.modules['Crypto'] = Crypto hostName = "10.13.254.40" uName = "Pi" pWord = "Raspberry" client = client.SSHClient() client.load_system_host_keys() client.connect(hostname=hostName, port=22, username=uName, password=pWord) response = client.exec_command('ls') print response