2014-12-18 61 views
1

我試圖在python中殺死一個偵聽端口。殺死正在用正則表達式偵聽的端口

os.system("sudo netstat -ap | grep 13000 > net.txt") 
f = open("net.txt","r") 
fr = f.read() 

上述命令的輸出是:

udp  0  0*:13000    *:*     5071/python 

到目前爲止,我有:

regex = re.compile(\d*.(python)) 
fl = regex.findall(fr) 

上述正則表達式只是打印蟒蛇。

所以現在的問題是,如何創建一個正則表達式來取適量PID值5071(這可能是任何其他數字)

編輯: 可能有一個以上的值,因爲有可能不止一個過程。

回答

2

您可以使用正前瞻:

>>> s="udp  0  0*:13000    *:*     5071/python" 
>>> re.search(r'\d+(?=/python)',s).group(0) 
'5071' 

,甚至只是一個正常的正則表達式和組:

>>> re.search(r'(\d+)/python', s).group(1) 
'5071' 

如果你有多個字符串在一個循環中把上面的命令:

for s in string_list: 
    print re.search(r'(\d+)/python', s).group(1) 
+0

我應該加上一句,如果有多個字符串?謝謝@Kasra – 2014-12-18 23:11:03

+1

@JonathanDavies不用客氣,所以你可以把它放在一個循環中!看編輯! – Kasramvd 2014-12-18 23:12:14

2

如果這只是一個字符串,您可以跳過使用findall並使用改爲。你似乎也沒有引用你想要編譯的模式。

您可以使用捕獲組並引用該組#來獲取匹配結果。

>>> re.search(r'(\d+)/python', s).group(1) 
'5071' 

如果您有多個字符串,您可以使用findall方法將匹配存儲在列表中。

>>> s = ''' 
udp  0  0*:13000    *:*     5071/python 
udp  0  0*:13000    *:*     8000/python 
''' 
>>> re.findall(r'(\d+)/python', s) 
['5071', '8000'] 
0

你可以做到這一點,而不需要一個正則表達式的所有:

s = "udp  0  0*:13000    *:*     5071/python" 
print(s.rsplit(" ",1)[-1].split("/python")[0]) 
5071 

我還要基於正回顧後使用subprocess,而不是使用os.system

from subprocess import PIPE,Popen 
p1 = Popen(["sudo","netstat", "-ap"], stdout=PIPE) 
p2 = Popen(["grep","13000" ], stdin=p1.stdout, stdout=open("net.txt","w")) 
p1.stdout.close() 
0

正則表達式的。

(\d+)(?=/python) 

輸出

>>> re.search('(\d+)(?=/python)', s).group() 
'5071' 
相關問題