コード例 #1
0
ファイル: sshLogger.py プロジェクト: shuoGG1239/LogViewer
def run_conn_log():
    user = load_user_info()
    host = user.host
    name = user.name
    password = user.password
    prompt = '.+'

    try:
        client = paramiko.SSHClient()
        client.load_system_host_keys()
        client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        client.connect(hostname=host, username=name, password=password)
        interact = SSHClientInteraction(client, timeout=10, display=False)
        interact.expect(prompt)
        interact.send(user.cmd)
        interact.tail(line_prefix=host + ': ', timeout=65535)

    except KeyboardInterrupt:
        print('Ctrl+C interruption detected, stopping tail')
    except Exception:
        traceback.print_exc()
    finally:
        try:
            client.close()
        except:
            pass
コード例 #2
0
    def get_zombie_number(self, node_details):
        failed_node = []

        try:
            ssh = paramiko.SSHClient()
            ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
            ssh.connect(node_details[1],
                        username=node_details[2],
                        password=node_details[3])
            interact = SSHClientInteraction(ssh, timeout=60, display=True)
            interact.expect('admin:')
            interact.send('set cli pagination off')
            interact.expect('admin:')
            interact.send('show process load')
            interact.expect('admin:')
            process_output = interact.current_output_clean
            regPattern = re.compile("(\d)\szombie")
            zombie_number = re.search(regPattern, process_output)
            if zombie_number == None:
                print("Some error occured")
            result = zombie_number.groups()[0]
            print("Zombies found: ", result)
            return result
        except paramiko.AuthenticationException:
            print("\nAuthentication failed for node: ", node_details[1],
                  ". Please check the credentials in input file")
            failed_node.append(node_details[1])
        except paramiko.SSHException as SSHException:
            print("\nUnable to establish a SSH connection: ", SSHException)
            print("connection failed for node:", node_details[1])
            failed_node.append(node_details[1])
        except Exception as E:
            print("\nError occured: ", E)
            print("connection failed for node:", node_details[1])
            failed_node.append(node_details[1])
コード例 #3
0
ファイル: cp.py プロジェクト: Barkie/Python_first_one
def commands():
        """ssh write commands"""
        try:
            ssh.connect(hostname=host, username=user, password=passwd)
        except TimeoutError:
            print('surprise m**********r, host is down')
        interact = SSHClientInteraction(ssh, timeout=10, display=True)\
        print('connected')
        interact.send(item)
        found_index = interact.expect([not_found, prompt])
        if found_index == 0:
            print('command not found, trying expert mode')
            interact.send('expert')
            entering_expert_index = interact.expect([no_expert_pass, enter_expert_pass])
            if entering_expert_index == 0:
                print('no expert password, need to set it')
                no_expert_output = interact.current_output_clean
                # something here to write to file
            elif entering_expert_index == 1:
                print('cp asked for expert password, entering it')
                interact.send(expert_passwd)
                expert_mode_index([wrong_expert_pass, expert_prompt])
                if expert_mode_index == 0:
                    print('wrong expert pass')
                    #something here to write to file
                elif expert_mode_index == 1:
                    print('password ok, continuing')
            interact.send(i)
            interact.expect(expert_prompt)
            interact.send('exit')
            interact.expect(prompt)
コード例 #4
0
 def remote_tail(self, host, port, user, passwd, logfile, webuser, filter_text=None):
     # 创建一个可跨文件的全局变量,控制停止
     try:
         self.client = paramiko.SSHClient()
         self.client.load_system_host_keys()
         self.client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
         self.client.connect(hostname=host, port=port, username=user, password=passwd)
         interact = SSHClientInteraction(self.client, timeout=10, display=False)
         interact.expect('.*#.*')
         logfile = logfile.strip().replace('&&', '').replace('||', '').replace('|', '')
         self.send_message(webuser, '[INFO][%s@%s]开始监控日志' % (user, host))
         redis = RedisObj()
         redis.set('remote_tail_' + str(webuser), self.client)
         if filter_text:
             filter_text_re = filter_text.strip().replace('&&', '').replace('||', '').replace('|', '')
             interact.send('tail -f %s|grep --color=never %s' % (logfile, filter_text_re))
         else:
             interact.send('tail -f %s' % (logfile))
         interact.tail(output_callback=lambda m: self.send_message(webuser, m), stop_callback=lambda x: self.get_is_stop(webuser))
     except Exception as e:
         self.send_message(webuser, e)
     finally:
         redis = RedisObj()
         redis.set('remote_tail_' + str(webuser), '1')
         try:
             self.client.close()
         except Exception as e:
             self.send_message(webuser, e)
コード例 #5
0
def session():
    try:
        sshconnect = paramiko.SSHClient()
        sshconnect.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        for ipaddr in hostname:
            filename = 'MSHealthCheck_' + ipaddr.replace('.',
                                                         '_') + '_' + timestr
            outputfile = '{}.txt'.format(filename)
            sshconnect.connect(hostname=ipaddr,
                               username=username,
                               password=password)
            interact = SSHClientInteraction(sshconnect,
                                            timeout=60,
                                            display=True)
            for command in commands:
                interact.expect('admin:')
                interact.send(command)
                devoutput = interact.current_output_clean
                with open(os.path.join(path, outputfile), 'a') as filewrite:
                    filewrite.write('#' * 5 + command + '#' * 5)
                    filewrite.write(devoutput)
        sshconnect.close()
    except paramiko.ssh_exception.AuthenticationException as a:
        print(a)
    except paramiko.ssh_exception.SSHException as c:
        print(c)
    except Exception as e:
        print(e)
コード例 #6
0
def ChangeCLIPW(ip, username, oldpassword, newpassword):
    command = "set password user admin"
    sshsession = paramiko.SSHClient()
    sshsession.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    sshsession.connect(ip, username=username, password=oldpassword)
    # "display=True" is just to show you what script does in real time. While in production you can set it to False
    interact = SSHClientInteraction(sshsession, timeout=600, display=True)
    # program will wait till session is established and CUCM returns admin prompt
    # "display=True" is just to show you what script does in real time. While in production you can set it to False
    interact = SSHClientInteraction(sshsession, timeout=600, display=True)
    # program will wait till session is established and CUCM returns admin prompt
    interact.expect('admin:')
    interact.send(command)
    interact.expect('.*password:.*')
    interact.send(oldpassword)
    interact.expect('.*password:.*')
    interact.send(newpassword)
    interact.expect('.*password.*')
    interact.send(newpassword)
    interact.expect('admin:')
    interact.send('exit')
    output = interact.current_output  # program saves output of show status command to the "output" variable
    with open("ChangeLog.txt", 'a') as outfile:
        lines = output.splitlines()
        last_line = lines[-1]
        outfile.write("{0} | CLI | {1} | {2} | {3}".format(
            datetime.now(), ip, newpassword, last_line))
        outfile.close()
    sshsession.close()
コード例 #7
0
def ConnectToSsh(UserID, Password):
    global objInteract
    global objSsh

    # Instantiate the SSH Object
    objSsh = paramiko.SSHClient()
    objSsh.set_missing_host_key_policy(paramiko.AutoAddPolicy())

    # Begin SSH Connection
    try:
        objSsh.connect(strPhoneIP, username=UserID, password=Password)
        strFail = "SSH Object Connected Successfully"
    except:
        objSsh.close()
        strFail = "CTG Phone Control\n\nFailed SSH Connection\n"
        ErrorWindow(strFail)

    # Nowthat the SSH session is started, send the secondary login to the Phone
    # to enter debug mode.
    # Use Expect because the UC CLI takes to long to start and commands
    # vary in duration of run time.  Expect ensures we enter the
    # command at the appropriate time.
    objInteract = SSHClientInteraction(objSsh, timeout=120, display=False)
    objInteract.expect('.*log.*', default_match_prefix='')
    objInteract.send('debug')
    objInteract.expect('.*Password.*')
    objInteract.send('debug')
コード例 #8
0
 def stalkLog(self, log, dir, timeToStop):
     cmd = "cd " + dir + ";tail -f " + log
     interact = SSHClientInteraction(self.ssh, timeout=10, display=False)
     interact.send(cmd)
     #def tail(self, line_prefix=None, callback=None,
     #         output_callback=None, stop_callback=lambda x: False,
     #         timeout=None):
     interact.tail(None, self.process_tail, None, self.timer)
コード例 #9
0
 def get_device_prompt(self, host, username, password):
     ssh_client = self.get_ssh_client(host, username, password)
     interact = SSHClientInteraction(ssh_client, timeout=10, display=True)
     interact.send("\n")
     interact.expect(".*")
     prompt = (str(interact.current_output)).strip()
     prompt_char = re.sub('[a-zA-Z0-9]*', '', prompt)
     return prompt_char
コード例 #10
0
ファイル: epg1.py プロジェクト: Pigiel/phoenix
def save_config(hostname, ip, username, password):
    """
	Downloads current configuration of Ericsson EPG 1.X node
	
	Args:
		hostname: 	hostname
		ip: 		host's ip address
		username: 	user's login
		password: 	user's password
	
	Returns:
		name of the configuration file or log with connection error
	"""

    PROMPT = '.*\[local\]{}#.*'.format(hostname)
    PROMPT_EXEC = '.*{}@{}>.*'.format(USERNAME, hostname)
    PROMPT_BASH = '.*bash-.*$.*'
    PROMPT_CONFIRM = '.*(y/n).*'

    try:
        ssh = paramiko.SSHClient()
        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        ssh.connect(ip, username=username, password=password, timeout=30)
        interact = SSHClientInteraction(ssh,
                                        timeout=60,
                                        display=SSH_DISPLAY_LOGGING)
        interact.expect(PROMPT)
        # Checking software version on the node
        interact.send('start shell')
        interact.expect(PROMPT_BASH)
        interact.send('show_epg_version |grep -v +')
        interact.expect(PROMPT_BASH)
        version = interact.current_output_clean.split('\n')
        interact.send('exit')
        interact.expect(PROMPT)
        # Puts node version into file name
        for line in version:
            if ('version') in line:
                file_name = '{}_{}.cfg'.format(hostname, line.split()[4])
        # Save the node configuration
        interact.send('start oam-cli')
        interact.expect(PROMPT_EXEC)
        interact.send('show-config')
        interact.expect(PROMPT_EXEC)
        # Save the EPG 1.X config output to file
        with open(TMP_PATH + file_name, 'a+') as f:
            f.write(interact.current_output_clean)
    except Exception as e:
        # Any exception is logged to file with current date
        file_name = '{}-errors.log'.format(hostname)
        log = DATE + ' : ' + str(e)
        with open(GIT_PATH + hostname + '/' + file_name, 'a') as f:
            f.write(log + '\n')
    finally:
        ssh.close()
    return file_name
コード例 #11
0
ファイル: cp5.py プロジェクト: Barkie/Python_first_one
def commands():
        """ssh write commands"""
        interact = SSHClientInteraction(ssh, timeout=10, display=True)
        interact.send('lock database override')
        interact.expect('\n.*> ')
        interact.send('fw tab -t connections -s')
        print('sended IF, expecting >')
        interact.expect('\n.*> ')
        print('ok!')
        cmd_output_uname = interact.current_output_clean
        print(cmd_output_uname)
コード例 #12
0
def test_channel():
    client = ParamikoClient('config.ini', 'PPM101')
    client.connect()
    interact = SSHClientInteraction(client.client, timeout=10, display=False)
    interact.expect(re_strings='.*#.*')
    interact.send('echo ""')
    interact.send(
        'tail -f /opt/ppm/ppm/QX_DEV_OPS_962/server/kintana/log/serverLog.txt')
    interact.tail(output_callback=lambda m: output_callback(m, interact),
                  stop_callback=lambda x: get_is_stop(x),
                  timeout=100)
コード例 #13
0
def process_data(threadName, q):
    while not exitFlag:
        queueLock.acquire(
        )  #lock child thread and wait to receive data from parent thread
        if not workQueue.empty():
            hostAddress = q.get(host)
            u = q.get(username)
            p = q.get(password)
            p = re.sub('\n', '', p)
            p = re.sub('\r', '', p)
            print(u + ' ' + p + ' ' + hostAddress)
            queueLock.release()  #release lock
            print((threadName) + ' -> processing')
            try:
                client = paramiko.SSHClient()
                client.load_system_host_keys()
                client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
                client.connect(hostname=hostAddress,
                               username=u,
                               password=p,
                               banner_timeout=120)
                prompt = 'admin:'
                accept = 'Continue \(y\/n\)\?'
                interact = SSHClientInteraction(client,
                                                timeout=120,
                                                display=False)
                interact.expect(prompt)
            except socket.gaierror:
                print(hostAddress + ' -> FAILED socket/dns error')
                print('Exiting ' + threadName)
                exit(1)
            print(hostAddress + ' -> SUCCESS ssh connected!')
            interact.send('set cli pagination off')
            interact.expect(prompt)
            for certType in certTypes:
                try:
                    interact.send('show cert own ' + certType)
                    interact.expect(prompt)
                    cmd_output_pd = interact.current_output_clean
                    pd = cmd_output_pd.split('\n')
                    out = re.findall(
                        '(To:\s+\S+\s\S+\s+\d+\s\S+\s\S+\s\S+|Not\sAfter\s:\s+\S+\s+\d+\s\S+\s\S+\s\S+)',
                        cmd_output_pd, re.DOTALL)[0]
                    out = re.sub('(To:\s+|Not\s+After\s+:\s+)', '', out)
                    print(hostAddress + ' ' + certType + ' expires ' + out)
                    file.write(hostAddress + ',' + certType + ',' + out + '\n')
                except Exception:
                    #interact.send('exit')
                    continue
            #interact.send('exit')
        else:
            queueLock.release()
コード例 #14
0
def ChangePlatformPw(ip, username, password, NewPlatPw, command):
    sshsession = paramiko.SSHClient()
    sshsession.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    sshsession.connect(ip, username=username, password=password)
    # "display=True" is just to show you what script does in real time. While in production you can set it to False
    interact = SSHClientInteraction(sshsession, timeout=600, display=True)
    # program will wait till session is established and CUCM returns admin prompt
    # "display=True" is just to show you what script does in real time. While in production you can set it to False
    interact = SSHClientInteraction(sshsession, timeout=600, display=True)
    # program will wait till session is established and CUCM returns admin prompt
    interact.expect('admin:')
    interact.send(command)
    interact.expect('.*password:.*')
    interact.send(password)
    interact.expect('.*password:.*')
    interact.send(NewPlatPw)
    interact.expect('.*password.*')
    interact.send(NewPlatPw)
    interact.expect('admin:')
    output = interact.current_output  # program saves output of show status command to the "output" variable
    with open("Logs/ChangeAppPw.txt", 'a') as outfile:
        outfile.write(output)
        outfile.write(
            "{0} {1} -- Password Initiated changed to {2} {3}".format(
                ip, username, NewPlatPw, datetime.now()))
        outfile.close()
    sshsession.close()
