python 使用 Twilio免费短信网关报警方法

工作原因,要定时检测服务状态,最开始想用微信公众号,发现只有企业认证帐号才可以给用户发送信息,这个方案给否掉了。

有一天看书突然发现在TWILIO免费发短信功能,试用后非常方便。

一、申请twilio帐号

地址:https://www.twilio.com/

注意:邮箱要用163.com gmail.com都可以,用QQ邮箱不行,通过不了,

申请完帐号后在申请一个临时的电话号码,这个号码是用来给自己发送短信的。


二、写python 接口
sms.py

点击(此处)折叠或打开

  1. #coding: utf-8
  2. from twilio.rest import Client
  3. def sms(t):
  4.     account_sid = " "

  5.     auth_token = " "

  6.     client = Client(account_sid, auth_token)

  7.     message = client.messages.create(
  8.         to="= ",#自己的手要号码
  9.         from_=" ",#在网站上申请的手机码,只能用这个号码发信息
  10.         body=t.decode("utf-8"))#编码密码使用utf-8才发送中文。

  11.     print(message.sid)

引用sms模块

点击(此处)折叠或打开

  1. #!/usr/bin/python
  2. import socket
  3. import time
  4. from sms import sms
  5. import logging
  6. import time
  7. def port_try(host,port):
  8.     shijian=time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))
  9.     sk = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  10.     sk.settimeout(1)
  11.     try:
  12.         sk.connect((host,port))
  13.         t=host+"服务器 "+str(port)+" 连接正常 "+str(shijian)
  14.         #sms(t)
  15.         print t
  16.     except Exception:
  17.         w=host+" 服务器 "+str(port)+" 无法连接 "+str(shijian)
  18.         print w
  19.         sms(w)
  20.     sk.close()

  21. file = open("/root/script/ip.txt")#ip地址写法192.16.0.1:80

  22. while True:
  23.     line = file.readline().strip('\n')
  24.     if len(line)==0:break
  25.     ip=str(line.split(':',1)[0])
  26.     port=int(line.split(':',1)[1])
  27.     port_try(ip,port)
  28.     #time.sleep(2)


来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/11363642/viewspace-2139238/,如需转载,请注明出处,否则将追究法律责任。

转载于:http://blog.itpub.net/11363642/viewspace-2139238/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值