簡體   English   中英

python使用netstat命令在cmd上獲取文件進程名稱

[英]python get file process name on cmd using netstat command

我想要一個簡單的程序來使Web服務器在本地運行。 我嘗試創建一些代碼,該代碼在Windows 7 64bit中運行良好。 但是,當我在Windows XP32位上運行代碼時,此代碼會使Windows XP掛起。

您能幫我解釋一下為什么此代碼會使Windows XP掛起嗎?

def get_web_server():
    import win32api
    import subprocess
    try:
        cmd = 'for /f "usebackq tokens=5" %i in (`"netstat -aon | findstr "0.0:80""`) do @wmic PROCESS get Name,ProcessId,ExecutablePath | findstr "%i"'
        output = subprocess.Popen(cmd,stdout=subprocess.PIPE,shell=True).communicate()
        try:
            windows_exe = (output[0].split('\r\n')[0].strip().split()[0])
        except:
            windows_exe = None
        try:
            language, codepage = win32api.GetFileVersionInfo(windows_exe, '\\VarFileInfo\\Translation')[0]
            stringFileInfo = u'\\StringFileInfo\\%04X%04X\\%s' % (language, codepage, "FileDescription")
            description = win32api.GetFileVersionInfo(windows_exe, stringFileInfo)
        except:
            description = None

    except:
        description = None

    return description

print get_web_server()

當我使用XAMPP時在win7 64bit中輸出樣本

Apache HTTP服務器

謝謝

import os
import subprocess
import re
import win32api
pid=subprocess.check_output('netstat.exe -abno | find /i "listening" |find ":80"', shell=True).split('\n', 1)[0].split()[-1]
webserver= subprocess.check_output('tasklist /FI "PID eq '+pid+'" /v /fo List', shell=True).splitlines()[-1].split("Window Title:", 1)[1].rsplit("Window Title:", 1)[0].strip()
def getFileDescription(windows_exe):
    try:
        language, codepage = win32api.GetFileVersionInfo(windows_exe, '\\VarFileInfo\\Translation')[0]
        stringFileInfo = u'\\StringFileInfo\\%04X%04X\\%s' % (language, codepage, "FileDescription")
        description = win32api.GetFileVersionInfo(windows_exe, stringFileInfo)
    except:
        description = "unknown"
    return description
print getFileDescription(webserver)

上面的輸出是“ Apache HTTP Server”

我不知道為什么您的不能在XP中使用,但是請嘗試上面的代碼(Python 2.7)

基本上:執行命令>獲取相關行>獲取輸出中的最后一個單詞(PID)>將pid傳遞到任務列表>轉到任務列表中的相關行>打印第一個單詞。

暫無
暫無

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

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