コード例 #15
0
def ShowCommands(ip, username, password, command):
    sshsession = paramiko.SSHClient()
    sshsession.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    sshsession.connect(ip, username=username, password=password)
    # "display=True" is just to show you what script does in real time. While in production you can set it to False
    interact = SSHClientInteraction(sshsession, timeout=600, display=True)
    # program will wait till session is established and CUCM returns admin prompt
    interact.expect('admin:')
    interact.send(command)
    interact.expect('admin:')
    output = interact.current_output  # program saves output of show status command to the "output" variable
    with open("Logs/ShowCommand.txt", 'a') as outfile:
        outfile.write(output)
        outfile.close()
    sshsession.close()
コード例 #16
0
ファイル: switch.py プロジェクト: Pigiel/phoenix
def save_config(hostname, ip, username, password):
    """
	Function that downloads running-configuration from Cisco switch
	Args:
		hostname: 	switch hostname
		ip:			switch management ip address
		username:	user's login switch
		password:	user's passowrd to switch
	
	Returns:
		name of the configuraiton file or log with connection error
	"""

    # Set PROMPT variables for Cisco routers/swtiches
    USER_PROMPT = f'.*{hostname}>.*'  # User mdoe
    PRIVILEGED_PROMPT = f'.*{hostname}#.*'  # Provileged (config) mode

    try:
        ssh = paramiko.SSHClient()
        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        ssh.connect(ip,
                    username=username,
                    password=password,
                    timeout=60,
                    look_for_keys=False,
                    allow_agent=False)
        # Library to interact with with SSH output
        interact = SSHClientInteraction(ssh, timeout=60, display=False)
        # Wait for switch prompt user (.*>) or privileged (.*#)
        interact.expect([USER_PROMPT, PRIVILEGED_PROMPT])
        # If user mode enable privileged
        if interact.last_match == USER_PROMPT:
            interact.send('enable')
            interact.expect('Password: '******'.cfg'
        # Set terminal length for session to infinite
        # (no "-- More --" prompt)
        interact.send('terminal length 0')
        interact.expect(PRIVILEGED_PROMPT)
        interact.send('show running-config')
        interact.expect(PRIVILEGED_PROMPT)
        config = interact.current_output_clean
        with open(TMP_PATH + file_name, 'a') as f:
            f.write(config)

    except Exception as e:
        # Any exception is logged to file with current date
        file_name = '{}-errors.log'.format(hostname)
        log = DATE + ' : ' + str(e)
        with open(GIT_PATH + hostname + '/' + file_name, 'a') as f:
            f.write(log + '\n')

    finally:
        ssh.close()

    return file_name
コード例 #17
0
ファイル: paramiko_ex.py プロジェクト: SeanWanghp/Python_snmp
def main():
    # Set login credentials and the server prompt
    hostname = '10.245.46.208'
    username = '******'
    password = '******'
    prompt = 'root@GPON-8R2:~# '
    cli_prompt = 'GPON-8R2# '
    client = None
    # Use SSH client to login
    try:
        # Create a new SSH client object
        client = paramiko.SSHClient()

        # Set SSH key parameters to auto accept unknown hosts
        client.load_system_host_keys()
        client.set_missing_host_key_policy(paramiko.AutoAddPolicy())

        # Connect to the host
        client.connect(hostname=hostname, username=username, password=password)

        # Create a client interaction class which will interact with the host
        interact = SSHClientInteraction(client, timeout=2, display=False)
        interact.expect(prompt)
        """only can using for linux mode in py3, py2 can using for CLI"""
        interact.send('pwd')
        interact.expect(prompt, timeout=2)
        cmd_output_uname = interact.current_output_clean
        print(cmd_output_uname)

        interact.send('ll')
        interact.expect(prompt, timeout=2)
        cmd_output_uname = interact.current_output_clean
        print(cmd_output_uname)

        # interact.send('show card')
        # interact.expect(cli_prompt, timeout=2)
        # cmd_output_uname = interact.current_output_clean
        # print(cmd_output_uname)

    except KeyboardInterrupt:
        print('Ctrl+C interruption detected, stopping tail')
    except EOFError:
        traceback.print_exc()
    finally:
        try:
            client.close()
        except EOFError:
            pass
コード例 #18
0
def session(ip, username, password):
    try:
        ssh = paramiko.SSHClient()
        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())

        ssh.connect(ip, username=username, password=password)
        interact = SSHClientInteraction(ssh, timeout=90, display=True)

        interact.expect('admin:')
        interact.send('show risdb query phone')
        interact.expect('admin:')
        output = interact.current_output_clean
    finally:
        ssh.close()

    ip_file_name = ip.replace('.', '_')
    output_file = '{}.csv'.format(ip_file_name)
    with open(output_file, mode='wt', encoding='utf-8') as out:
        out.write(output)
コード例 #19
0
def ChangeUsername(ip, username, password, command, Username):
    sshsession = paramiko.SSHClient()
    sshsession.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    sshsession.connect(ip, username=username, password=password)
    # "display=True" is just to show you what script does in real time. While in production you can set it to False
    interact = SSHClientInteraction(sshsession, timeout=600, display=True)
    # program will wait till session is established and CUCM returns admin prompt
    interact.expect('admin:')
    output = interact.current_output_clean  # program saves output of show status command to the "output" variable
    interact.send(command)
    interact.last_match == '.*administrator.*'
    interact.send(Username)
    interact.expect('admin:')
    output = interact.current_output_clean  # program saves output of show status command to the "output" variable
    with open("Logs/ChangeAdminName.txt", 'a') as outfile:
        outfile.write(
            f"{output} {username} -- Administrator Name Changed to {Username} {datetime.now()}"
        )
        outfile.close()
    sshsession.close()
コード例 #20
0
def connection_ssh():
    SSH_ADDRESS = "10.76.7.18"
    SSH_USERNAME = "******"
    SSH_PASSWORD = "******"
    ## CODE BELOW ##
    ssh = paramiko.SSHClient()
    ssh.load_system_host_keys()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    ssh.connect(SSH_ADDRESS,
                username=SSH_USERNAME,
                password=SSH_PASSWORD,
                look_for_keys=False)
    interact = SSHClientInteraction(ssh, display=True)
    a = interact.expect(['.*seeing.*', '.*#.*'])
    if a == 0:
        interact.send('y')
        interact.expect('.*#.*')
    else:
        interact.send('\n')
        interact.expect('.*#.*')
    return interact
