Exemplo n.º 1
0
    def sshOpen(self, timeout=5):
        "Opens a SSH connection to the mgmt LXC."
        if self._ssh_interact is not None:
            return self._ssh_interact

        self.log(WARN, 'Acquiring LXC SSH session')
        self._ssh_client = paramiko.SSHClient()
        paramiko.hostkeys.HostKeys(filename=os.devnull)
        # client.load_system_host_keys()
        self._ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        # the below might update self._lxc_host if the env var is set during
        # the execution of getLXCPort().
        port = self.getLXCPort()
        try:
            self._ssh_client.connect(hostname=self._lxc_host,
                                     username=self._username,
                                     pkey=None,
                                     look_for_keys=False,
                                     allow_agent=False,
                                     password=self._password,
                                     port=port)
        except (paramiko.AuthenticationException, paramiko.SSHException) as e:
            self.log(CRITICAL, 'SSH connect failed: %s' % e)
            return None

        self._ssh_interact = SSHClientInteraction(self._ssh_client,
                                                  timeout=timeout,
                                                  display=self.isLogDebug())
        return self._ssh_interact
Exemplo n.º 2
0
 def __init__(self, appliance):
     SSHClientInteraction.__init__(
         self,
         appliance.ssh_client,
         timeout=10,
         display=True,
         output_callback=logging_callback(appliance))
Exemplo n.º 3
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)
Exemplo n.º 4
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')
Exemplo n.º 5
0
    def start_session(self):
        self.client.connect(hostname=self._hostname,
                            username=self._username,
                            password=self._password)

        interact = SSHClientInteraction(self.client, timeout=10, display=True)
        interact.expect(PROMPT)
        self._session = interact
Exemplo n.º 6
0
 def expect(self, re_string, *args, **kwargs):
     try:
         SSHClientInteraction.expect(self, re_string, *args, **kwargs)
     except socket.timeout:
         current_output = '""' if not self.current_output else self.current_output
         raise SSHExpectTimeoutError(
             f"Timeouted when waiting for '{re_string}'. Current output:\n"
             + textwrap.indent(current_output, '> '))
Exemplo n.º 7
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)
Exemplo n.º 8
0
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
Exemplo n.º 9
0
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)
Exemplo n.º 10
0
    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
Exemplo n.º 11
0
	def upgrade3228Fpga(self):
		try:
			client = paramiko.SSHClient()
			client.load_system_host_keys()
			client.set_missing_host_key_policy(paramiko.AutoAddPolicy)

			client.connect(self.ip, username=self.username, password=self.password)

			with SSHClientInteraction(client, timeout=10, display=True) as exp:
				exp.expect([".*#\s+", ".*\$\s+"])
				exp.send("wget -c -O /tmp/bcm3228.bin ftp://%s/%s"%(  self.ftpdip, self.fpga_file ))
#				exp.send("tftp -g -l /tmp/bcm3228.bin -r %s %s"%(   self.fpga_file , self.ftpdip ))
				exp.expect([".*#\s+", ".*\$\s+"])
				exp.send("proxy_stdio_client docsiscore\n")
				exp.send("cd /\n")
				exp.expect("CMTS>\s+")
				exp.send("/hal/download_3228_fpga /tmp/bcm3228.bin\n")
				exp.expect(".*Success.*",timeout=180)
			return True
		except socket.timeout:
			self.logger.error("upgrade 3228 fpga error")
			return False
		finally:
			try:
				client.close()
			except:
				pass
Exemplo n.º 12
0
def dump(host, commands, date, save_dir):
    # 1: Cisco enable mode, 2: Linux prompt, you may need to add prompt expression
    PROMPT = ['.*>\s*', '.*#\s*', '.*$\s*']
    print('Taking {} backup configuration file'.format(host[0]))
    hostname, ipaddress, username, password = host[0], host[1], host[2], host[3]

    try:
        client = paramiko.SSHClient()
        client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        client.connect(hostname=ipaddress, username=username, password=password, timeout=10, look_for_keys=False)

        with SSHClientInteraction(client, timeout=10, display=True) as interact:
            interact.send('')
            index = interact.expect(PROMPT)
            interact.expect('.*#\s')

            for command in commands:
                interact.send('')
                interact.expect('.*#\s')
                interact.send('n')
                interact.expect('.*#\s')
                output = interact.current_output_clean
                filename = hostname + '_' + date + '.txt'
                path = os.path.join(save_dir, filename)
                with open(path, 'a') as config_file:
                    config_file.write(str(output) + '\n')
            interact.send('exit')
            index = interact.expect(PROMPT)

    except Exception as e:
        print('Exception throws: {}'.format(e.args))
