我使用下面的代码逐行读取带有主机地址的txt文件,但当代码创建并写入日志文件时,会使用引号和“?”字符进行写入:
代码如下:
import getpass
import sys
import telnetlib
user = "cisco"
password = "cisco"
file = open('hosts.txt', 'r')
for line in file:
tn = telnetlib.Telnet(line)
tn.read_until("Username: ")
tn.write(user + "\n")
tn.read_until("Password: ")
tn.write(password + "\n")
tn.write("enable \n")
tn.write(password + "\n")
tn.write("sh ver | i revision \n")
tn.write("exit \n")
str_all = tn.read_all()
log = open(line + ".txt","w")
log.write(str_all)
tn.close()
所以创建的文件是:
[temp@ser1 Projeto]$ ls
21.10.176.4?.txt clean_up_819 hosts.txt master.py test1.txt teste.txt
然后,当我使用cat时,文件用问号表示:
[noctemp@svcactides Projeto_QoS]$ cat '21.10.176.4
.txt'
有没有办法保存到一个名为21.10.176.4.txt的文件中
文件名没有引号;这些是通过shell的tab completion添加的,以保护它所拥有的新行
换行符来自
line
,这样您就可以检测最后一行是否有换行符(并且在重新编写类似文件时也很方便)。见How can I remove (chomp) a newline in Python?相关问题 更多 >
编程相关推荐