shadowsocks流量监控脚本

#!/usr/bin/env python

#coding=utf8
import json
import os
def run_cmd(port):
cmd = “iptables-save | grep -w %s | grep -v grep | wc -l” % port
num = os.popen(cmd).read()
if int(num) == 0:
cmd = “iptables -A INPUT -p tcp –dport %s;” % port
cmd += “iptables -A OUTPUT -p tcp –sport %s;” % port
os.popen(cmd).read()
def get_network():
cmd = “iptables -vnL| awk ‘{print $2,$11 }’”

#cmd = "iptables -vnL"
data = os.popen(cmd).read()
data += "\n"
print data
file_name = "/root/network.txt"
f = open(file_name, "a+")
f.write(data)
f.close()

def get_port():
file_path = “/etc/shadowsocks/config.json”
f = open(file_path, ‘r’)
data = json.load(f)
for port in (data[“port_password”]).keys():
run_cmd(port)
get_network()
if name == “main“:
get_port()