コード例 #21
0
ファイル: kadai14.py プロジェクト: PythonGakusyu/repository
def check_command(ssh, command, logger, vm, PROMPT, password):

    # コマンドライン引数はtouch cpuinfo.txt & vim-cmd hostsvc/hosthardware & vim-cmd hostsvc/hosthardware > cpuinfo.txt
    #192.168.144.136 esxcli network firewall set --enabled false

    interact = SSHClientInteraction(ssh, display=True)
    #	interact.expect(PROMPT)
    interact.send(command)
    interact.send('scp cpuinfo.txt [email protected]:/home/tokunaga')
    interact.send('yes')
    interact.expect('[email protected]\'s password:'******'Toku1456')
    interact.expect()
コード例 #22
0
def main():
    # Set login credentials and the server prompt
    hostname = "localhost"
    username = "******"
    password = "******"
    prompt = "fots@fotsies-ubuntu-testlab:~\$ "

    # Use SSH client to login
    try:
        # Create a new SSH client object
        client = paramiko.SSHClient()

        # Set SSH key parameters to auto accept unknown hosts
        client.load_system_host_keys()
        client.set_missing_host_key_policy(paramiko.AutoAddPolicy())

        # Connect to the host
        client.connect(hostname=hostname, username=username, password=password)

        # Create a client interaction class which will interact with the host
        interact = SSHClientInteraction(client, timeout=10, display=False)
        interact.expect(prompt)

        # Send the tail command
        interact.send("tail -f /var/log/auth.log")

        # Now let the class tail the file for us
        interact.tail(line_prefix=hostname + ": ")

    except KeyboardInterrupt:
        print "Ctrl+C interruption detected, stopping tail"
    except Exception:
        traceback.print_exc()
    finally:
        try:
            client.close()
        except:
            pass
コード例 #23
0
def main():
    # Set login credentials and the server prompt
    hostname = 'localhost'
    username = '******'
    password = '******'
    prompt = 'vagrant@paramiko-expect-dev:~\$\s+'

    # Use SSH client to login
    try:
        # Create a new SSH client object
        client = paramiko.SSHClient()

        # Set SSH key parameters to auto accept unknown hosts
        client.load_system_host_keys()
        client.set_missing_host_key_policy(paramiko.AutoAddPolicy())

        # Connect to the host
        client.connect(hostname=hostname, username=username, password=password)

        # Create a client interaction class which will interact with the host
        interact = SSHClientInteraction(client, timeout=10, display=False)
        interact.expect(prompt)

        # Send the tail command
        interact.send('tail -f /var/log/syslog')

        # Now let the class tail the file for us
        interact.tail(line_prefix=hostname + ': ')

    except KeyboardInterrupt:
        print('Ctrl+C interruption detected, stopping tail')
    except Exception:
        traceback.print_exc()
    finally:
        try:
            client.close()
        except:
            pass
コード例 #24
0
def main():
    # Set login credentials and the server prompt
    hostname = 'localhost'
    username = '******'
    password = '******'
    prompt = r'vagrant@paramiko-expect-dev:~\$\s+'

    # Use SSH client to login
    try:
        # Create a new SSH client object
        client = paramiko.SSHClient()

        # Set SSH key parameters to auto accept unknown hosts
        client.load_system_host_keys()
        client.set_missing_host_key_policy(paramiko.AutoAddPolicy())

        # Connect to the host
        client.connect(hostname=hostname, username=username, password=password)

        # Create a client interaction class which will interact with the host
        interact = SSHClientInteraction(client, timeout=10, display=False)
        interact.expect(prompt)

        # Send the tail command
        interact.send('tail -f /var/log/syslog')

        # Now let the class tail the file for us
        interact.tail(line_prefix=hostname+': ')

    except KeyboardInterrupt:
        print('Ctrl+C interruption detected, stopping tail')
    except Exception:
        traceback.print_exc()
    finally:
        try:
            client.close()
        except Exception:
            pass
コード例 #25
0
def process_UCM(SSH, KEY, OPERATION):
    try:
        interact = SSHClientInteraction(SSH, display=False)
        interact.expect('admin:')
        interact.send(OPERATION)
        interact.expect('admin:')
        output = interact.current_output_clean
        SSH.close()

        #PARSING
        if KEY == "DIAGNOSTIC":
            parsed_output = diagnose_parser(output.split('\n'))
            return parsed_output

        if KEY == "DISASTER_RECOVERY":
            parsed_output = disaster_parser(output.split('\n'))
            return parsed_output

        if KEY == "DBREPLICATION":
            parsed_output = dbreplication_parser(output.split('\n'))
            return parsed_output

    except Exception as e:
        return str(e)
コード例 #26
0
ファイル: vepc.py プロジェクト: Pigiel/phoenix
def save_config(hostname, ip, username, password):
    """
	Function that downloads current config of Cisco vEPC node
	
	Args:
		hostname: 	node's hostname
		ip:			node's management ip address
		username:	user's login to node
		password:	user's passowrd to node
	
	Returns:
		name of the configuraiton file or log with connection error
	"""

    PROMPT = '.*{}#.*'.format(hostname)
    PROMPT_CFG = '.*{}\(config\)#.*'.format(hostname)

    try:
        ssh = paramiko.SSHClient()
        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        ssh.connect(ip, username=username, password=password, timeout=30)
        interact = SSHClientInteraction(ssh, timeout=60, display=False)
        interact.expect(PROMPT)
        # Check node software version
        interact.send('show version')
        interact.expect(PROMPT)
        version = interact.current_output_clean.split('\n')
        # Put node version into file name
        for line in version:
            if ('Image Version:') in line:
                file_name = '{}_{}.cfg'.format(hostname, line.split()[2])
        # Save node config in path /sftp/<file_name>
        interact.send('save configuration {}{}'.format(SFTP_PATH, file_name))
        interact.expect(PROMPT)
        # Open SFTP conneciton to download config file
        sftp = ssh.open_sftp()
        sftp.get(SFTP_PATH + file_name, TMP_PATH + file_name)
        sftp.close()
        # Delete config file to free up space
        interact.send('delete {}{}'.format(SFTP_PATH, file_name))
        interact.expect(PROMPT)

    except Exception as e:
        # Any exception is logged to file with current date
        file_name = '{}-errors.log'.format(hostname)
        log = DATE + ' : ' + str(e)
        with open(GIT_PATH + hostname + '/' + file_name, 'a') as f:
            f.write(log + '\n')

    finally:
        ssh.close()

    return file_name
コード例 #27
0
def GetRegisteredPhones(cucm=None, clusterpass=None):
    hostAddress = cucm
    u = 'admin'
    p = clusterpass

    output = ''
    client = paramiko.SSHClient()
    client.load_system_host_keys()
    client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    client.connect(hostname=hostAddress,
                   username=u,
                   password=p,
                   timeout=25,
                   banner_timeout=120)
    prompt = 'admin:'
    interact = SSHClientInteraction(client, timeout=30, display=False)
    try:
        interact.expect(prompt, timeout=15)
    except:
        interact.send('\n')
        interact.expect(prompt)
    trash = interact.current_output_clean
    try:
        interact.send('show risdb query phone')
        interact.expect(prompt, timeout=15)
    except:
        interact.send('\n')
        interact.expect(prompt)
    output = interact.current_output_clean
    regex = r"(DeviceName[\s\S]*)\n\n"
    matches = re.findall(regex, output, re.DOTALL)
    client.close()
    f = open("phones.csv", "a+", encoding="utf-8")
    for match in matches:
        f.write(match)
    f.close()
