Telnet脚本在函数内部不起作用

2024-10-03 19:33:34 发布

您现在位置:Python中文网/ 问答频道 /正文

在函数外,脚本工作,但在函数内,脚本不工作。你知道吗

import telnetlib
import sys

def teltest():

    host = "192.168.2.2"
    user = "admin"
    password = "admin"
    tn = telnetlib.Telnet(host)
    tn.read_until("Username:")
    tn.write(user + "\n")
    tn.read_until("Password:")
    tn.write(password + "\n")
    tn.write("enable\n")
    tn.write("config t\n")
    tn.write("interface eth 0/0/13\n")
    tn.write("description TEST\n")

teltest()

为什么?我怎样才能修复它?你知道吗


Tags: 函数import脚本hostreadadmindefsys
1条回答
网友
1楼 · 发布于 2024-10-03 19:33:34

这是因为函数在正确终止连接之前返回,使设备的另一端处于元状态。如注释中所述,在末尾添加一个sleep将为清理连接腾出空间,从而执行写入设备的操作。你知道吗

Telnet.write(buffer) Write a string to the socket, doubling any IAC characters. This can block if the connection is blocked. May raise socket.error if the connection is closed.

import telnetlib
import sys

def teltest():
    host = "192.168.2.2"
    user = "admin"
    password = "admin"
    tn = telnetlib.Telnet(host)
    tn.read_until("Username:")
    tn.write(user + "\n")
    tn.read_until("Password:")
    tn.write(password + "\n")
    tn.write("enable\n")
    tn.write("config t\n")
    tn.write("interface eth 0/0/13\n")
    tn.write("description TEST\n")
    time.sleep(1)

teltest()

尽管op从评论中得到了帮助,但为了社区的利益,还是将此作为一个答案发布。你知道吗

相关问题 更多 >