![](/img/trans.png)
[英]Using Python: How can I telnet into a server and then from that connection telnet into a second server?
[英]How can I read one line from a telnet response with Python?
我很驚訝我在這里找不到這個問題。
我想從telnet響應中提取一行並使其成為變量。 (實際上是該行的一個數字)。 我可以使用telnet.read_until()提取到我需要的位置,但整個開始仍然存在。 打印輸出顯示機器的不同狀態。
我想要獲取的行格式如下:
CPU Utilization : 5 %
我真的只需要數字,但輸出的其余部分有很多':'和'%'字符。 任何人都可以幫我提取這個價值嗎? 提前致謝!
這是我的代碼(這將讀取整個輸出並打印):
import telnetlib, time
print ("Starting Client...")
host = input("Enter IP Address: ")
timeout = 120
print ("Connecting...")
try:
session = telnetlib.Telnet(host, 23, timeout)
except socket.timeout:
print ("socket timeout")
else:
print("Sending Commands...")
session.write("command".encode('ascii') + b"\r")
print("Reading...")
output = session.read_until(b"/r/n/r/n#>", timeout )
session.close()
print(output)
print("Done")
編輯:輸出可能是的一些示例:
Boot Version : 1.1.3 (release_82001975_C)
Post Version : 1.1.3 (release_82001753_E)
Product VPD Version : release_82001754_C
Product ID : 0x0076
Hardware Strapping : 0x004C
CPU Utilization : 5 %
Uptime : 185 days, 20 hours, 31 minutes, 29 seconds
Current Date/Time : Fri Apr 26 17:50:30 2013
正如你在問題中所說:
我可以使用
telnet.read_until()
提取到我需要的telnet.read_until()
,但整個開始仍然存在。
因此,您可以將所需的所有行(包括所需的行)添加到變量output
。 你唯一缺少的是如何獲得output
字符串中的最后一行,對吧?
這很簡單:只需將output
拆分成行並取最后一行:
output.splitlines()[:-1]
或者只是拆掉最后一行:
output.rpartition('\n')[-1]
這不會改變輸出,它只是一個計算新值的表達式( output
的最后一行)。 因此,只需執行此操作,然后執行print(output)
,就不會執行任何明顯有用的操作。
我們來看一個更簡單的例子:
a = 3
a + 1
print(a)
這顯然是打印3
。 如果你想打印4
,你需要這樣的東西:
a = 3
b = a + 1
print(b)
所以,回到真實的例子,你想要的可能是這樣的:
line = output.rpartition('\n')[-1]
print(line)
現在你會看到這個:
CPU Utilization : 5 %
當然,您仍然需要像Johnny的代碼那樣從其余部分中提取數字:
numbers = [int(s) for s in line.split() if s.isdigit()]
print(numbers)
現在你會得到這個:
['5']
請注意,它為您提供了一個字符串的列表。 如果你只想要一個字符串,你仍然有另一個步驟:
number = numbers[0]
print(number)
哪個給你:
5
最后, number
仍然是字符串 '5'
,而不是整數5
。 如果您需要,請將最后一位替換為:
number = int(numbers[0])
print(number)
這仍將打印 5
,但現在你有一個變量,你可以實際用作數字:
print(number / 100.0) # convert percent to decimal
我依賴於telnet
將行尾定義為\\r\\n
的事實,並且任何錯誤的telnet兼容服務器幾乎肯定會使用Windows風格(也是\\r\\n
)或Unix風格(只是\\n
)行結尾。 因此,分割\\n
將始終獲得最后一行,即使對於棘手的服務器也是如此。 如果您不需要擔心額外的健壯性,可以拆分\\r\\n
而不是\\n
。
還有其他方法可以解決這個問題。 我可能會使用session.expect([r'CPU Utilization\\s*: (\\d+)\\s*%'])
,或者將會話包裝為行的迭代器(如文件)然后只做編寫標准的itertools
解決方案。 但鑒於你已經擁有的東西,這似乎是最簡單的。
如果你只想獲得數字:
>>> output = "CPU Utilization : 5 %"
>>> [int(s) for s in output.split() if s.isdigit()]
[5]
>>> output = "CPU Utilization : 5 % % 4.44 : 1 : 2"
>>> [int(s) for s in output.split() if s.isdigit()]
[5, 4.44, 1, 2]
編輯:
for line in output:
print line # this will print every single line in a loop, so you can make:
print [int(s) for s in line.split() if s.isdigit()]
據我所知,你想從一個行塊中選擇1行,但不一定是最后一行。
您感興趣的行始終以“CPU利用率”開頭
這應該工作:
for line in output.splitlines():
if 'CPU Utilization' in line:
cpu_utilization = line.split()[-2]
In [27]: mystring= "% 5 %;%,;;;;;%"
In [28]: ''.join(c for c in mystring if c.isdigit())
Out[28]: '5'
更快的方式:
def find_digit(mystring):
return filter(str.isdigit, mystring)
find_digit(mystring)
5
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.