示例#1
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)
示例#2
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)
示例#3
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 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)
示例#5
0
 def ssh(hostname=None, username=None):
     client = SSHClient()
     kw = {'hostname': hostname or nodes[0]}
     if username:
         kw['username'] = username
     client.connect(**kw)
     return client
示例#6
0
def reload_vm(vmname, mastervol=None, vmhost='bruce.openend.se', wait=True):

    if mastervol is None:
        cmd = '/usr/local/bin/reloadvm -y {vmname} -pubkey - '
    else:
        cmd = '/usr/local/bin/reloadvm -y {vmname} -pubkey - {mastervol}'

    with SSHClient() as client:
        client.connect(vmhost)
        keys = list(map(open,
                        glob.glob(os.path.expanduser('~/.ssh/id_*.pub'))))
        with contextlib.nested(*keys):
            client.run(cmd.format(**locals()), stdin=itertools.chain(*keys))

    stop = time.time() + 60
    while True:
        try:
            with SSHClient() as client:
                client.connect(vmname)
                stdout = StringIO()
                client.run('/bin/hostname', stdout=stdout)
                assert stdout.getvalue().strip() == vmname
        except paramiko.ssh_exception.NoValidConnectionsError:
            if time.time() > stop:
                raise
            continue
        else:
            break
示例#7
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)
    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
示例#9
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)
示例#10
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
示例#11
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
    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"
示例#13
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))
示例#14
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
 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_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_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
示例#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)
示例#19
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
示例#20
0
def clean_db(nodes):
    with SSHClient() as client:
        client.connect(nodes[0])
        client.run('PYTHONPATH=/root/accounting '
                   '/root/accounting/bin/test_replica_set.py 300')
        with tempfile.NamedTemporaryFile(mode='w') as f:
            f.write(
                textwrap.dedent('''\
                import accounting.db
                database = accounting.db.connect()
                print 'Removing database %s.' % database.name
                database.client.drop_database(database.name)
                print 'Database %s removed.' % database.name
                '''))
            f.flush()
            sftp = client.open_sftp()
            sftp.put(f.name, '/tmp/clean_db.py')
        client.run('PYTHONPATH=/root/accounting python /tmp/clean_db.py')
示例#21
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)
示例#22
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
示例#24
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)
示例#25
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)
示例#26
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
示例#27
0
def open_auth_log(hostname, *args, **kwargs):
    """Open a readonly file-like object that reads /etc/log/auth.log on `hostname`.

    :param hostname: the server to connect to
    :param args: extra args to pass to SSHClient.connect()
    :param kwargs: extra keyword args to pass to SSHClient.connect()
    :return: TemporaryFile object with log file contents
    """
    # Initiate connection
    client = paramiko.client.SSHClient()
    client.load_system_host_keys()
    kwargs["compress"] = kwargs.get("compress", True)
    client.connect(hostname, *args, **kwargs)

    # Copy file
    temp = tempfile.TemporaryFile()
    sftp = client.open_sftp()
    sftp.getfo("/var/log/auth.log", temp, print_download_progress)
    sftp.close()
    print()

    # Seek back to beginning of file for reading
    temp.seek(0)
    return temp
import sys
import Crypto
import paramiko.client as client
sys.modules['Crypto'] = Crypto

hostName = "10.13.254.40"
uName = "Pi"
pWord = "Raspberry"

client = client.SSHClient()
client.load_system_host_keys()
client.connect(hostname=hostName, port=22, username=uName, password=pWord)
response = client.exec_command('ls')

print response
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
示例#30
0
    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()
示例#31
0
文件: gui.py 项目: psas/tsar-software
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)
# cf. https://github.com/PyCQA/bandit/blob/d5f8fa0d89d7b11442fc6ec80ca42953974354c8/examples/paramiko_injection.py

import paramiko
from paramiko import client


client = paramiko.client.SSHClient()
# this is safe
# ok
client.connect('somehost')

# this is not safe
# ruleid:paramiko-exec-command
client.exec_command('something; really; unsafe')





client2 = client.SSHClient()
client2.connect("somewhere-out-there")
# ruleid:paramiko-exec-command
client2.exec_command("ls -r /")
示例#33
0
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
示例#34
0
文件: lint-all.py 项目: inakypg/tcf
def _gerrit_feedback(_args, _errors, _warnings, _blockage, message):
    # pylint: disable = too-many-locals
    import json
    # work around from https://github.com/paramiko/paramiko/pull/861
    # for bug https://github.com/paramiko/paramiko/issues/1068 when
    # GSSAPI is installed by Ansible
    sys.modules['gssapi'] = None
    import paramiko.client

    if _args.gerrit_from_jenkins:
        logging.info("Getting gerrit info from Jenkins environment")
        scheme = os.environ['GERRIT_SCHEME']
        if scheme != 'ssh':
            logging.error('%s: GERRIT_SCHEME unsupported', scheme)
        host = os.environ['GERRIT_HOST']
        port = int(os.environ['GERRIT_PORT'])
        change_number = int(os.environ['GERRIT_CHANGE_NUMBER'])
        patchset_number = int(os.environ['GERRIT_PATCHSET_NUMBER'])
        ssh_user = os.environ['SSH_USER']
    else:
        logging.info("Getting gerrit info from cmdline")
        host = _args.gerrit_ssh_host
        port = int(_args.gerrit_ssh_port)
        change_number = _args.gerrit_change_number
        patchset_number = _args.gerrit_patchset_number
        ssh_user = _args.gerrit_ssh_user

    params = {}
    if ssh_user:
        params['username'] = ssh_user
    client = paramiko.client.SSHClient()
    client.load_system_host_keys()
    client.connect(host, port, **params)

    data = dict(labels={}, )
    if _warnings > 0:
        data['labels']['Code-Review'] = -1
    if _errors == 0:
        data['labels']['Verified'] = 1
    else:
        data['labels']['Verified'] = -1
    if _blockage > 0:
        # No verification if missing tools
        print(("W: 'Verified %d' vote skipped as some tools are missing "
               "and can't check it all" % data['labels']['Verified']))
        del data['labels']['Verified']

    if message and message != "":
        if _args.url:
            cut_msg = "...\n<cut oversized report, more at %s>" % _args.url
        else:
            cut_msg = "...\n<cut oversized report>"
        cut_len = len(cut_msg)
        if len(message) > _args.gerrit_message_limit:
            message = message[:_args.gerrit_message_limit - cut_len] \
                      + cut_msg
        data['message'] = message
    stdin, stdout, stderr = client.exec_command(
        'gerrit review --json %d,%d' % (change_number, patchset_number),
        bufsize=-1)
    stdin.write(json.dumps(data))
    stdin.flush()
    stdin.channel.shutdown_write()
    output = str(stdout.read(), encoding = 'utf-8') \
            + str(stderr.read(), encoding = 'utf-8')
    if output:
        logging.error("gerrit review output: %s", output)
示例#35
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)
示例#36
0
def bootstrapped(nodes):
    with SSHClient() as client:
        client.connect(nodes[0])
        print('Bootstrapping system.')
        client.run('PYTHONPATH=/root/accounting '
                   '/root/accounting/bin/bootstrap.py')