背景
之前在文章Windows Server 2008R2使用Batch脚本查看有效连接数提到过要使用Python脚本来统计连接数,并且做日志分割。之前还考虑过直接使用Batch来完成日志分割,最后败在Batch通过%time%
获取到的当前时间为命令行窗口打开的时间(我去,我放弃Batch了)。
Python3
import subprocess
import time
from datetime import datetime
import os
import csv
import time
import argparse
# python3 windows_netstat.py :80
# netstat -ano | find ":80" | find "ESTABLISHED" /c
parser = argparse.ArgumentParser()
parser.add_argument("port", type=str, help="port")
args = parser.parse_args()
timeFormat = "%Y-%m-%d %H:%M:%S.%f"
starTimeTitle = "时间"
connectionsTitle = "连接数"
while True:
starTime = datetime.now()
timeNow = starTime.strftime(timeFormat)
try:
output=subprocess.check_output('netstat -ano | find "{0}" | find "ESTABLISHED" /c'.format(args.port), shell=True)
connections = output.decode('utf-8').strip()
nowTime = datetime.now()
csvFileName = "netstat_{0}.csv".format(nowTime.strftime("%Y-%m-%d"))
if os.path.exists(csvFileName) is not True:
with open(csvFileName, "w", encoding="utf-8", newline="") as csvfile:
fieldnames = [starTimeTitle, connectionsTitle]
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
writer.writeheader()
with open(csvFileName, "a", encoding="utf-8", newline="") as csvfile:
fieldnames = [starTimeTitle, connectionsTitle]
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
writer.writerow({starTimeTitle : timeNow, connectionsTitle : connections})
except subprocess.CalledProcessError as e:
print("command '{0}' return with error (code {1}): {2}".format(e.cmd, e.returncode, e.output))
time.sleep(0.2)
这里大部分要点,都在文章Windows Server 2008R2使用Batch脚本查看有效连接数提到过,这里只提一下subprocess
调用本地netstat
的问题。
output=subprocess.check_output('netstat -ano | find "{0}" | find "ESTABLISHED" /c'.format(args.port), shell=True)
这里是执行本地netstat
命令。这里获取到output
是字节数据组,不是字符串,还需要将该值转化成文本,故使用如下方式,进行编码:
output.decode('utf-8')
这样转化过文本包含换行符\n
,则还需要进行如下操作:
connections = output.decode('utf-8').strip()
这样得到的connections
值才是我们需要的统计的连接数。
使用
python3 windows_netstat.py :80
只要80端口存在有效连接就在本地生成一个csv文件,并且按天进行文件分割。
感受
人生苦短 我用Python 参考: Built-in Functions Python3 open python3 csv 如何移除换行符? 13.6 执行外部命令并获取它的输出 Subprocess management