繁体   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