我有以下列表
['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
由于
答案 0 :(得分:1)
能够多次对不同值执行某些操作的编程概念是迭代。在Python中,您可以轻松地迭代许多内容,例如列表,文件中的行,或者在本例中是正则表达式匹配。
在最简单的迭代示例中,您使用“for list in 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')