通过python脚本查看端口

[root@zabbix-server alertscripts]# cat check_port1.py 
#!/usr/bin/env python  
#coding:utf-8  
   
import os, json  
   
port_list=[]  
port_dict={"data":None}  
cmd='''''ss -tnlp|egrep -i "$1"|awk {'print $4'}|awk -F':' '{if ($NF~/^[0-9]*$/) print $NF}'|sort |uniq   2>/dev/null'''  
local_ports=os.popen(cmd).readlines()  
   
for port in local_ports:  
    pdict={}  
    pdict["{#TCP_PORT}"]=port.replace("
", "")  
    port_list.append(pdict)  
   
port_dict["data"]=port_list  
jsonStr = json.dumps(port_dict, sort_keys=True, indent=4)  
   
print jsonStr  

 执行结果:

[root@zabbix-server alertscripts]# python check_port1.py 
{
    "data": [
        {
            "{#TCP_PORT}": "10050"
        }, 
        {
            "{#TCP_PORT}": "10051"
        }, 
        {
            "{#TCP_PORT}": "22"
        }, 
        {
            "{#TCP_PORT}": "25"
        }, 
        {
            "{#TCP_PORT}": "3306"
        }, 
        {
            "{#TCP_PORT}": "80"
        }
    ]
}
原文地址:https://www.cnblogs.com/nulige/p/7110480.html