检测端口状态的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()

 

posted @ 2016-11-14 10:52  梦轻尘  阅读(4564)  评论(0编辑  收藏  举报