python监控端口_Python监控服务端口并报警

#!/usr/bin/env python

importosimportwmiimporttimeimportsocketimportbase64importsmtplibimportloggingfrom email.mime.text importMIMETextdefGetSrv(designation):"""Get stopped service name and caption,

Filtration ‘designation‘ service whether there is ‘Stopped‘.

:return: service state"""c=wmi.WMI()

ret=dict()for service inc.Win32_Service():

state, caption=service.State, service.Captionif state == ‘Stopped‘:

t=ret.get(state, [])

t.append(caption)

ret[state]=t#If ‘designation‘ service in the ‘Stopped‘, return status is ‘down‘

if designation in ret.get(‘Stopped‘):

logging.error(‘Service [%s] is down, try to restart the service. \r\n‘ %designation)return ‘down‘

returnTruedefMonitor(sname):"""Send the machine IP port 20000 socket request,

If capture the abnormal returns the string ‘ex‘.

:return: string ‘ex‘"""s=socket.socket()

s.settimeout(3) #timeout

host = (‘127.0.0.1‘, 20000)try: #Try connection to the host

s.connect(host)exceptsocket.error as e:

logging.warning(‘[%s] service connection failed: %s \r\n‘ %(sname, e))return ‘ex‘

returnTruedefRestartSocket(rstname, conn, run):"""First check whether the service is stopped,

if stop, start the service directly.

The check whether the zombies,

if a zombie, then restart the service.

:return: flag or True"""flag=Falsetry:#From GetSrv() to obtain the return value, the return value

if run == ‘down‘:

ret= os.system(‘sc start "%s"‘ %rstname)if ret !=0:raise Exception(‘[Errno %s]‘ %ret)

flag=Trueelif conn == ‘ex‘:

retStop= os.system(‘sc stop "%s"‘ %rstname)

retSart= os.system(‘sc start "%s"‘ %rstname)if retSart !=0:raise Exception(‘retStop [Status code %s]‘

‘retSart [Status code %s]‘ %(retStop, retSart))

flag=Trueelse:

logging.info(‘[%s] service running status to normal‘ %rstname)returnTrueexceptException as e:

logging.warning(‘[%s] service restart failed: %s \r\n‘ %(rstname, e))returnflagdefSendMail(to_list, sub, contents):"""Send alarm mail.

:return: flag"""mail_server= ‘mail.stmp.com‘ #STMP Server

mail_user = ‘YouAccount‘ #Mail account

mail_pass = base64.b64decode(‘Password‘) #The encrypted password

mail_postfix = ‘smtp.com‘ #Domain name

me= ‘Monitor alarm‘ %(mail_user, mail_postfix)

message= MIMEText(contents, _subtype=‘html‘, _charset=‘utf-8‘)

message[‘Subject‘] =sub

message[‘From‘] =me

message[‘To‘] = ‘;‘.join(to_list)

flag= False #To determine whether a mail sent successfully

try:

s=smtplib.SMTP()

s.connect(mail_server)

s.login(mail_user, mail_pass)

s.sendmail(me, to_list, message.as_string())

s.close()

flag=TrueexceptException, e:

logging.warning(‘Send mail failed, exception: [%s]. \r\n‘ %e)returnflagdefmain(sname):"""Parameter type in the name of the service need to monitor,

perform functions defined in turn, and the return value is correct.

After the program is running, will test three times,

each time interval to 10 seconds.

:return: retValue"""retry= 3count=0

retValue= False #Used return to the state of the socket

while count

ret=Monitor(sname)if ret != ‘ex‘: #If socket connection is normaol, return retValue

retValue =retreturnretValue

isDown=GetSrv(sname)

RestartSocket(rstname=sname, conn=ret, run=isDown)

host=socket.gethostname()

address=socket.gethostbyname(host)

mailto_list= [‘mail@smtp.com‘, ] #Alarm contacts

SendMail(mailto_list, ‘Alarm‘,‘

Level: ERROR Host name: %s‘

‘IP Address: %s‘

‘Service name:

%s

%(host, address, sname))

count+= 1time.sleep(10)else:

logging.error(‘[%s] service try to restart more than three times \r\n‘ %sname)returnretValueif __name__ == ‘__main__‘:

logging.basicConfig(level=logging.INFO,

format=‘%(asctime)s %(levelname)s %(message)s‘,

datefmt=‘%Y/%m/%d %H:%M:%S‘,

filename=‘D:\\em_logs\\SocketMonitor.log‘,

filemode=‘ab‘)

name= ‘IM_IMConnectorServerWinService‘response=main(name)ifresponse:

logging.info(‘The [%s] service connection is normal \r\n‘ % name)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值