コード例 #28
0
def main():
    # Set login credentials and the server prompt
    hostname = '10.10.0.254'
    username = '******'
    password = '******'
    prompt = 'test-checkpoint-for-scripts> '

    # Use SSH client to login
    try:
        # Create a new SSH client object
        client = paramiko.SSHClient()

        # Set SSH key parameters to auto accept unknown hosts
        client.load_system_host_keys()
        client.set_missing_host_key_policy(paramiko.AutoAddPolicy())

        # Connect to the host
        client.connect(hostname=hostname, username=username, password=password)

        # Create a client interaction class which will interact with the host
        interact = SSHClientInteraction(client, timeout=10, display=True)
        interact.expect(prompt)

        # Run the first command and capture the cleaned output, if you want
        # the output without cleaning, simply grab current_output instead.
        interact.send('netstat -rnv')
        interact.expect(prompt)
        cmd_output_uname = interact.current_output_clean

        # Now let's do the same for the ls command but also set a timeout for
        # this specific expect (overriding the default timeout)
        interact.send('show interface Lan2')
        interact.expect(prompt, timeout=5)
        cmd_output_ls = interact.current_output_clean

        # To expect multiple expressions, just use a list.  You can also
        # selectively take action based on what was matched.

        # Method 1: You may use the last_match property to find out what was
        # matched
        #interact.send('~/paramiko_expect-demo-helper.py')
        #interact.expect([prompt, 'Please enter your name: '])
        #if interact.last_match == 'Please enter your name: ':
        #    interact.send('Fotis Gimian')
        #    interact.expect(prompt)

        # Method 2: You may use the matched index to determine the last match
        # (like pexpect)
        #interact.send('~/paramiko_expect-demo-helper.py')
        #found_index = interact.expect([prompt, 'Please enter your name: '])
        #if found_index == 1:
        #    interact.send('Fotis Gimian')
        #    interact.expect(prompt)

        # Send the exit command and expect EOF (a closed session)
        interact.send('exit')
        interact.expect()

        # Print the output of each command
        #print '-'*79
        print('Cleaned Command Output')
        #print '-'*79
        print('uname -a output:')
        print(cmd_output_uname)
        print('ls -l / output:')
        print(cmd_output_ls)

    except Exception:
        traceback.print_exc()
    finally:
        try:
            client.close()
        except:
            pass
コード例 #29
0
 cert_writer.writerow([
     'Serial Number', 'Node IP', 'Certificate CN', 'Certificate Type',
     'Certificate Issued on', 'Certificate Expiry Date',
     'Certificate Status', 'Will Expire In'
 ])
 for elem in all_server:
     try:
         ssh = paramiko.SSHClient()
         ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
         ssh.connect(elem[0], username=elem[1], password=elem[2])
         print("\nConnected to node no:", node_no + 1)
         print("Fetching and analyzing certificates from node :",
               elem[0])
         interact = SSHClientInteraction(ssh, timeout=60, display=True)
         interact.expect('admin:')
         interact.send('set cli pagination off')
         interact.expect('admin:')
         interact.send('show cert list own')
         interact.expect('admin:')
         CertListOutput = interact.current_output_clean
         certList = Strip_certificate_name(CertListOutput)
         certList = list(filter(None, certList))
         for cert in certList:
             interact.send('show cert own ' + cert)
             interact.expect('admin:')
             CertNameOutput = interact.current_output_clean
             cert_details = extract_cert_details(
                 elem[0], cert, CertNameOutput)
             cert_writer.writerow(cert_details)
         node_no += 1
     except paramiko.AuthenticationException:
コード例 #30
0
def main():
    # Set login credentials and the server prompt
    hostname = 'localhost'
    username = '******'
    password = '******'
    prompt = 'fots@fotsies-ubuntu-testlab:~\$ '

    # Use SSH client to login
    try:
        # Create a new SSH client object
        client = paramiko.SSHClient()

        # Set SSH key parameters to auto accept unknown hosts
        client.load_system_host_keys()
        client.set_missing_host_key_policy(paramiko.AutoAddPolicy())

        # Connect to the host
        client.connect(hostname=hostname, username=username, password=password)

        # Create a client interaction class which will interact with the host
        interact = SSHClientInteraction(client, timeout=10, display=True)
        interact.expect(prompt)

        # Run the first command and capture the cleaned output, if you want
        # the output without cleaning, simply grab current_output instead.
        interact.send('uname -a')
        interact.expect(prompt)
        cmd_output_uname = interact.current_output_clean

        # Now let's do the same for the ls command but also set a timeout for
        # this specific expect (overriding the default timeout)
        interact.send('ls -l /')
        interact.expect(prompt, timeout=5)
        cmd_output_ls = interact.current_output_clean

        # To expect multiple expressions, just use a list.  You can also
        # selectively take action based on what was matched.

        # Method 1: You may use the last_match property to find out what was
        # matched
        interact.send('~/paramiko_expect-demo-helper.py')
        interact.expect([prompt, 'Please enter your name: '])
        if interact.last_match == 'Please enter your name: ':
            interact.send('Fotis Gimian')
            interact.expect(prompt)

        # Method 2: You may use the matched index to determine the last match
        # (like pexpect)
        interact.send('~/paramiko_expect-demo-helper.py')
        found_index = interact.expect([prompt, 'Please enter your name: '])
        if found_index == 1:
            interact.send('Fotis Gimian')
            interact.expect(prompt)

        # Send the exit command and expect EOF (a closed session)
        interact.send('exit')
        interact.expect()

        # Print the output of each command
        print '-' * 79
        print 'Cleaned Command Output'
        print '-' * 79
        print 'uname -a output:'
        print cmd_output_uname
        print 'ls -l / output:'
        print cmd_output_ls

    except Exception:
        traceback.print_exc()
    finally:
        try:
            client.close()
        except:
            pass
