connection_vproc.py 3.92 KB
#!/usr/bin/python
# encoding:utf-8

#######################################################
#   author: liuh    2018-12-10
#   version: v1.0
#   python version: 2
#######################################################

import sys
import getopt
import os
import shutil
import time
import json
import subprocess
import threading
import time
import pdb

class conn(object):
    """docstring for conn"""
    def __init__(self, port, cors, interval):
        super(conn, self).__init__()
        self.port = port
        self.cors = cors
        self.interval = interval 
    def display(self):
        if(self.cors == 0):
            print("conn info: server port {}, interval {}".format(self.port, self.interval))
        else:
            print("conn info: client port {}, interval {}".format(self.port, self.interval))

def usage():
    print("""
    useage: connection_vproc.py [options]

    options:
        [+]-s any, --serverports=any | the connection that host as server listen port 
        [+]-c any, --clientports=any | the connection that host as client connect port
        example:
            ./connection_vproc.py --serverports=8851 --serverports=9999 --clientports=20080

    """)

global_working = 1

def loop(connlist_, interval_):
    print("enter loop, conn size:{}, interval:{}".format(len(connlist_), interval_))
    last = 0
    while global_working:
        now = time.time()
        interval = now-last
        if( interval > interval_):
            for conn_ in connlist_:
                port_status(conn_.port,conn_.cors)
            last = now
        time.sleep(1)

def main():
    argc = len(sys.argv)
    try:
        options,args = getopt.getopt(sys.argv[1:],"-h-s:-c:-i:",["help","serverports=","clientports=", "invertal="])
    except getopt.GetoptError:
        print("error: invalid args")
        usage()
        sys.exit(-1)
    serverports = []
    clientports = []
    interval = 600
    for name,value in options:
        if name in ("--help"):
            usage()
        if name in ("--serverports"):
            serverports.append(value)
        if name in ("--clientports"):
            clientports.append(value)
        if name in ("--invertal"):
            interval = int(value)
    connlist = []
    for sport in serverports:
        connlist.append(conn(sport, 0, interval))
    for cport in clientports:
        connlist.append(conn(sport, 1, interval))

    for _conn in connlist:
        _conn.display()

    global_working = 1
    t = threading.Thread(target=loop, args=(connlist,interval))
    t.setDaemon(True)
    t.start()

    # print("before thread join")
    # t.join()

    try:
        while 1:
            time.sleep(1)
    except KeyboardInterrupt as e:
        print('recv exit signal')
        global_working = 0
        t.join(5)
        print('exit')
        sys.exit(0)

    for _conn in connlist:
        port_status(_conn.port,_conn.cors)
    sys.exit(0)

# cors: int 0-server 1-client
def port_status(port, cors):
    ipss = ""
    ipcs = ""
    p = subprocess.Popen(['lsof -i:{}'.format(port)], shell=True, stdout=subprocess.PIPE)
    while 1:
        out = p.stdout.readline().decode()
        if len(out) == 0:
            break
        out = out.split(" ")[-2]
        if(out.find("->") == -1):
            continue
        ipport = out.split("->")[1].split(":")
        ip = ipport[0]
        # print("cors:{} ipport[1]:{} port:{}".format(cors,ipport[1],port))
        if(cors == 0):
            if ipport[1] != port :
                ipss = ipss + ip + "\|"
        else:
            if ipport[1] == port :
                ipcs = ipcs + ip + "\|"
    if cors == 0:
        command = "vproc write --key=connection.server_{} --value={}".format(port, ipss)
        print(command)
        subprocess.Popen([command],shell=True)
    else:
        command = "vproc write --key=connection.client_{} --value={}".format(port, ipcs)
        print(command)
        subprocess.Popen([command],shell=True)


if __name__ == '__main__':
    main()