def run_command(self, host, command, username=None, port=None, progress_stderr=None): if not isinstance(command, bytes): raise TypeError(command) if port is None: port = 22 client = paramiko.SSHClient() client.set_missing_host_key_policy(AutoAcceptPolicy()) client.connect(host, username=username, port=port, **self.ssh_kwargs) channel = client.get_transport().open_session() channel.exec_command(command) def progress_stderr(s): import sys sys.stderr.write(s.decode("utf-8")) sys.stderr.flush() try: from dulwich.client import ParamikoWrapper except ImportError: from dulwich.contrib.paramiko_vendor import _ParamikoWrapper as ParamikoWrapper return ParamikoWrapper(client, channel, progress_stderr=progress_stderr)
def run_command(self, host, command, username=None, port=None, progress_stderr=None): if port is None: port = 22 client = paramiko.SSHClient() client.set_missing_host_key_policy(AutoAcceptPolicy()) client.connect(host, username=username, port=port, **self.ssh_kwargs) channel = client.get_transport().open_session() channel.exec_command(command) def progress_stderr(s): import sys sys.stderr.write(s.decode("utf-8")) sys.stderr.flush() try: from dulwich.client import ParamikoWrapper except ImportError: from dulwich.contrib.paramiko_vendor import (_ParamikoWrapper as ParamikoWrapper) return ParamikoWrapper(client, channel, progress_stderr=progress_stderr)
def run_command(self, host, command, username=None, port=None, progress_stderr=None): if not isinstance(command, bytes): raise TypeError(command) # Paramiko needs an explicit port. None is not valid if port is None: port = 22 client = paramiko.SSHClient() policy = paramiko.client.MissingHostKeyPolicy() client.set_missing_host_key_policy(policy) client.connect(host, username=username, port=port, **self.ssh_kwargs) # Open SSH session channel = client.get_transport().open_session() # Run commands channel.exec_command(command) return _ParamikoWrapper(client, channel, progress_stderr=progress_stderr)
def run_command(self, host, command, username=None, port=None, progress_stderr=None, password=None, pkey=None, key_filename=None, **kwargs): client = paramiko.SSHClient() connection_kwargs = {'hostname': host} connection_kwargs.update(self.kwargs) if username: connection_kwargs['username'] = username if port: connection_kwargs['port'] = port if password: connection_kwargs['password'] = password if pkey: connection_kwargs['pkey'] = pkey if key_filename: connection_kwargs['key_filename'] = key_filename connection_kwargs.update(kwargs) policy = paramiko.client.MissingHostKeyPolicy() client.set_missing_host_key_policy(policy) client.connect(**connection_kwargs) # Open SSH session channel = client.get_transport().open_session() # Run commands channel.exec_command(command) return _ParamikoWrapper( client, channel, progress_stderr=progress_stderr)
def run_command(self, host, command, username=None, port=None, progress_stderr=None): if not isinstance(command, bytes): raise TypeError(command) if port is None: port = 22 client = paramiko.SSHClient() policy = paramiko.client.MissingHostKeyPolicy() client.set_missing_host_key_policy(policy) client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) client.connect(host, username=username, port=port, **self.ssh_kwargs) # Open SSH session channel = client.get_transport().open_session() # Run commands channel.exec_command(command) from dulwich.contrib.paramiko_vendor import ( _ParamikoWrapper as ParamikoWrapper) return ParamikoWrapper( client, channel, progress_stderr=progress_stderr)
def run_command(self, host, command, username=None, port=None, progress_stderr=None): if (type(command) is not list or not all([isinstance(b, bytes) for b in command])): raise TypeError(command) # Paramiko needs an explicit port. None is not valid if port is None: port = 22 client = paramiko.SSHClient() policy = paramiko.client.MissingHostKeyPolicy() client.set_missing_host_key_policy(policy) client.connect(host, username=username, port=port, **self.ssh_kwargs) # Open SSH session channel = client.get_transport().open_session() # Quote command assert command assert is_shell_safe(command[0]) quoted_command = ( command[0] + b' ' + b' '.join( shell_quote(c) for c in command[1:])) # Run commands channel.exec_command(quoted_command) return _ParamikoWrapper( client, channel, progress_stderr=progress_stderr)
def ssh_command(ip, user, passwd, command): client = paramiko.client.SSHClient() # client.load_host_keys('/home/justin/.ssh/known_hosts') client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) client.connect(ip, username=user, password=passwd) ssh_session = client.get_transport().open_session() if ssh_session.active: ssh_session.exec_command(command) print ssh_session.recv(1024) return
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 run_command(self, host, command, username=None, port=None, progress_stderr=None): if port is None: port = 22 client = paramiko.SSHClient() client.set_missing_host_key_policy(AutoAcceptPolicy()) client.connect(host, username=username, port=port, **self.ssh_kwargs) channel = client.get_transport().open_session() channel.exec_command(*command) from dulwich.client import ParamikoWrapper return ParamikoWrapper( client, channel, progress_stderr=progress_stderr)
def run_command(self, host, command, username=None, port=None, progress_stderr=None): if not isinstance(command, bytes): raise TypeError(command) # Paramiko needs an explicit port. None is not valid if port is None: port = 22 client = paramiko.SSHClient() policy = paramiko.client.MissingHostKeyPolicy() client.set_missing_host_key_policy(policy) client.connect(host, username=username, port=port, **self.ssh_kwargs) # Open SSH session channel = client.get_transport().open_session() # Run commands channel.exec_command(command) return _ParamikoWrapper( client, channel, progress_stderr=progress_stderr)
def run_command(self, host, command, username=None, port=None, progress_stderr=None): if port is None: port = 22 client = paramiko.SSHClient() client.set_missing_host_key_policy(AutoAcceptPolicy()) client.connect(host, username=username, port=port, **self.ssh_kwargs) channel = client.get_transport().open_session() assert command assert is_shell_safe(command[0]) command = ( command[0] + b' ' + b' '.join( shell_quote(c) for c in command[1:])) channel.exec_command(command) def progress_stderr(s): import sys sys.stderr.write(s.decode("utf-8")) sys.stderr.flush() try: from dulwich.client import ParamikoWrapper except ImportError: from dulwich.contrib.paramiko_vendor import ( _ParamikoWrapper as ParamikoWrapper) return ParamikoWrapper( client, channel, progress_stderr=progress_stderr)
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 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)