コード例 #31
0
class SSHConn2Machine:
    """
    Creates an SSH Connection to Remote Machine.
    """
    def __init__(self, ServerIPAddress, userName, password):
        self.ServerIPAddress = ServerIPAddress
        self.userName = userName
        self.password = password

        self.logger = SetUpLogger(loggerName='SSH Connection', )

        # SSH Connection object provided by paramiko.
        self.sshClient = None

        # IO Streams to the server.
        self.stdin = None
        self.stdout = None
        self.stderr = None

        # Decrease this if you trust that your server is faster and no command
        # will take more that 2min to process.
        self.sshCommandsTimeout = 120

        # Hold command's output as string with newline chars.
        self.output = ""
        self.exitStatus = None
        self.error = ""

        # Interactive SSH.
        self.interact = None

    def RefreshRecords(self):
        """
        Refresh the connection details locally.
        """
        self.stdin = None
        self.stdout = None
        self.stderr = None

        self.output = ""
        self.exitStatus = None
        self.error = ""

    def SSHConnect(self):
        """
        Create SSH Connection to remote client.
        :return: Create connection object.
        """
        self.logger.info("Creating SSH Connection :{}@{}: with password :{}:".\
                            format(self.userName, self.ServerIPAddress, self.password))

        try:
            # Create a new SSHClient.
            self.sshClient = paramiko.SSHClient()

            # Load host keys from a system (read-only) file.
            self.sshClient.load_system_host_keys()

            # Trust the remote machine and don't reject the connection.
            self.sshClient.set_missing_host_key_policy(
                paramiko.AutoAddPolicy())

            # Connect to an SSH server and authenticate to it.
            self.sshClient.connect(self.ServerIPAddress,
                                   username=self.userName,
                                   password=self.password,
                                   timeout=60)

            self.logger.info("SSH Connection established to {}".\
                                    format(self.ServerIPAddress))

        except Exception as error:
            self.logger.error("SSHConnect raised : {} while connecting to {}".\
                              format(error, self.ServerIPAddress))
            raise error

    def RunCommands(self, command):
        """
        Run param command on ssh client at server.
        Wait for the command to complete or fail.
        return "success" / "fail" in respective cases.
        :param command: ssh command to be run at server.
        :return: command result
        """
        # Clear older command's output and status code.
        self.logger.info("Running CMD > {}".format(command))
        self.RefreshRecords()

        if not self.sshClient:
            self.logger.error(
                "SSH connection is needed before running commands at server")
            raise Exception("SSH connection not present to server")

        try:
            self.stdin, self.stdout, self.stderr = self.sshClient.exec_command(
                command, timeout=self.sshCommandsTimeout)
        except Exception as error:
            self.logger.error(
                "Failed while running ssh command {} at server {} with error {}"
                .format(command, self.ServerIPAddress, error))
            return "fail"

        # ** Immediately check for the exit status of command. ** #

        # Get the SSH transport channel ( follows socket data behaviour ).
        channel = self.stdout.channel

        # Ensure the channel is not closed before going ahead.
        if channel.closed:
            self.logger.error(
                "SSH Channel was closed abruptly after sending cmd")
            return "fail"

        # Reading some stdout data to prevent read block hang.
        stdoutChunks = []
        stdoutChunks.append(channel.recv(1024))

        # Wait until the channel is closed because of transport conn error.
        # Or till there is something to read on recv port, indicating command returned.
        # Or read is available on stderr indicating presence of internal error.

        # Note : Don't use recv_exit_status, it may hold in case read operations are
        #           not run and
        while not channel.closed or channel.recv_ready(
        ) or channel.recv_stderr_ready():
            # Read present on stdout from command.
            if channel.recv_ready():
                stdoutChunks.append(channel.recv(1024))

            # Read present from stderr, indicating command failed.
            elif channel.recv_stderr_ready():
                self.error = self.stderr.channel.recv_stderr(1024)
                self.logger.error(" Received error {} while running command {}".\
                                    format(self.error, command))

                self.exitStatus = channel.recv_exit_status()
                return "fail"

            # There was nothing to read, probably command execution complete,
            # Let's check exit_status_ready to know if command execution is over.
            elif channel.exit_status_ready():
                self.logger.info("Command execution completed")
                break

        # Just confirm that command has nothing pending.
        self.exitStatus = channel.recv_exit_status()

        self.logger.info("Command exit status {}".format(self.exitStatus))
        if not channel.closed:
            # Close the channel.
            channel.close()

        self.logger.info("Output > {}".format(str(stdoutChunks)))

        # get command output in string format.
        for line in stdoutChunks:
            self.output += line

        return "success"

    def GetCmdOutput(self):
        """
        Return command's output.
        :return:
        """
        return self.output

    def GetExitStatus(self):
        """
        Get exit status of commmand.
        :return:
        """
        return self.exitStatus

    def GetError(self):
        """
        Get Error from command execution.
        :return:
        """
        return self.error

    def Close(self):
        """
        Close SSH connection to server.
        """
        self.logger.info("Closed the SSH Client")
        self.sshClient.close()

    def GetInteractiveSSh(self):
        """
        Get an interactive object for running commands.
        """
        try:
            self.interact = SSHClientInteraction(self.sshClient,
                                                 timeout=10,
                                                 encoding='utf-8',
                                                 display=True,
                                                 buffer_size=100000)

        except Exception as error:
            self.logger.error(
                "Couldnt get a SSHClientInteraction session to server")
            raise error

    def expect(self, prompt):
        self.interact.expect(prompt)

    def send(self, command):
        self.interact.send(command)
コード例 #32
0
ファイル: cp5.py プロジェクト: Barkie/Python_first_one
        interact.send('fw tab -t connections -s')
        print('sended IF, expecting >')
        interact.expect('\n.*> ')
        print('ok!')
        cmd_output_uname = interact.current_output_clean
        print(cmd_output_uname)
#        time.sleep(25)
#        output = stdout.readlines()
#        print('current output', output)
#        
#        return output
ssh.connect(hostname=host, username=user, password=passwd)
prompt = 'trevor@test-deb-morgan:~$'
interact = SSHClientInteraction(ssh, timeout=10, display=True)
#interact.expect('>')
interact.send('show interface External')
#interact.send('>')
print('sended IF, expecting >')
interact.expect('\n.*> ')
interact.send('fw tab -t connections -s')
interact.expect('.*> ')
cmd_output_uname = interact.current_output
print(cmd_output_uname)
print('ok!')
#print(cmd_output_uname)

#ssh_connection()
#commands()

#for host in ip_addr_list:
#        print(host)
コード例 #33
0
ファイル: epg2.py プロジェクト: Pigiel/phoenix
def save_config(hostname, ip, username, password):
    """
	Downloads current configuration of Ericsson EPG 2.X node
	
	Args:
		hostname: 	hostname
		ip: 		host's ip address
		username: 	user's login
		password: 	user's password
	
	Returns:
		name of the configuration file or log with connection error
	"""

    PROMPT = '.*\[local\]{}#.*'.format(hostname)
    PROMPT_CFG = '.*{}\(config\)#.*'.format(hostname)
    PROMPT_BASH = '.*bash-.*$.*'
    PROMPT_CONFIRM = '.*[yes,no].*'

    try:
        ssh = paramiko.SSHClient()
        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        ssh.connect(ip, username=username, password=password, timeout=30)
        interact = SSHClientInteraction(ssh,
                                        timeout=60,
                                        display=SSH_DISPLAY_LOGGING)
        interact.expect(PROMPT)
        # Checking software version on the node
        interact.send('start shell')
        interact.expect(PROMPT_BASH)
        interact.send('show_epg_version |grep -v +')
        interact.expect(PROMPT_BASH)
        version = interact.current_output_clean.split('\n')
        interact.send('exit')
        interact.expect(PROMPT)
        # Puts node version into file name
        for line in version:
            if ('version') in line:
                file_name = '{}_{}.xml'.format(hostname, line.split()[4])
        # Save the node configuration
        interact.send('config')
        interact.expect(PROMPT_CFG)
        interact.send('save {}'.format(file_name))
        interact.expect([PROMPT_CFG, PROMPT_CONFIRM])
        if interact.last_match == PROMPT_CONFIRM:
            interact.send('yes')
            interact.expect(PROMPT_CFG)
        interact.send('exit')
        interact.expect(PROMPT)
        # Open SFTP conneciton to download saved config file
        sftp = ssh.open_sftp()
        sftp.get(SFTP_PATH + file_name, TMP_PATH + file_name)
        sftp.close()
        # Delete the configuration file to free up space
        interact.send('delete {}'.format(file_name))
        interact.expect([PROMPT, PROMPT_CONFIRM])
        if interact.last_match == PROMPT_CONFIRM:
            interact.send('y')
            interact.expect(PROMPT)
    except Exception as e:
        # Any exception is logged to file with current date
        file_name = '{}-errors.log'.format(hostname)
        log = DATE + ' : ' + str(e)
        with open(GIT_PATH + hostname + '/' + file_name, 'a') as f:
            f.write(log + '\n')
    finally:
        ssh.close()
    return file_name
