Python如何生成文件名
我想知道社区是否能帮助我,我是个编程新手。我试图ssh到“list.txt”上包含的设备列表,一旦它登录到路由器,我会向每个设备发送相同的命令,并将输出写入文件。但是,在下面的代码上,它会覆盖每个设备的输出。我需要为每个输出创建一个唯一的文件,文件名为“list.txt”文件中包含的IP地址。如果有人能帮我,我将不胜感激Python如何生成文件名,python,ssh,Python,Ssh,我想知道社区是否能帮助我,我是个编程新手。我试图ssh到“list.txt”上包含的设备列表,一旦它登录到路由器,我会向每个设备发送相同的命令,并将输出写入文件。但是,在下面的代码上,它会覆盖每个设备的输出。我需要为每个输出创建一个唯一的文件,文件名为“list.txt”文件中包含的IP地址。如果有人能帮我,我将不胜感激 import paramiko import time import os def disable_paging(remote_conn): '''Disable
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()
您可以在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”的内容很困难)。你只需要一个唯一的文件名吗?理想的做法是从我的list.txt文件创建一个IP地址的文件名。如果不可能,那么是的,因为我将有5个IPs 5个输出。提前谢谢你!!!谢谢我试试看。顺便说一句,list.txt文件的内容只包含一个IP地址列表,每行一个IP。