def test_05_context():
    client = paramiko.SSHClient()
    client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    client.connect(hostname="localhost", username="******", port=2222, key_filename='./test/id_rsa')
    with SSHClientInteraction(client, timeout=10, display=True) as interact:
        interact.send('ls -all /')
        interact.expect(prompt, timeout=120)
Exemplo n.º 14
0
def interact_with_ssh_connection(client, prompt_line = '.*@.*:.*', TIMEOUT=60*30):
    with SSHClientInteraction(client, timeout=TIMEOUT, display=True) as interact:
        need_to_exit=False
        interact.expect(prompt_line)
        while not need_to_exit:
            data = input(">")
            if "exit" in data:
                need_to_exit = True
            interact.send(data)
            interact.expect(prompt_line)
Exemplo n.º 15
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()
def install_k8s_plugin(pn_ssh_conn, plugin):
    try:
        panorama_op_prompt = '.*> '
        with SSHClientInteraction(pn_ssh_conn, timeout=10, display=False) as interact:
            interact.send("request plugins install {}".format(plugin))
            interact.expect(panorama_op_prompt)
            interact.send('exit')
            info("Plugin {} installation triggered".format(plugin))
    except:
        error("I couldn't install the kubernetes plugin. Try to install it manually.")
        sys.exit()
def download_plugin(pn_ssh_conn, plugin):
    try:
        panorama_op_prompt = '.*> '
        with SSHClientInteraction(pn_ssh_conn, timeout=10, display=False) as interact:
            interact.send("request plugins download file {}".format(plugin))
            interact.expect(panorama_op_prompt)
            interact.send('exit')
            info("Plugin {} downloading.".format(plugin))
    except:
        error("I couldn't download the kubernetes plugin. Try to download it manually.")
        sys.exit()
Exemplo n.º 18
0
def cucm_connect(ip, username, password):
    #
    # Create and return the connection to a CUCM node
    #
    ssh = paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    ssh.connect(ip, username=username, password=password)
    #
    # Set display=False for production
    #
    connection = SSHClientInteraction(ssh, timeout=60, display=True)
    return connection
Exemplo n.º 19
0
def main():
    # Set login credentials and the server prompt
    HOSTNAME = '192.168.1.177'
    USERNAME = '******'
    PASSWORD = '******'
    PROMPT = '~#'

    # 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
        with SSHClientInteraction(client, timeout=10,
                                  display=True) as interact:
            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

            interact.send("amixer -c1 sget OutputMode")
            interact.expect("Item0:")
            interact.send("amixer -c1 sset OutputMode EQ")
            interact.expect("EQ:")

            # 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)

    except Exception:
        traceback.print_exc()
    finally:
        try:
            client.close()
        except Exception:
            pass
def configure_collector_group(pn_ssh_conn, cg):
    try:
        panorama_config_prompt = '.*# '
        with SSHClientInteraction(pn_ssh_conn, timeout=10, display=False) as interact:
            interact.send('configure')
            interact.expect(panorama_config_prompt)
            interact.send('set log-collector-group {}'.format(cg))
            interact.expect(panorama_config_prompt)
            interact.send('exit')
    except:
        error("I can not create a device group")
        sys.exit()
Exemplo n.º 21
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)
Exemplo n.º 22
0
    def change_pwd(self, verbose):
        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
            proxy = None
            if self.proxy is not None:
                proxy = paramiko.ProxyCommand(self.proxy)
            client.connect(hostname=self.hostname, timeout=20, sock=proxy,
                           username=self.username, password=self.oldpwd)

            with SSHClientInteraction(
                    client, timeout=10, display=False,
                    output_callback=lambda m: self.log_msg(m)) \
                    as interact:
                found_index = interact.expect(
                    [Host.CONST_PROMPT, Host.CONST_OLDPWPROMPT])
                if found_index == 0:
                    interact.send("passwd")
                    interact.expect(Host.CONST_OLDPWPROMPT)

                interact.send(self.oldpwd)
                interact.expect(Host.CONST_NEWPWPROMPT)
                interact.send(self.newpwd)
                interact.expect(Host.CONST_NEWPWPROMPT2)
                interact.send(self.newpwd)

                if found_index == 0:
                    interact.expect(Host.CONST_SUCCESSMSG)
                    interact.send('exit')
                interact.expect()
                self.changed = True
                client.close()

        except Exception:
            self.log_msg(traceback.format_exc())
        finally:
            try:
                client.close()
            except Exception:
                pass
        status = HostStatus(self.hostname, self.changed)
        Host.updated.append(status)
        if verbose:
            status.print_status()
            if not self.changed:
                print(self.log)