コード例 #34
0
    def main_function(self, node_details):
        failed_node = []
        filename = "Reports/Cert_report_" + str(
            datetime.now().strftime("%Y-%m-%d")).split(".")[0] + ".txt"
        modfile = filename.replace(' ', '_').replace(':', '_')
        errorFileName = "Reports/Error_report" + str(
            datetime.now().strftime("%Y-%m-%d")).split(".")[0] + ".txt"
        modErrorFileName = errorFileName.replace(':', '_')
        with open(modfile, mode='a',
                  newline='') as certReport, open(modErrorFileName,
                                                  mode='a',
                                                  newline='') as errorReport:
            try:
                cert_writer = csv.writer(certReport, delimiter=',')
                error_writer = csv.writer(errorReport, delimiter=',')
                print("running for:", node_details[2])
                ssh = paramiko.SSHClient()
                ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
                ssh.connect(node_details[3],
                            username=node_details[4],
                            password=node_details[5])
                interact = SSHClientInteraction(ssh, timeout=60, display=True)
                interact.expect('admin:')
                interact.send('set cli pagination off')
                interact.expect('admin:')
                interact.send('show cert list own')
                interact.expect('admin:')
                CertListOutput = interact.current_output_clean
                certList = self.strip_certificate_name(CertListOutput)
                certList = list(filter(None, certList))
                for cert in certList:
                    interact.send('show cert own ' + cert)
                    interact.expect('admin:')
                    CertNameOutput = interact.current_output_clean
                    cert_details = self.extract_cert_details(
                        node_details[0], node_details[1], node_details[2],
                        cert, CertNameOutput)
                    cert_writer.writerow(cert_details)

                # # trust certs
                # interact.send('show cert list trust')
                # interact.expect('admin:')
                # TrustCertListOutput = interact.current_output_clean
                # TrustCertList = self.strip_certificate_name(TrustCertListOutput)
                # TrustCertList = list(filter(None,TrustCertList))
                # for cert in TrustCertList:
                #     interact.send('show cert trust ' + cert)
                #     interact.expect('admin:')
                #     TrustCertNameOutput  = interact.current_output_clean
                #     TrustCert_details = self.regex_extract_cert_details(node_details[0], node_details[1],node_details[2], cert, TrustCertNameOutput)
                #     cert_writer.writerow(TrustCert_details)
            except paramiko.AuthenticationException:
                print("\nAuthentication failed for node: ", node_details[2],
                      ". Please check the credentials in input file")
                failed_node.append(node_details[2])
            except paramiko.SSHException as SSHException:
                print("\nUnable to establish a SSH connection: ", SSHException)
                print("connection failed for node:", node_details[2])
                failed_node.append(node_details[2])
            except Exception as E:
                print("\nError occurred: ", E)
                print("connection failed for node:", node_details[2])
                failed_node.append(node_details[2])
                #failed node info
            finally:
                for item in failed_node:
                    error_writer.writerow([item])
コード例 #35
0
def login(argv):
    cmds = ''
    hostname = ''
    interval = 1
    out1 = []
    out2 = []
    res_1 = []
    res_2 = []
    prompt = ''
    try:
        opts, args = getopt.getopt(argv, "hc:i:n:",
                                   ["command=", "interval=", "node="])
    except getopt.GetoptError:
        print('deltaScript.py -n <node> -i <interval in secs> -c <command>')
        sys.exit(2)
    for opt, arg in opts:
        if opt == '-h':
            print(
                'deltaScript.py -n <node> -i <interval in secs> -c <command>')
            sys.exit()
        elif opt in ("-i", "--interval"):
            interval = int(arg)
        elif opt in ("-c", "--command"):
            cmds = arg
        elif opt in ("-n", "--node"):
            hostname = arg
    #s = pxssh.pxssh()
    # hostname = raw_input('hostname: ')
    username = input('username: '******'password: '******'\n')
        interact.expect(prompt)
        interact.send('environment time-stamp')
        interact.expect(prompt)
        interact.send('environment no more')
        interact.expect(prompt)
        cmd_output = interact.current_output_clean
        #interact.send(cmd_output)
        #print(cmd_output)
        #s.sendline('environment time-stamp')
        #s.prompt()
        #s.sendline('environment no more')
        #s.prompt()
        for cmd in cmds.split(";"):
            #s.sendline(cmd)
            interact.send(cmd)
            #s.prompt()  # match the prompt
            interact.expect(prompt)
            #out1.append(s.before)
            out1.append(interact.current_output)
            #print(out1[-1])
        # print(s.before)    # print everything before the prompt.
        # s.prompt ()
        # s.sendline ('sleep ' + str(interval))
        time.sleep(interval)
        # s.prompt ()         # match the prompt
        for cmd in cmds.split(";"):
            #s.sendline(cmd)
            interact.send(cmd)
            #s.prompt()  # match the prompt
            interact.expect(prompt)
            #out2.append(s.before)
            out2.append(interact.current_output)
            # print len(out2)
        # print(s.before)    # print everything before the prompt.
        print("The prompt is " + prompt)
        #s.sendline('logout')
        #s.close()
        #print (out1)
        #print (out2)
        for (aOut1, aOut2) in zip(out1, out2):
            #print(aOut1.decode('utf-8').split("\r")[-2])
            #print(aOut2.decode('utf-8').split("\r")[-2])
            #res_1.append(parse(aOut1.decode('utf-8').split("\r")))
            #res_2.append(parse(aOut2.decode('utf-8').split("\r")))
            #print(aOut1)
            #print(aOut2)
            print(aOut1.split("\n")[-2])
            print(aOut2.split("\n")[-2])
            res_1.append(parse(aOut1.split("\n")))
            res_2.append(parse(aOut2.split("\n")))
        # print (res_1)
        # print (res_2)
        for (aRes_1, aRes_2) in zip(res_1, res_2):
            delta(aRes_1, aRes_2, interval)
