개발 내용
네트워크 프로그래밍을 하다 보면 서버에서 어떤 클라이언트가 접속했는지 확인을 해야 하는데 Windows 환경에서 제공하는 netstat
으로 목록을 출력하고 findstr
command를 이용하여 필터링하는 과정을 주기적으로 하는 프로그램을 Python
으로 구현
개발 및 동작 환경
- OS: Windows 7 64Bit
- Python: 2.7.10
소스 코드
# -*- coding: utf-8 -*- # =================================================================== # Author: coozplz@gmail.com # File: netstat.py # Date: 2015. 10. 16 # Desc: Windows command "netstat -anp tcp | findstr [PORT]" 를 주기적으로 하는 프로그램 # =================================================================== import subprocess import time from time import localtime, strftime import datetime PORT = '12084' SLEEP_SEC = 5 class NetstatInfo: def __init__(self, protocol, local_addr, remote_addr, status): self.protocal = protocol self.local_addr = local_addr self.remote_addr = remote_addr self.status = status def __str__(self): return '%s %s %s %s' % (self.protocal, self.local_addr, self.remote_addr, self.status) if __name__ == '__main__': while True: print '-' * 70 print '%40s' % strftime('%Y-%m-%d, %H:%M:%S', localtime()) print '-' * 70 out, err = subprocess.Popen("netstat -anp tcp", stdout=subprocess.PIPE).communicate() result = out.splitlines() filtered_line = [] for line in result: if PORT in line: splitted_value = filter(lambda x: len(x) > 0, line.split(' ')) n = NetstatInfo(splitted_value[0], splitted_value[1], splitted_value[2], splitted_value[3]) print n time.sleep(SLEEP_SEC)