2010-06-30 155 views

回答

5

兩個部分:

殼牌

netstat | python read_netstat.py 

的Python read_netstat.py

import sys 
variable = sys.stdin.read() 

將讀取從輸出netst變成一個變量。

6

這是可能的。請參閱:

​​3210

在Python 2.4及以上版本:

from subprocess import * 
x = Popen(["netstat", "-x", "-y", "-z"], stdout=PIPE).communicate()[0] 
+1

你確定這有效嗎?我不認爲反引號在Python中調用shell,並且無論如何都不鼓勵使用它們。 – 2010-06-30 21:24:17

+0

你好,我想試試看。反引號至少需要使用cygwin。沒有反撥,我得到幫助吐了回來。 >>> x = Popen([「netstat」,「-a」,「-b」,「-e」],stdout = PIPE).communicate()[0] >>> x 'Interface Statistics \ r \ n \ r \ n收到已發送郵件\ r \ n \ r \ nBytes 636096584 44729983 \ r \ n Unicast 數據包540296 2972​​33 \ r \ n非單播數據包1058608 338 \ r \ nDiscards 0 0 \ r \ n錯誤0 13 \ r \ n未知的協議4405 \ r \ n' – manifest 2010-06-30 21:40:47

+0

在DOS中也試過了,同樣的交易。需要反標記。 – manifest 2010-06-30 21:44:41

2

看看在subprocess模塊。它允許你啓動新的進程,與它們交互並讀取它們的輸出。

特別請參見Replacing /bin/sh shell backquote

output = Popen(["mycmd", "myarg"], stdout=PIPE).communicate()[0] 
相關問題