コード例 #36
0
def login(server_ip, os_user, os_pass):
    output = []
    ssh = paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    #print('server_ip:',server_ip)
    ssh.connect(server_ip, username=os_user, password=os_pass)
    interact = SSHClientInteraction(ssh, timeout=90, display=True)

    # "display=True" is just to show you what script does in real time. While in production you can set it to False
    interact.expect('admin:')
    interact.send(
        "run sql select paramname,paramvalue from processconfig where paramname='RollBackToPreGrayback'"
    )
    interact.expect('admin:')
    output.append(interact.current_output)
    interact.send(
        "run sql select paramname,paramvalue from processconfig where paramname='ClusterSecurityMode'"
    )
    interact.expect('admin:')
    output.append(interact.current_output)
    interact.send("show itl")
    interact.expect('admin:')
    output.append(interact.current_output)
    interact.send("show ctl")
    interact.expect('admin:')
    output.append(interact.current_output)
    #interact.send("file view install system-history.log")
    #interact.expect('admin:')
    interact.send("utils disaster_recovery history backup")
    interact.expect('admin:')
    output.append(interact.current_output)
    interact.send("utils service list")
    interact.expect('admin:')
    output.append(interact.current_output)
    #interact.send("utils network connectivity",) #Need to come back here this comman is not what I thought will want to run to each node.
    #interact.expect(['admin:', 'Continue (y/n)?'])
    #if interact.last_match == 'Continue (y/n)?':
    #        interact.send('y')
    #        interact.expect('admin:')
    #interact.expect("This command can take up to 3 minutes to complete.\nContinue (y/n)?")
    #interact.send("y")
    #interact.expect('admin:')
    interact.send("utils core active list")
    interact.expect('admin:')
    output.append(interact.current_output)
    interact.send("utils ntp status")
    interact.expect('admin:')
    output.append(interact.current_output)
    interact.send("utils dbreplication runtimestate")
    interact.expect('admin:')
    output.append(interact.current_output)
    interact.send("show network cluster")
    interact.expect('admin:')
    output.append(interact.current_output)
    interact.send("show status")
    interact.expect('admin:')
    output.append(interact.current_output)
    interact.send("utils diagnose test")
    interact.expect('admin:')
    output.append(interact.current_output)
    interact.send("utils system upgrade status")
    interact.expect('admin:')
    output.append(interact.current_output)
    ssh.close()
    ip_file_name = server_ip.replace('.', '_')
    ip_file_name2 = "Health_Check_" + ip_file_name
    output_file = '{}.txt'.format(ip_file_name2)
    with open(output_file, 'w') as out:
        for command in output:
            out.write("%s\n" % command)
def main():
    # Use SSH client to login
    try:
        # Create a new SSH client object
        ssh = paramiko.SSHClient()

        # Set SSH key parameters to auto accept unknown hosts
        ssh.load_system_host_keys()
        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())

        # Connect to the host
        ssh.connect(hostname=host, username=user, password=passwd)

        # Create a client interaction class which will interact with the host
        interact = SSHClientInteraction(ssh, timeout=5, display=True)
        interact.expect(prompt)

        # Run the first command and capture the cleaned output, if you want
        # the output without cleaning, simply grab current_output instead.
        interact.send('netstat -rnv')
        interact.expect(prompt)
        route_list = interact.current_output_clean
        expert_mode()
        exp_cmd_output = interact.current_output_clean
        # To expect multiple expressions, just use a list.  You can also
        # selectively take action based on what was matched.

        # Method 1: You may use the last_match property to find out what was
        # matched
        #interact.send('~/paramiko_expect-demo-helper.py')
        #interact.expect([prompt, 'Please enter your name: '])
        #if interact.last_match == 'Please enter your name: ':
        #    interact.send('Fotis Gimian')
        #    interact.expect(prompt)

        # Method 2: You may use the matched index to determine the last match
        # (like pexpect)
        #interact.send('~/paramiko_expect-demo-helper.py')
        #found_index = interact.expect([prompt, 'Please enter your name: '])
        #if found_index == 1:
        #    interact.send('Fotis Gimian')
        #    interact.expect(prompt)

        # Send the exit command and expect EOF (a closed session)
        #interact.send('exit')
        #interact.expect()

        ## Print the output of each command
        #print '-'*79
        #print 'Cleaned Command Output'
        #print '-'*79
        #print 'uname -a output:'
        #print cmd_output_uname
        #print 'ls -l / output:'
        #print cmd_output_ls

    except Exception:
        traceback.print_exc()
    finally:
        try:
            client.close()
        except:
            pass
コード例 #38
0
def main(i):
    # Use SSH client to login
    try:
        # Create a new SSH client object
        ssh = paramiko.SSHClient()

        # Set SSH key parameters to auto accept unknown hosts
        ssh.load_system_host_keys()
        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        file = open('c:/python/checkpoint/{0}.txt'.format(host),"a")
        # Connect to the host
        ssh.connect(hostname=host, username=user, password=passwd)

        # Create a client interaction class which will interact with the host
        interact = SSHClientInteraction(ssh, timeout=5, display=True)
        interact.expect(prompt)

        # Run the first command and capture the cleaned output, if you want
        # the output without cleaning, simply grab current_output instead.
        interact.send('netstat -rnv')
        interact.expect(prompt)
        route_list = 'netstat -rnv \n' + interact.current_output_clean

        # Now let's do the same for the ls command but also set a timeout for
        # this specific expect (overriding the default timeout)
        #interact.send('ls -l /')
        #interact.expect(prompt, timeout=5)
        #cmd_output_ls = interact.current_output_clean
        interact.send('expert')
        entering_expert_index = interact.expect([no_expert_pass, enter_expert_pass])
        if entering_expert_index == 0:
            print('no expert password, need to set it')
            no_expert_password = interact.current_output_clean
            set_expert_pass = no_expert_password
            file.write(set_expert_pass)
            file.close()
            ws.write(i, 1, 'No Expert Password. Need to set up.')
            i += 1
        elif entering_expert_index == 1:
            print('cp asked for expert password, entering it')
            interact.send(expert_passwd)
            expert_mode_index = interact.expect([wrong_expert_pass, expert_prompt])
            if expert_mode_index == 0:
                print('wrong expert pass')
                wrong_expert_pass_output = interact.current_output_clean                
                file.write(wrong_expert_pass_output)
                file.close()
                ws.write(i, 1, 'Wrong Expert Password')
                i += 1
            elif expert_mode_index == 1:
                print('password ok, continuing')
                interact.send('cat /etc/sysconfig/netconf.C')
                interact.expect(expert_prompt)
                netconf = 'cat /etc/sysconfig/netconf.C \n' + interact.current_output_clean
                
                interact.send('cat /etc/hosts.allow')
                interact.expect(expert_prompt)
                hosts = 'cat /etc/hosts.allow \n' + interact.current_output_clean

                interact.send('cat /etc/hosts')
                interact.expect(expert_prompt)
                hosts1 = 'cat /etc/hosts \n' + interact.current_output_clean

                interact.send('cat /etc/passwd')
                interact.expect(expert_prompt)
                passwords = 'cat /etc/passwd \n' + interact.current_output_clean\

                interact.send('cat /etc/resolv.conf')
                interact.expect(expert_prompt)
                resolv = 'cat /etc/resolv.conf \n' + interact.current_output_clean

                interact.send('cat /etc/sysconfig/ntp')
                interact.expect(expert_prompt)
                ntp = 'cat /etc/sysconfig/ntp \n' + interact.current_output_clean
                output = sk1+route_list+sk1+netconf+sk1+hosts+sk1+hosts1+sk1+passwords+sk1+resolv+sk1+ntp
                file.write(output)
                file.close()
                ws.write(i, 1, 'OK')
                i += 1

    except TimeoutError:
        file = open('c:/python/checkpoint/{0}.txt'.format(host),"a")
        file.write('Connection Failed')
        file.close
        ws.write(i, 1, 'Connection Failed')
        i += 1
        
    except Exception:
        traceback.print_exc()
        errorstatus = 'connection failed'
        file = open('c:/python/checkpoint/{0}.txt'.format(host),"a")
        file.write('Connection Failed(exception)')
        file.close()
        ws.write(i, 1, 'UnknownError')
        i += 1
    finally:
        try:
            ssh.close()
        except:
            pass              
    return i