如何将 telnet 输出日志保存到文本文件

问题描述

大家好,请问我如何将输出日志保存到此脚本的文本文件中以解决此问题

    import sys
    import telnetlib
    import getpass
    #####################
    ###### Define Host
    host=["192.168.1.164","192.168.1.169"]
    devno=len(host)
    user='ali'
    Password='cisco'

    for i in range(devno):
        print('*'*50 + ' Connected to device : '+str(host[i]) +'*'*50)
        tn=telnetlib.Telnet(host[i])
        tn.read_until(b'Username: ')
        tn.write(user.encode('ascii')+ b'\n')
        tn.read_until(b'Password')
        tn.write(Password.encode('ascii')+b'\n')
        #tn.write(b'enable' + b'\n')
        #tn.write(b"\n")
        #tn.write(b"terminal length 0\n")
        #tn.write(b"show run\n")
        #tn.write(b' show ip route\n')
        tn.write(b'  exit\n')
        print(tn.read_all().decode('ascii'))

解决方法

你可以在 for 循环的末尾添加这个

    with open("text1.txt","w") as f:
            f.write(str(tn.read_all().decode("ascii")))

以上应该将命令的输出保存到文件中

如果您还想获取日志,则需要在退出前添加以下内容

    tn.write(b' show log\n')