python使用netstat命令获取cmd上的文件进程名称

时间:2016-02-16 03:44:36

标签: python winapi subprocess netstat

我想制作一个简单的程序,让我的本地网络服务器处于活动状态。 我试着创建一些代码,这个代码我在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 Server

由于

1 个答案:

答案 0 :(得分:0)

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传递给任务列表>转到任务列表中的相关行>打印第一个单词。