我想知道社区能否帮助我成为编程的新手。我试图ssh到包含on" list.txt"的设备列表一旦它登录到路由器,我就向每个命令发送相同的命令并将输出写入文件。但是,在下面的代码中,它会覆盖每个设备的输出。我需要为每个输出创建一个唯一的文件,其中包含" list.txt"中包含的IP地址的名称。文件。如果有人可以帮助我,我真的很感激。
import paramiko
import time
import os
def disable_paging(remote_conn):
'''Disable paging on a Cisco router'''
remote_conn.send("terminal length 0\n")
time.sleep(1)
# Clear the buffer on the screen
output = remote_conn.recv(1000)
return output
#Create variables
f = open('list.txt')
filepath = ('test/tas.txt')
username = 'test'
password = 'test'
#Create a for loop
for i in f:
remote_conn_pre = paramiko.SSHClient()
remote_conn_pre.set_missing_host_key_policy(
paramiko.AutoAddPolicy())
remote_conn_pre.connect(i, username=username, password=password)
remote_conn = remote_conn_pre.invoke_shell()
output = remote_conn.recv(1000)
disable_paging(remote_conn)
# Now let's try to send the router a command
remote_conn.send("\n")
remote_conn.send("show int des\n")
# Wait for the command to complete
time.sleep(2)
output = remote_conn.recv(88880000)
# print output
if not os.path.exists(os.path.dirname(filepath)):
os.makedirs(os.path.dirname(filepath))
with open(filepath, "w") as f:
f.write(output)
f.close()
答案 0 :(得分:0)
您可以在for循环中定义'filepath'变量,并使用'i'字符串创建它:
for i in f:
filename = 'tas_%s.txt' % str(i)
filepath = os.path.join('test', filename)
# anything else remains unchanged
希望它有效(在不知道'list.txt'的内容的情况下很难)。