检测端口状态的python脚本

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了检测端口状态的python脚本相关的知识,希望对你有一定的参考价值。

#!/usr/bin/env python
import os,subprocess,socket,time,sys
from urllib import urlencode
from socket import gethostname

def check_port():
        port = [8091,8080]
        failed_port = []
        for _each_port in port:
                #print i
                try:
                        sk = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
                        sk.settimeout(2)
                        sk.connect((localhost,_each_port))
                        sk.close
                        now = time.strftime("%Y-%m-%d %H:%M:%S")
                        tt = "check port success!"
                        logfile = "/home/op/check.log"
                        f = open(logfile,a+)
                        f.write(now + " " + tt + "\n")
                        f.close()
                except socket.error:
                        failed_port.append(_each_port)

        for _each_port in failed_port:
                name = gethostname()
                message = "host: %s port: %d down" %(name, _each_port)
                tel = [电话号码]
                for _each_phone in tel:
                        data = {
                                "phone": _each_phone,
                                "message": message
                        }
                        command=curl "http://"短信接口ip":8080/message.php?%s" %(urlencode(data))
                        print command
                        ck = subprocess.Popen(command,shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
                        std_ok, std_err = ck.communicate(input=None)
                        #print std_ok
                        #print std_err

if __name__ == __main__:
        check_port()

 

以上是关于检测端口状态的python脚本的主要内容,如果未能解决你的问题,请参考以下文章

LVS健康检测脚本分享

python3写的一个检测远程服务器端口脚本

看端口是否被占用的python脚本

每日一道shell练习(06)——检测端口服务

python监控端口脚本

常用python日期日志获取内容循环的代码片段