Exemplo n.º 23
0
 def config(self, config_cmds, verbose=True):
     try:
         config_cmds.insert(0, 'system-view')
         with SSHClientInteraction(self.client, timeout=20,
                                   display=verbose) as interact:
             interact.expect('<[\S\s]+>')
             for cmd in config_cmds:
                 interact.send(cmd)
                 interact.expect('\[[\S\s]+\]')
     except Exception as e:
         print(e)
     finally:
         self.client.close()
Exemplo n.º 24
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
Exemplo n.º 25
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()
Exemplo n.º 26
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)
def configure_template(pn_ssh_conn, template):
    try:
        panorama_config_prompt = '.*# '
        with SSHClientInteraction(pn_ssh_conn, timeout=10, display=False) as interact:
            interact.send('configure')
            interact.expect(panorama_config_prompt)
            interact.send('set template {} config  vsys vsys1'.format(template))
            interact.expect(panorama_config_prompt)
            interact.send('set template {} settings default-vsys vsys1'.format(template))
            interact.expect(panorama_config_prompt)
            interact.send('exit')
            info("Template {} Created".format(template))
    except:
        error("I can not create a template")
        sys.exit()
def configure_template_stack(pn_ssh_conn, template_stack):
    try:
        panorama_config_prompt = '.*# '
        with SSHClientInteraction(pn_ssh_conn, timeout=10, display=False) as interact:
            interact.send('configure')
            interact.expect(panorama_config_prompt)
            interact.send('set template-stack {} settings'.format(template_stack))
            interact.expect(panorama_config_prompt)
            interact.send('set template-stack {} templates {}'.format(template_stack,template_stack + '-tmp'))
            interact.expect(panorama_config_prompt)
            interact.send('exit')
            info("Template Stack {} Created".format(template_stack))
    except:
        error("I can not create a template stack")
        sys.exit()
Exemplo n.º 29
0
def test_08_issue_25_skip_newline():
    client = paramiko.SSHClient()
    client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    client.connect(hostname="localhost", username="******", port=2222, key_filename='./test/id_rsa')
    with SSHClientInteraction(client, timeout=10, display=True) as interact:
        interact.send('ls -all')
        interact.expect(prompt, timeout=5)

        # Do not actually sleep, send a ctrl-c at the end
        interact.send('sleep 1', newline=chr(3))
        interact.expect(prompt, timeout=5)
        interact.send('sleep 1' + chr(3), newline='')
        interact.expect(prompt, timeout=5)

        interact.send('ls -all')
        interact.expect(prompt, timeout=5)
def create_auth_key(pn_ssh_conn):
    try:
        duration = 48
        panorama_op_prompt = '.*> '
        with SSHClientInteraction(pn_ssh_conn, timeout=10, display=False) as interact:
            interact.send("request bootstrap vm-auth-key generate lifetime {}".format(duration))
            interact.expect(panorama_op_prompt)
            interact.send('exit')
        auth_key_output = interact.current_output_clean
        for l in auth_key_output.split('\n'):
            if 'generated' in l:
                auth_key = re.findall(r"\d{15,}", l)[0]
                return auth_key.strip()
    except:
        error("I couldn't create bootstrapping auth key")
        sys.exit()
def activate_license(pn_ssh_conn, auth_code, tokens=1):
    # Add CN-Series auth code
    try:
        info("Applying CN-Series Authcode {} and activating {} token(s)".format(auth_code, tokens))
        panorama_op_prompt = '.*> '
        with SSHClientInteraction(pn_ssh_conn, timeout=10, display=False) as interact:
            interact.send("request plugins kubernetes set-license-tokens authcode {} token-count {}".format(auth_code, tokens))
            interact.expect(panorama_op_prompt)
            authcode_output = interact.current_output_clean
            if 'Error' in authcode_output:
                error(authcode_output.split('\n')[-3])
                error("Auth code can not be added. CN-Series can run for 4 hours. without license.")
            else:
                info("CN-Series license auth code {} added and {} tokens activated".format(auth_code,tokens))
    except:
        error("Auth code can not be added. CN-Series can run for 4 hours. without license.")
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
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
Exemplo n.º 34
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
Exemplo n.º 35
0
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)
Exemplo n.º 36
0
        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)
#        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()
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
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