簡體   English   中英

使用正則表達式殺死正在監聽的端口

[英]Kill a port that is listening with regex

我正在嘗試殺死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)

上面的正則表達式只打印python。

所以問題是,我如何創建一個正則表達式以僅接受PID值5071 (這可以是任何其他數字)

編輯:可能有多個值,因為可能有多個進程。

您可以使用正向預看:

>>> 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)

如果這只是一個字符串,則可以跳過使用findall ,而是使用re.search() 您似乎也沒有在試圖編譯的模式周圍加引號。

您可以使用捕獲組並引用該組#來獲取您的比賽結果。

>>> 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']

您完全不需要正則表達式即可:

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

我也將使用進程而不是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()  

正則表達式基於積極的回顧。

(\d+)(?=/python)

輸出量

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM