telnetlib read_until() 函数混淆
我正在尝试使用 python3 自动执行一些 telnet 操作。所以我开始使用telnetlib中的构建(不是pexpect)。
实际上到目前为止一切正常,但我不完全理解 read_until 是如何工作的 - 实际上文档说你可以设置一个超时,如果找不到搜索字符串,超时会发回一个空字节值,或者如果有另一个值,那就是可以作为返回值存储的!
这有道理吗?
如果我想 read_until 某个值 - 我如何找出该值确实是函数读取的值。我也不知道如何检查是否超时。
我现在的解决方法是:
output = telnet.read_until(str.encode(hostname), 3)
if re.search(hostname, bytes.decode(output), re.IGNORECASE):
#do something when the output matches the searchstring
else:
#stop the function
但这对我来说没有任何意义,所以也许你现在有一个更好的解决方案
I am trying to automate some telnet actions with python3. So I started to use the build in telnetlib (not pexpect).
Actually everything works so far but I do not understand completly how read_until works - actually the documentation says that you can set a timeout and if the search string is not found the timeout sends back a empty byte value or or if there is another value thats the one which can be stored as a return value!
Does that make sense ?!
If I wanna read_until a certain value - how do I find out that this value was really the one the function read. Also I couldn't find out how to check if the timeout was hit.
My workaround for now is:
output = telnet.read_until(str.encode(hostname), 3)
if re.search(hostname, bytes.decode(output), re.IGNORECASE):
#do something when the output matches the searchstring
else:
#stop the function
but that doesn't make any sense for me, so perhaps you now a better solution
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
是的,如果您的主机名是
example.com
,read_until 将返回类似weijwrgnerg hgqwv blather example.com
的内容。除非它在三秒后没有找到主机名,否则它只会吐出此时得到的任何内容:weijwrgnerg hg
。所以我认为你做得几乎是正确的。您可能想要
re.escape
您的主机名,否则它会将其解释为正则表达式。或者,您可以只使用 Python 的.endswith()
。您可以执行output.decode()
来获取字符串(而不是bytes.decode(output)
)。Yes, if your hostname is
example.com
, read_until will return something likeweijwrgnerg hgqwv blather example.com
. Except if it hasn't found the hostname after three seconds, it will just spit out whatever it's got by then:weijwrgnerg hg
.So I think you're doing it almost right. You probably want to
re.escape
your hostname, otherwise it will interpret it as a regex. Alternatively, you could just use Python's.endswith()
. And you can dooutput.decode()
to get a string (rather thanbytes.decode(output)
).