標籤:warning python 練習題 import 檢測
寫一個指令碼,判斷原生80連接埠是否開啟著,如果開啟著什麼都不做,如果發現連接埠不存在,那麼重啟一下httpd服務,並發郵件通知你自己。指令碼寫好後,可以每一分鐘執行一次,也可以寫一個死迴圈的指令碼,30s檢測一次。
#!/usr/bin/env python
#!coding=utf-8
import os
import time
import sys
import smtplib
from email.mime.text import MIMEText
from email.MIMEMultipart import MIMEMultipart
def sendsimplemail (warning):
msg = MIMEText(warning)
msg[‘Subject‘] = ‘python first mail‘
msg[‘From‘] = ‘[email protected]‘
try:
smtp = smtplib.SMTP()
smtp.connect(r‘smtp.126.com‘)
smtp.login(‘[email protected]‘, ‘13716370012‘)
smtp.sendmail(‘[email protected]‘, [‘[email protected]‘], msg.as_string())
smtp.close()
except Exception, e:
print e
while True:
http_status = os.popen(‘netstat -tulnp | grep httpd‘,‘r‘).readlines()
try:
if http_status == []:
os.system(‘service httpd start‘)
new_http_status = os.popen(‘netstat -tulnp | grep httpd‘,‘r‘).readlines()
str1 = ‘‘.join(new_http_status)
is_80 = str1.split()[3].split(‘:‘)[-1]
if is_80 != ‘80‘:
print ‘httpd 啟動失敗‘
else:
print ‘httpd 啟動成功‘
sendsimplemail(warning = "This is a warning!!!")
else:
print ‘httpd正常‘
time.sleep(5)
except KeyboardInterrupt:
sys.exit(‘\n‘)
python練習題(四)