def key_push(self): """Deploys public key to remote machine""" with open(self.public_key_file) as key_file: self.public_key = key_file.readline() deploy_client = paramiko.SSHClient() deploy_client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) deploy_client.connect(hostname=self.host, username=self.user_name, password=self.user_pass, port=self.port) deploy_client.exec_command('mkdir -p ~/.ssh/') deploy_client.exec_command('echo "%s" > ~/.ssh/authorized_keys' % self.public_key) deploy_client.exec_command('chmod 644 ~/.ssh/authorized_keys') deploy_client.exec_command('chmod 700 ~/.ssh/') deploy_client.close() # logger.debug(command) _, stdout, stderr = deploy_client.exec_command(com) stderr = stderr.read() if stderr != '': client.close() logger.error(stderr) return False deploy_client.close() return True
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 checkhostSSHStatus(self, HOST, USER, PASS): client = paramiko.SSHClient() client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) try: client.connect(HOST, username=USER, password=PASS, timeout=10) print "SSH connection to %s established" % HOST client.close() print "Logged out of device %s" % HOST return "SSH established successfully" except: return "SSH failed"
def stream_logs(self, colorize: bool = True): clients = self.connect() # First, establish connections to the workers. channels = {} for name, client in clients.items(): transport = client.get_transport() channel = transport.open_session(timeout=1) channel.get_pty() channel.exec_command("journalctl -o cat -f -u thor-worker.service") channel.settimeout(0.05) stdout = channel.makefile("r", 4096) channels[name] = stdout # Set up pretty colors, if requested. if colorize: printer = ColorizedPrinter(list(clients.keys())) else: printer = PlainPrinter() # Loop over the open connections, printing output as we get it. while True: # Keep track of any connections that appear to be closed. We should # remove them from the list that we loop over. closed = set() for instance, stdout in channels.items(): # If any channel greedily emits at least 1024 lines, then pause # and move on to other connections to give them a chance to spam # us too. i = 0 while i < 1024: try: line = stdout.readline()[:-1] i += 1 printer.print(instance, line) except socket.timeout: # Wait for more input - exit the loop. break except OSError: # Closed - exit the loop. closed.add(instance) break # Clean up and close channels to any commands that exited. for closed_instance in closed: client = clients[closed_instance] client.close() clients.pop(closed_instance) if len(clients) == 0: return
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 test_004_check_updated_status_of_DCA_and_ATP(self): sleep(10) 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: failure' in stdout and 'atp_status: failure' in stdout : print("Success : Status of DCA and ATP are rightly updated for fastpath") else: print("Failure : Status of DCA and ATP are rightly updated for fastpath") client.close() assert False
def removing_created_keys(self): """Removes created keys""" removing_client = paramiko.SSHClient() removing_client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) removing_client.connect(hostname=self.host, username=self.user_name, password=self.user_pass, port=self.port) removing_client.exec_command('rm ~/.ssh/authorized_keys') removing_client.close() # logger.debug(command) _, stdout, stderr = deploy_client.exec_command(com) stderr = stderr.read() if stderr != '': client.close() logger.error(stderr) return False deploy_client.close() return True
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 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 release_client(client): client.close()
def writeall(sock): count = 0 while True: data = sock.recv(9999).decode('utf8') file.write(data + '\n') if not data or not ON: sys.stdout.write("\r\n*** Done ***\r\n\r\n") sys.stdout.flush() file.close() chan.close() client.close() break #strip non useful info if count <= 1: data = data[400:] count += 1 if str(data).startswith('debian@beaglebone:~$'): data = str(data).replace( 'debian@beaglebone:~$ python3 bb.py', ' ') if str(data).startswith('python3'): data = str(data).replace('python3 bb.py', ' ') if start_parsing: # Parse the sensor values if 'Sensor' in str(data): #change the box color to red to indicate warning if float(data[16:19]) > 1.0: box1["bg"] = "#fb9898" #light red box1["fg"] = "black" box1.insert(END, "") box1.delete(1.0, END) box1.insert('1.0', data[16:19]) # if float(data[20:23]) > 1.0: box2["bg"] = "#fb9898" #light red box2["fg"] = "black" box2.insert(END, "") box2.delete(1.0, END) box2.insert("1.0", data[20:23]) # if float(data[24:27]) > 1.0: box3["bg"] = "#fb9898" #light red box3["fg"] = "black" box3.insert(END, "") box3.delete(1.0, END) box3.insert("1.0", data[24:27]) # if float(data[28:31]) > 1.0: box4["bg"] = "#fb9898" #light red box4["fg"] = "black" box4.insert(END, "") box4.delete(1.0, END) box4.insert("1.0", data[28:31]) # if float(data[32:35]) > 1.0: box5["bg"] = "#fb9898" #light red box5["fg"] = "black" box5.insert(END, "") box5.delete(1.0, END) box5.insert("1.0", data[32:35]) # if float(data[36:39]) > 1.0: box6["bg"] = "#fb9898" #light red box6["fg"] = "black" box6.insert(END, "") box6.delete(1.0, END) box6.insert("1.0", data[36:39]) # ''' box7.delete(1.0, END) box7.insert("1.0",data[40:43]) # box8.delete(1.0, END) box8.insert("1.0",data[44:47]) # box9.delete(1.0, END) box9.insert("1.0",data[40:43]) # box10.delete(1.0, END) box10.insert("1.0",data[44:47]) # box11.delete(1.0, END) box11.insert("1.0",data[48:51]) # box12.delete(1.0, END) box12.insert("1.0",data[52:55]) # box13.delete(1.0, END) box13.insert("1.0",data[56:59]) # box14.delete(1.0, END) box14.insert("1.0",data[60:63]) # box15.delete(1.0, END) box15.insert("1.0",data[64:67]) # box16.delete(1.0, END) box16.insert("1.0",data[68:71]) ''' if 'Sensor' in str(data): continue output.insert("end-1c", data) output.see("end") #for testing #print(data, end= '\r', flush= True) if not ON: return "Exiting GUI"
def init_paramiko(): # needed parameters for connection port = 22 hostname = 'beaglebone' username = '******' password = '******' ############################## #determine if we are in linux or windows try: import termios import tty has_termios = True except ImportError: has_termios = False try: global chan client = paramiko.SSHClient() client.load_system_host_keys() client.set_missing_host_key_policy(paramiko.WarningPolicy()) print("*** Connecting...") client.connect(hostname, port, username, password) chan = client.invoke_shell() print(repr(client.get_transport())) output.insert("end-1c", '*** SSH Connection to BB_AI stablished ***\n') chan.send('python3 bb.py\n') print("*** SSH Connection to BB_AI stablished!\n") #creating the log file #if the file exist if path.exists("log_gui.txt"): #then append to the existing file file = open("log_gui.txt", "+a") else: #create a new one file = open("log_gui.txt", "+w") ########################################################################### if has_termios: import select oldtty = termios.tcgetattr(sys.stdin) try: tty.setraw(sys.stdin.fileno()) tty.setcbreak(sys.stdin.fileno()) chan.settimeout(0.0) while True: r, w, e = select.select([chan, sys.stdin], [], []) if chan in r: try: c = 0 x = u(chan.recv(1024)) if len(x) == 0: sys.stdout.write("\r\n*** Done ***\r\n") chan.close() client.close() break #strip non useful info if c <= 1: data = data[400:] c += 1 if str(data).startswith('debian@beaglebone:~$'): data = str(data).replace( 'debian@beaglebone:~$ python3 bb.py', ' ') if str(data).startswith('python3'): data = str(data).replace('python3 bb.py', ' ') if start_parsing: # Parse the sensor values if 'Sensor' in str(data): #change the box color to red to indicate warning if float(data[16:19]) > 1.0: box1["bg"] = "#fb9898" #light red box1["fg"] = "black" box1.insert(END, "") #box_color_change("red", "black", "box1") box1.delete(1.0, END) box1.insert('1.0', data[16:19]) # box2.delete(1.0, END) box2.insert("1.0", data[20:23]) # box3.delete(1.0, END) box3.insert("1.0", data[24:27]) # box4.delete(1.0, END) box4.insert("1.0", data[28:31]) # box5.delete(1.0, END) box5.insert("1.0", data[32:35]) # box6.delete(1.0, END) box6.insert("1.0", data[36:39]) # ''' box7.delete(1.0, END) box7.insert("1.0",data[40:43]) # box8.delete(1.0, END) box8.insert("1.0",data[44:47]) # box9.delete(1.0, END) box9.insert("1.0",data[40:43]) # box10.delete(1.0, END) box10.insert("1.0",data[44:47]) # box11.delete(1.0, END) box11.insert("1.0",data[48:51]) # box12.delete(1.0, END) box12.insert("1.0",data[52:55]) # box13.delete(1.0, END) box13.insert("1.0",data[56:59]) # box14.delete(1.0, END) box14.insert("1.0",data[60:63]) # box15.delete(1.0, END) box15.insert("1.0",data[64:67]) # box16.delete(1.0, END) box16.insert("1.0",data[68:71]) ''' if 'Sensor' in str(x): continue output.insert("end-1c", x) output.see("end") #for testing #print(x, end= '\r', flush= True) #sys.stdout.write(x) #sys.stdout.flush() except socket.timeout: pass if not ON: return "Exiting GUI" #writing in console ''' if sys.stdin in r: x = sys.stdin.read(1) if len(x) == 0: break chan.send(x) ''' finally: termios.tcsetattr(sys.stdin, termios.TCSADRAIN, oldtty) # if we are in a windows based environment else: def writeall(sock): count = 0 while True: data = sock.recv(9999).decode('utf8') file.write(data + '\n') if not data or not ON: sys.stdout.write("\r\n*** Done ***\r\n\r\n") sys.stdout.flush() file.close() chan.close() client.close() break #strip non useful info if count <= 1: data = data[400:] count += 1 if str(data).startswith('debian@beaglebone:~$'): data = str(data).replace( 'debian@beaglebone:~$ python3 bb.py', ' ') if str(data).startswith('python3'): data = str(data).replace('python3 bb.py', ' ') if start_parsing: # Parse the sensor values if 'Sensor' in str(data): #change the box color to red to indicate warning if float(data[16:19]) > 1.0: box1["bg"] = "#fb9898" #light red box1["fg"] = "black" box1.insert(END, "") box1.delete(1.0, END) box1.insert('1.0', data[16:19]) # if float(data[20:23]) > 1.0: box2["bg"] = "#fb9898" #light red box2["fg"] = "black" box2.insert(END, "") box2.delete(1.0, END) box2.insert("1.0", data[20:23]) # if float(data[24:27]) > 1.0: box3["bg"] = "#fb9898" #light red box3["fg"] = "black" box3.insert(END, "") box3.delete(1.0, END) box3.insert("1.0", data[24:27]) # if float(data[28:31]) > 1.0: box4["bg"] = "#fb9898" #light red box4["fg"] = "black" box4.insert(END, "") box4.delete(1.0, END) box4.insert("1.0", data[28:31]) # if float(data[32:35]) > 1.0: box5["bg"] = "#fb9898" #light red box5["fg"] = "black" box5.insert(END, "") box5.delete(1.0, END) box5.insert("1.0", data[32:35]) # if float(data[36:39]) > 1.0: box6["bg"] = "#fb9898" #light red box6["fg"] = "black" box6.insert(END, "") box6.delete(1.0, END) box6.insert("1.0", data[36:39]) # ''' box7.delete(1.0, END) box7.insert("1.0",data[40:43]) # box8.delete(1.0, END) box8.insert("1.0",data[44:47]) # box9.delete(1.0, END) box9.insert("1.0",data[40:43]) # box10.delete(1.0, END) box10.insert("1.0",data[44:47]) # box11.delete(1.0, END) box11.insert("1.0",data[48:51]) # box12.delete(1.0, END) box12.insert("1.0",data[52:55]) # box13.delete(1.0, END) box13.insert("1.0",data[56:59]) # box14.delete(1.0, END) box14.insert("1.0",data[60:63]) # box15.delete(1.0, END) box15.insert("1.0",data[64:67]) # box16.delete(1.0, END) box16.insert("1.0",data[68:71]) ''' if 'Sensor' in str(data): continue output.insert("end-1c", data) output.see("end") #for testing #print(data, end= '\r', flush= True) if not ON: return "Exiting GUI" writer = threading.Thread(target=writeall, args=(chan, )) writer.start() except Exception as e: print("*** Caught exception: %s: %s" % (e.__class__, e)) traceback.print_exc() try: client.close() except: pass sys.exit(1)
def writeall(sock): global sig_to_resend while True: data = ' ' data = sock.recv(9999).decode('utf8') file.write(data + '\n') if not data or not ON: sys.stdout.write("\r\n*** Done ***\r\n\r\n") sys.stdout.flush() file.close() chan.close() client.close() break #Make sure we always have only one data packet if 'Sensor' in data: spl = data.split('\r') #splitting the sensor values and adding the to a FIFO Queue for index in range(len(spl)): if len(spl[index]) > 0: q.put(spl[index]) #for testing #print(data, end= '\r', flush= True) #strip non useful info with a more specific approach is better if 'The programs' in str(data) or 'GNU/Linux' in str(data) \ or 'exact distribution' in str(data) or '@beaglebone' in str(data) \ or 'python3' in str(data) or 'bb.py' in str(data): length = len(data) data = data[length:] if 'PORTLAND' in str(data): global sig sig = True # Once done slicing the greeting section lest get State status #global sig global count if sig: #wait till next time around if count >= 1: chan.send('status\n') #global sig sig = False #sig_to_resend = True #global count count += 1 #for testing #print(data) if 'State :' in str(data) or 'tate :' in str(data): global state_preview index = data.find(':') if not index == -1: state_preview = str(data[index + 1:]).replace( '[K', '').replace('\x1b', ' ') #for testing print(state_preview) else: #state_preview = str(data[8:]).replace('[K', '').replace('\x1b', ' ') pass if start_parsing: #Always display the current state in the P&ID window box18.delete(1.0, END) box18.insert("1.0", state_preview) # Parse the sensor values if 'Sensor values:' in str(data): # for testing (prints sensor values ) #print(data, end= '\r', flush= True) #change the box color to red to indicate warning #for testing #x = x.split(' ') data = q.get() index2 = data.find(':') if not index == -1: data = data[index2 + 2:].replace('\x1b[F', '') data = data + ' 0 1 2 1 1 2 1 0 0' s_val = data.split(' ') #for testing only (for the case where we get less than 30 sensor values) if not len(s_val) == 39: while len(s_val) < 39: s_val.insert(30, '0') s_val = s_val[0:17] + s_val[30:39] mapping = map(float, s_val) s_val = list(mapping) obj_list = [box1, box2, box3, box4, box5, box6, box7, box8, box9, box10, box11, box12, box13, box14, box15, box16, \ box17, c1, c2, c3, c4, c5, c6, c7, c8, c9] lenq = len(s_val) for index in range(len(s_val)): for index in range(0, 17): if s_val[index] > 1: #change the box color when outside valid range box_color_change( obj_list[index], "#fb9898") # if the sensor value is withing the spected range then keep box color yellow obj_list[index].delete(1.0, END) obj_list[index].insert('1.0', s_val[index]) for index in range(17, 26): # if the valve is turned ON then light up GREEN if s_val[index] == 1: valve_position_color( obj_list[index], "#58df52") # if the valve is turned OFF then light up BLUE elif s_val[index] == 0: valve_position_color( obj_list[index], "blue") # if there is an error with the valve light up RED elif s_val[index] == 2: valve_position_color( obj_list[index], "red") #format the data back to distinguis from the screen we want to print to data = f'Sensor values: {data}' if 'Sensor' in str(data): continue output.insert("end-1c", str(data).replace('\x1b[K', ' ')) output.see("end") if not ON: return "Exiting GUI"
def init_paramiko(): # needed parameters for connection port = 22 hostname = 'beaglebone' username = '******' password = '******' #For testing with usb #hostname = '192.168.7.2' ############################## #determine if we are in linux or windows try: import termios import tty has_termios = True except ImportError: has_termios = False try: global chan client = paramiko.SSHClient() client.load_system_host_keys() client.set_missing_host_key_policy(paramiko.WarningPolicy()) print("*** Connecting...") client.connect(hostname, port, username, password) chan = client.invoke_shell() print(repr(client.get_transport())) output.insert("end-1c", '*** SSH Connection to BB_AI stablished ***\n\n') global flag_1 flag_1 = True # This flag is created with the objective that Automatic Shutdown button can only # work if an SSH connection is actually stablished #chan.flush() chan.send('python3 multiprocessingbb.py\n') print("*** SSH Connection to BB_AI stablished!\n") #creating the log file #if the file exist if path.exists("log_gui.txt"): #then append to the existing file file = open("log_gui.txt", "+a") else: #create a new one file = open("log_gui.txt", "+w") ########################################################################### if has_termios: import select oldtty = termios.tcgetattr(sys.stdin) try: tty.setraw(sys.stdin.fileno()) tty.setcbreak(sys.stdin.fileno()) chan.settimeout(0.0) while True: r, w, e = select.select([chan, sys.stdin], [], []) if chan in r: try: c = 0 x = u(chan.recv(1024).decode('utf8')) if len(x) == 0: sys.stdout.write("\r\n*** Done ***\r\n") chan.close() client.close() break #strip non useful info #strip non useful info with a more specific approach is better if 'The programs' in str(x) or 'GNU/Linux' in str(x) \ or 'exact distribution' in str(x) or '@beaglebone' in str(x) \ or 'python3' in str(x) or 'bb.py' in str(x): length = len(x) x = x[length:] if 'PORTLAND' in str(x): global sig sig = True # Once done slicing the greeting section lest get State status #global sig global count if sig: if count >= 1: chan.send('status\n') #global sig sig = False #global count count += 1 if 'State :' in str(x) or 'tate :' in str(x): global state_preview state_preview = x[8:].replace('[K', '') if start_parsing: box18.delete(1.0, END) box18.insert("1.0", state_preview) # Parse the sensor values if 'Sensor' in str(x): #change the box color to red to indicate warning #for testing #x = x.split(' ') x = x + ' 0 1 2 1 1 2 1 0 0' s_val = x.replace('\x1b[F\r', '').split(' ') #for testing only (for the case where we get less than 30 sensor values) if not len(s_val) == 41: while len(s_val) < 41: s_val.insert(32, '0') s_val = s_val[2:19] + s_val[32:41] s_val = map(float, s_val) s_val = list(s_val) obj_list = [box1, box2, box3, box4, box5, box6, box7, box8, box9, box10, box11, box12, box13, box14, box15, box16, \ box17, c1, c2, c3, c4, c5, c6, c7, c8, c9] lenq = len(s_val) for index in range(len(s_val)): for index in range(0, 17): if s_val[index] > 1: #change the box color when outside valid range box_color_change( obj_list[index], "#fb9898") # if the sensor value is withing the spected range then keep box color yellow obj_list[index].delete(1.0, END) obj_list[index].insert( '1.0', s_val[index]) for index in range(17, 26): # if the valve is turned ON then light up GREEN if s_val[index] == 1: valve_position_color( obj_list[index], "#58df52") # if the valve is turned OFF then light up BLUE elif s_val[index] == 0: valve_position_color( obj_list[index], "blue") # if there is an error with the valve light up RED elif s_val[index] == 2: valve_position_color( obj_list[index], "red") if 'Sensor' in str(x): continue x = x.replace('[K', '') output.insert("end-1c", x) output.see("end") #for testing #print(x, end= '\r', flush= True) #sys.stdout.write(x) #sys.stdout.flush() except socket.timeout: pass if not ON: return "Exiting GUI" #writing in console ''' if sys.stdin in r: x = sys.stdin.read(1) if len(x) == 0: break chan.send(x) ''' finally: termios.tcsetattr(sys.stdin, termios.TCSADRAIN, oldtty) ############################################################################# # if we are in a windows. ############################################################################# else: #global count def writeall(sock): global sig_to_resend while True: data = ' ' data = sock.recv(9999).decode('utf8') file.write(data + '\n') if not data or not ON: sys.stdout.write("\r\n*** Done ***\r\n\r\n") sys.stdout.flush() file.close() chan.close() client.close() break #Make sure we always have only one data packet if 'Sensor' in data: spl = data.split('\r') #splitting the sensor values and adding the to a FIFO Queue for index in range(len(spl)): if len(spl[index]) > 0: q.put(spl[index]) #for testing #print(data, end= '\r', flush= True) #strip non useful info with a more specific approach is better if 'The programs' in str(data) or 'GNU/Linux' in str(data) \ or 'exact distribution' in str(data) or '@beaglebone' in str(data) \ or 'python3' in str(data) or 'bb.py' in str(data): length = len(data) data = data[length:] if 'PORTLAND' in str(data): global sig sig = True # Once done slicing the greeting section lest get State status #global sig global count if sig: #wait till next time around if count >= 1: chan.send('status\n') #global sig sig = False #sig_to_resend = True #global count count += 1 #for testing #print(data) if 'State :' in str(data) or 'tate :' in str(data): global state_preview index = data.find(':') if not index == -1: state_preview = str(data[index + 1:]).replace( '[K', '').replace('\x1b', ' ') #for testing print(state_preview) else: #state_preview = str(data[8:]).replace('[K', '').replace('\x1b', ' ') pass if start_parsing: #Always display the current state in the P&ID window box18.delete(1.0, END) box18.insert("1.0", state_preview) # Parse the sensor values if 'Sensor values:' in str(data): # for testing (prints sensor values ) #print(data, end= '\r', flush= True) #change the box color to red to indicate warning #for testing #x = x.split(' ') data = q.get() index2 = data.find(':') if not index == -1: data = data[index2 + 2:].replace('\x1b[F', '') data = data + ' 0 1 2 1 1 2 1 0 0' s_val = data.split(' ') #for testing only (for the case where we get less than 30 sensor values) if not len(s_val) == 39: while len(s_val) < 39: s_val.insert(30, '0') s_val = s_val[0:17] + s_val[30:39] mapping = map(float, s_val) s_val = list(mapping) obj_list = [box1, box2, box3, box4, box5, box6, box7, box8, box9, box10, box11, box12, box13, box14, box15, box16, \ box17, c1, c2, c3, c4, c5, c6, c7, c8, c9] lenq = len(s_val) for index in range(len(s_val)): for index in range(0, 17): if s_val[index] > 1: #change the box color when outside valid range box_color_change( obj_list[index], "#fb9898") # if the sensor value is withing the spected range then keep box color yellow obj_list[index].delete(1.0, END) obj_list[index].insert('1.0', s_val[index]) for index in range(17, 26): # if the valve is turned ON then light up GREEN if s_val[index] == 1: valve_position_color( obj_list[index], "#58df52") # if the valve is turned OFF then light up BLUE elif s_val[index] == 0: valve_position_color( obj_list[index], "blue") # if there is an error with the valve light up RED elif s_val[index] == 2: valve_position_color( obj_list[index], "red") #format the data back to distinguis from the screen we want to print to data = f'Sensor values: {data}' if 'Sensor' in str(data): continue output.insert("end-1c", str(data).replace('\x1b[K', ' ')) output.see("end") if not ON: return "Exiting GUI" writer = threading.Thread(target=writeall, args=(chan, )) #writer.daemon = True writer.start() except Exception as e: print("*** Caught exception: %s: %s" % (e.__class__, e)) traceback.print_exc() if '[Errno 11001] getaddrinfo failed' == str(e): output.insert("end-1c", f' Error connecting to BB_AI.\n') elif '[WinError 10060]' in str(e): output.insert("end-1c", f' Error connecting to BB_AI.\n') try: client.close() except: pass sys.exit(1)
def add_alias_member(ip_address): exp = "\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}" r = re.search(exp, ip_address) """ Make sure we receive a valid IP address """ if r is None: logger.error("Did not receive a valid IP address") return False # Connect to WatchGuard, set disable looking for keys # If you're using pubkey auth, you'll need to change some params here try: client.connect(WATCHGUARD_IP, port=WATCHGUARD_PORT, username=WATCHGUARD_USER, password=WATCHGUARD_PASSWORD, allow_agent=False, look_for_keys=False) logger.info("Connect to WatchGuard") except Exception as e: print("Error connecting to WatchGuard: {}".format(str(e))) return False # Invoke a shell that we can work with shell = client.invoke_shell() # Change to configure mode shell.send("configure\n") sleep(2) # Change to policy mode shell.send("policy\n") sleep(2) # Add the IP to our alias containing blocked IPs shell.send("alias {} host-ip {} \n".format(WATCHGUARD_ALIAS, ip_address)) sleep(2) shell.send("apply\n") sleep(2) # This response is a bytes-object response = shell.recv(2024) logger.info(f"Response from WatchGuard\n: {str(response)}") # Exit policy mode shell.send("exit\n") sleep(2) # Exit configure mode shell.send("exit\n") sleep(2) # Exit WatchGuard CLI shell.send("exit\n") sleep(2) # Close the shell we invoked shell.close() # Close the connection client.close() logger.info("Closed connection to WatchGuard") return True
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()