Windows & Unix 版。

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import urllib
import urllib2
import time
import os
import sys
from datetime import datetime

_defval_win = 'win'
_defval_linux = 'linux'

platform = sys.platform
interval = 0.2
now = datetime.now().strftime('%Y-%m-%d %H:%M:%S')

# 系統變數
site = sys.argv[1]
IP = sys.argv[2]
username = 'flyfox'
password = '123'
mobile = ["0910234567", "0910345678", "0910456789"]
message = '簡訊內容測試'+ site + IP
message = urllib.quote(message)

if platform.find(_defval_win) >= 0:
# windows
f = open('D:\\temp\\pingtwsms.log', 'a')
f.write(now)

# 在呼叫網頁前將 ping 的資料寫入 Log
cmd ='ping -n 3 api.twsms.com >> D:\\temp\pingtwsms.log'
ps = os.system(cmd)
before = len(open("D:\\temp\\twsms.log").readlines())
if ps == 0:
f.write('Ping Success.\n')
else:
f.write('Ping Fail.\n')

f.close()

file = open('D:\\temp\\twsms.log', 'a')

for i in mobile:
msg = 'username='+username+'&password='+password+'&mobile='+i+'&message='+message
url = 'http://api.twsms.com/smsSend.php?'+msg
resp = urllib2.urlopen(url)
file.write(time.asctime()+" "+resp.read()+"\n")

file.close()

# 判斷是否成功發送簡訊
fo = open("D:\\temp\\twsms.log","r")
mylist = fo.readlines()
after = mylist[before+len(mobile)-1][41:46]
fo.close()

if after == '00000':
f = open('D:\\temp\\pingtwsms.log', 'a')
f.write(now + 'Send Success!\n')
f.close()
else:
f = open('D:\\temp\\pingtwsms.log', 'a')
f.write(now + 'Send Fail!\n')
f.close()

elif platform.find(_defval_linux) >= 0:
# linux
f = open('/tmp/pingtwsms.log', 'a')
f.write(now + '\n')
# 在呼叫網頁前將 ping 的資料寫入 Log
cmd ='ping -c 3 -i '+str(interval)+' api.twsms.com >> /tmp/pingtwsms.log'
ps = os.system(cmd)
before = len(open("/tmp/twsms.log").readlines())
if ps == 0:
f.write('Ping Success.\n')
else:
f.write('Ping Fail.\n')

f.close()

file = open('/tmp/twsms.log', 'a')

for i in mobile:
msg = 'username='+username+'&password='+password+'&mobile='+i+'&message='+message
url = 'http://api.twsms.com/smsSend.php?'+msg
resp = urllib2.urlopen(url)
file.write(time.asctime()+" "+resp.read()+"\n")

file.close()

# 判斷是否成功發送簡訊
fo = open("/tmp/twsms.log","r")
mylist = fo.readlines()
after = mylist[before+len(mobile)-1][41:46]
fo.close()

if after == '00000':
f = open('/tmp/pingtwsms.log', 'a')
f.write(now + 'Send Success!\n')
f.close()
else:
f = open('/tmp/pingtwsms.log', 'a')
f.write(now + 'Send Fail!\n')
f.close()
cmd = '/bin/mv /usr/local/nagios/bin/sms.sent /usr/local/nagios/bin/sms'
ps = os.system(cmd)

else:
# unknown OS
pass

sys.exit(1)

flyfox 發表在 痞客邦 PIXNET 留言(0) 人氣()