简体   繁体   English

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

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

I want make a simple program to get the web server active on my local. 我想要一个简单的程序来使Web服务器在本地运行。 I have try to create some code, this code i working well in windows 7 64bit. 我尝试创建一些代码,该代码在Windows 7 64bit中运行良好。 but when I run my code on windows XP32 bit, this code make a windows XP hang. 但是,当我在Windows XP32位上运行代码时,此代码会使Windows XP挂起。

can you help me to explain why this code make the windows XP hang ? 您能帮我解释一下为什么此代码会使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()

sample output in win7 64bit when I'm using XAMPP 当我使用XAMPP时在win7 64bit中输出样本

Apache HTTP Server Apache HTTP服务器

Thanks 谢谢

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)

Output for above is "Apache HTTP Server" 上面的输出是“ Apache HTTP Server”

I don't know why your's doesn't work in XP, but try the code above (Python 2.7) 我不知道为什么您的不能在XP中使用,但是请尝试上面的代码(Python 2.7)

Basically: executes command> gets relevant line> gets last word(PID) in output> passes pid to tasklist> goes to relevant line in tasklist> prints first word. 基本上:执行命令>获取相关行>获取输出中的最后一个单词(PID)>将pid传递到任务列表>转到任务列表中的相关行>打印第一个单词。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM