简体   繁体   English

如何将 Telnet 输出存储到 python 中的变量中

[英]How to store a Telnet output into a variable in python

I am trying to use telnet to run a command and grab a value from a text output and store it in a variable in python.我正在尝试使用 telnet 运行命令并从文本输出中获取值并将其存储在 python 中的变量中。 In the image, the value I am trying to grab is the External alarm contact 2: Analog input value.在图像中,我试图获取的值是外部警报触点 2:模拟输入值。 In this case 5.99 which I want stored in a variable.在这种情况下,我想将 5.99 存储在一个变量中。 I need to store the 5.99 value or whatever it may change to in a variable我需要将 5.99 值或它可能更改的任何值存储在变量中

If you are using the telnetlib library for Python, you can use read_until() and specify a string it should read up to, or read_all() to read the output until EOF and obtain the output from the string.如果您使用的是telnetlib为Python,你可以使用read_until()并指定一个字符串,它应该读到,或read_all()读取输出,直到EOF,并获得从字符串输出。

import getpass
import sys
import telnetlib

HOST = "localhost"
user = raw_input("Enter your remote account: ")
password = getpass.getpass()

tn = telnetlib.Telnet(HOST)

tn.read_until("login: ")
tn.write(user + "\n")
if password:
    tn.read_until("Password: ")
    tn.write(password + "\n")

tn.write("ls\n")
tn.write("exit\n")

print tn.read_all()

https://docs.python.org/2/library/telnetlib.html#telnet-objects https://docs.python.org/2/library/telnetlib.html#telnet-objects

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM