Python/Python for Windows

[Python] psutil을 이용한 프로세스/로컬IP/로컬Port/리모트IP/리모트Port 모니터링

Pydole 2019. 9. 8. 16:00

psutil은 실행중인 프로세스 및 시스템 자원 정보를 볼 수 있는 모듈

import psutil

strings = ''
stringsFormat = '%-30s\t%-20s\t%-10s\t%-20s\t%-10s\n'
strings = stringsFormat % ('process', 'local ip', 'local port', 'remote ip', 'remote port')
strings += '-'*30+'\t'+'-'*20+'\t'+'-'*10+'\t'+'-'*20+'\t'+'-'*10+'\n'

def processinfo():
        process = psutil.Process(conn.pid)
        return process.name()

for conn in psutil.net_connections():
        if conn.status == 'NONE':
                pass
        else:
                localip = conn.laddr[0]
                localport = conn.laddr[1]
                remoteip = conn.raddr[0] if conn.raddr else '-'
                remoteport = conn.raddr[1] if conn.raddr else '-'

        strings += stringsFormat % (processinfo(), localip, localport, remoteip, remoteport)
        print(strings)


---------------------------------------------------------------------------------
process                         local ip                local port      remote ip               remote port
------------------------------  --------------------    ----------      --------------------    ----------
chrome.exe                      x.x.x.x                 60384           x.x.x.x                 443
chrome.exe                      x.x.x.x                 59517           x.x.x.x                 xxxx

.............................