예제 #1
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
예제 #2
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)
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
예제 #4
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)
예제 #5
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)
예제 #6
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)
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