Exemplo n.º 1
0
    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 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 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)
Exemplo n.º 4
0
    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)
Exemplo n.º 5
0
    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)
Exemplo n.º 6
0
    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)
Exemplo n.º 7
0
    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)
Exemplo n.º 8
0
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
Exemplo n.º 9
0
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
Exemplo n.º 10
0
    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"
Exemplo n.º 11
0
 def connect(self):
     instances = self.manager.list_worker_instances()
     addrs = [_get_external_ip(instance) for instance in instances]
     hosts = {
         ip: instance["name"]
         for ip, instance in zip(addrs, instances)
     }
     clients = {}
     for ip, name in hosts.items():
         client = paramiko.client.SSHClient()
         client.set_missing_host_key_policy(_IgnoreMissingHostKeys)
         client.connect(hostname=ip)
         clients[name] = client
     return clients
Exemplo n.º 12
0
 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_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 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()
Exemplo n.º 16
0
def ssh_attempt_connect(nodename, ssh_key):
    client = paramiko.client.SSHClient()
    client.set_missing_host_key_policy(IgnoreMissingKeyPolicy())
    user = '******'
    port = 22
    logger.debug("Connect to \"{nodename}\" as \"{user}\" on port {port}.".
                 format(nodename=nodename, user=user, port=port))
    try:
        client.connect(nodename,
                       port=port,
                       username=user,
                       timeout=SSH_TIMEOUT,
                       pkey=ssh_key,
                       allow_agent=False,
                       look_for_keys=False)
    except (paramiko.SSHException, socket.timeout, socket.error):
        raise
    return client
Exemplo n.º 17
0
    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)
Exemplo n.º 18
0
    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)
Exemplo n.º 19
0
    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_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
Exemplo n.º 21
0
    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)
Exemplo n.º 22
0
    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)
Exemplo n.º 23
0
    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
Exemplo n.º 24
0
    def __init__(self, hosts, **kwargs):
        etce.fieldclient.FieldClient.__init__(self, hosts)

        self._connection_dict = {}

        self._execute_threads = []

        user = kwargs.get('user', None)

        port = kwargs.get('port', None)

        key_filenames = None

        self._envfile = kwargs.get('envfile', None)

        self._config = ConfigDictionary()

        ssh_config_file = os.path.expanduser('~/.ssh/config')

        ssh_config = None

        if os.path.exists(ssh_config_file):            
            ssh_config = paramiko.SSHConfig()
            ssh_config.parse(open(ssh_config_file))
        
        for host in hosts:
            host_config = None
            if ssh_config:
                host_config = ssh_config.lookup(host)
            host_user = os.path.basename(os.path.expanduser('~'))
            host_port = 22
            host_key_filenames = []
            
            if user:
                host_user = user
            elif host_config:
                host_user = host_config.get('user', host_user)

            if port:
                host_port = port
            elif host_config:
                host_port = host_config.get('port', host_port)

            if key_filenames:
                host_key_filenames = key_filenames
            elif host_config:
                host_key_filenames = host_config.get('identityfile', host_key_filenames)
                
            try:
                client = paramiko.SSHClient()

                client.set_missing_host_key_policy(paramiko.client.RejectPolicy())

                client.load_system_host_keys()

                self._connection_dict[host] = client

                self._connection_dict[host].connect(hostname=host,
                                                    username=host_user,
                                                    port=int(host_port),
                                                    key_filename=host_key_filenames,
                                                    allow_agent=True)

            except socket.gaierror as ge:
                message = '%s "%s". Quitting.' % (ge.strerror, host)
                raise FieldConnectionError(message)

            except paramiko.ssh_exception.NoValidConnectionsError as e:
                raise FieldConnectionError('Unable to connect to host "%s". Quitting.' % host)

            except Exception as e:
                message = 'Unable to connect to host "%s" (%s). Quitting.' % (host, str(e))
                raise FieldConnectionError(message)
Exemplo n.º 25
0
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)
Exemplo n.º 26
0
import re

from config import WATCHGUARD_USER, WATCHGUARD_PASSWORD, WATCHGUARD_PORT, WATCHGUARD_IP, WATCHGUARD_ALIAS

from time import sleep

from app_logger import logger
"""
General idea of command sequence
Connect over SSH > configure > policy > alias MaliciousIP host-ip 83.217.11.193 > apply
"""

# Set up SSH client
client = client.SSHClient()

client.set_missing_host_key_policy(AutoAddPolicy())


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
Exemplo n.º 27
0
def get_sshclient(host):
    client = paramiko.SSHClient()
    client.load_system_host_keys()
    client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    client.connect(hostname=host, username=None, password=None)
    return client
Exemplo n.º 28
0
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)