Пример #1
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()
Пример #2
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()
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)
Пример #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)
    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])
Пример #6
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')
Пример #7
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
Пример #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
Пример #9
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))
Пример #10
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
Пример #11
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)
Пример #12
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
Пример #13
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
Пример #14
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)
Пример #15
0
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
Пример #16
0
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
Пример #17
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)
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()
Пример #20
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)
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()
Пример #22
0
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
Пример #23
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
Пример #24
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
Пример #25
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()
Пример #26
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)
Пример #27
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()
Пример #28
0
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()
Пример #29
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()
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()