import os
import telnetlib
import tempfile
import time
username = 'luotao'
password = 'xxxxxxx'
command1 = 'show run'
command2 = 'quit'
device_ip = '10.160.3.201'
client = telnetlib.Telnet(device_ip, port=23) # 生成一个telnet对象
client.write(username.encode('ascii') + b"\n")
client.write(password.encode('ascii') + b"\n")
if command1: # 如果有这个自动翻页命令的话
client.write(command1.encode('ascii') + b"\n")
client.write(command2.encode('ascii') + b"\n")
time.sleep(1)
output = client.read_very_eager()
client.close()
fd, config_file = tempfile.mkstemp(text=True) # 创建一个临时文件,[1]表示临时文件的绝对路径
# temp_file.mkstemp 返回的是两个参数,一个是fd,一个是f_name,fd是文件描述符,f_name是指生成的文件的绝对路径。
with open(config_file, "w", encoding="utf-8") as f: # 打开这个临时文件
f.write(output.decode("utf-8")) # 写入配置
print(f)
os.close(fd)
结果:
<_io.TextIOWrapper name='C:\Users\SZ-IT-~1\AppData\Local\Temp\tmp0j93b6az' mode='w' encoding='utf-8'>
打开生成的临时文件
C:\Users\SZ-IT-~1\AppData\Local\Temp\tmp0j93b6az
发现获取的结果里面,每一行下面都新增了一个空行
我初步了解,read_very_eager()获取的二进制代码,换行代码是\r\n,可能是这个原因导致了多出了一行。
我不需要这些空行,请问有办法解决吗?