[英]Save loop outputs into variables
我有以下清单
['200', '530', '540']
列表的大小是动态的。 它取决于ssh_conn.rec
的输出。 我需要获取这些值并为列表中的每个值运行以下命令
ssh_conn.send('show running-config crypto map | i 200\n')
ssh_conn.send('show running-config crypto map | i 530\n')
ssh_conn.send('show running-config crypto map | i 540\n')
我有可以使用循环的填充,但是我不确定在代码下面如何做:
#!/usr/bin/env python
import paramiko
import time
import re
# Variables
host = xxxx = 'xxxxx'
# Create instance of SSHClient object
ssh = paramiko.SSHClient()
# Automatically add untrusted hosts
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
# Automatically add untrusted hosts
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
# initiate SSH connection
ssh.connect('xxxxx', port=22, username='xxxx', password='xxxxx', look_for_keys=False, allow_agent=False)
print "SSH COnnection established with %s" % host
# Use invoke_shell to establish an 'interactive session'
ssh_conn = ssh.invoke_shell()
print "Interactive SSH session established"
print "Give the name of the 3PPartner\n"
partner = raw_input('>')
# Commands prompted
ssh_conn.send('\n')
ssh_conn.send('enable\n')
time.sleep(.5)
ssh_conn.send('xxxxx\n')
time.sleep(.5)
ssh_conn.send("terminal pager 0\n")
time.sleep(.5)
ssh_conn.send('show running-config crypto map | i ' + str(partner) + '\n')
time.sleep(1)
output = ssh_conn.recv(65535)
print output
crypto_list = re.findall("OUTSIDEMAP (\d+) match",output)
print crypto_list
产量
python IPSEC_config_attributes.py
SSH COnnection established with XXXX
Interactive SSH session established
Give the name of the 3PPartner
>XXXX
Type help or '?' for a list of available commands.
XXXX/pri/act>
XXXX/pri/act> enable
Password: ************
XXXX/pri/act# terminal pager 0
XXXX/pri/act# show running-config crypto map | i XXX
crypto map OUTSIDEMAP 200 match address XXXX
crypto map OUTSIDEMAP 530 match address XXXX
crypto map OUTSIDEMAP 540 match address XXXX
XXXX/pri/act#
['200', '530', '540']
200
530
540
Logged out of device XXXXXXXX
谢谢
能够多次执行不同值操作的编程概念是迭代。 在Python中,您可以轻松地遍历许多事物,例如列表,文件中的行,或者在这种情况下,是正则表达式匹配。
在最简单的迭代示例中,使用“ for list中的项目”构造具有一个变量item,该变量接收列表中的每个值。 要为每个匹配执行命令,您将使用类似以下的命令:
crypto_list = re.findall("OUTSIDEMAP (\d+) match",output)
for match in crypto_list:
ssh_conn.send('show running-config crypto map | i ' + match + '\n')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.