用于远程登录 DUT 的 Python 代码需要进一步优化



我需要进一步优化我在Python中的代码。

我之前在被测设备上逐步执行命令,这很多,因为我还需要睡眠定时器。但是,我能够通过列表并在 for 循环中调用列表的元素来最小化它:

我需要您的输入来进一步优化此代码:

ConfigListBFD = ['conf t' , 'int Fa1/0' , 'ip address 10.10.10.1 255.255.255.0', 'no shut']
for i in ConfigListBFD:
    tn.write(i.encode('ascii') + b"n")
    print (i, "command entered successfully")
    time.sleep(2)

请注意:我正在远程修复 DUT,因为不支持 ssh。

我正在为telnet使用这个优化的通用代码。 我们可以创建一个通用文件,您可以在其中添加此方法

import telnetlib
import time
def telnet(host):
    user = <username>
    password = <password>
    try :
        tn = telnetlib.Telnet(host)
    except :
        print("Unable to connect")
        sys.exit()
    tn.read_until(b"Username:") # read until username prompt 
    tn.write(user.encode('ascii') + b"n")
    if password:
        tn.read_until(b"password:") #read until password prompt
        tn.write(password.encode('ascii') + b"n")
    tn.read_until(b"#")
    return tn   #return telnetlib handle

而不是将此方法导入到另一个文件,我们在其中编写脚本