Telnetlib的read_until在Python中将不会读取预期字符串。有哪些备选方案?

2024-09-30 16:28:54 发布

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

import getpass
import sys
import telnetlib

host = "10.28.103.126"
user = b"apc"
password = b"apc"
outlet = b"8"

tnObject = telnetlib.Telnet(host)
print("yes")
tnObject.read_until(b"User Name :")
tnObject.write(user + b"\n")
print("sent user")
tnObject.read_until(b" ")
tnObject.write(password + b"\n")
print("sent password")
tnObject.read_until(b"Name ")
tnObject.write(b"1" + b"\n")
print("sent first command")
tnObject.read_until(b">")
tnObject.write(outlet + b"\n")
print("sent second command")
tnObject.read_until(b">")
tnObject.write(b"1" + b"\n")
print("sent third command")
tnObject.read_until(b">")
tnObject.write(b"2" + b"\n") #(1 is ON) (2 is OFF)
print("sent fourth command")
tnObject.read_until(b"Enter ")
tnObject.write(b"yes" + b"\n" + b"\n")
tnObject.read_until(b">")
tnObject.close()

print(tnObject.read_all())

我尝试了几十种不同的字符串组合,我尝试过在前面和后面添加空格,拼写,以及简单的b“”,以期望有一个空格,但似乎没有任何方法可以发送第一个命令。前面的3个字符串都读得很好。有什么办法可以替代这个阅读直到?在

另外,我试过睡觉(.5)和睡眠(1),但也没用。我也尝试过只将字符串写入缓冲区,而不等待read_ntil。救命啊!在


Tags: 字符串importhostreadpasswordcommandsentwrite
1条回答
网友
1楼 · 发布于 2024-09-30 16:28:54

你试过看这条线吗?Python - telnet - automation APC PDU-解决此问题的方法是在写入用户名和密码时添加“\r\n”。 所以你需要使用: tnObject.read_直到(b“用户名:”) tnObject.write(用户+b“\r\n”) tnObject.read_直到(b“”) tnObject.write(密码+b“\r\n”)

不需要使用tnObject.read_直到(b“>;”)

请注意,对于其他命令,您可以在结尾处保留“\n”: tnObject.write(b“userList\n”)应该可以正常工作

我在我的APC系统上试过了,效果很好。在

希望对你也有用!在

相关问题 更多 >