自动获取公网IP并定时发送到指定邮箱 #!/usr/bin/env python import sys, os, smtplib, urllib from time import sleep from email.mime.text import MIMEText ipaddr = urllib.urlopen("http://ip.3322.net").read() ipaddr = os.popen("nvram get wan_ipaddr").read() smtpserver = 'smtp.gmail.com' username = '你的GMAIL@gmail.com' password = '你的GMAIL密码' sender = 'Router' receiver = '你的移动手机号@139.com' #或者联通号@wo.com.cn,电信号@189.cn msg = MIMEText(ipaddr) msg['Subject'] = 'Note: IP Address Changed!' msg['From'] = sender msg['To'] = receiver smtp = smtplib.SMTP() smtp.connect(smtpserver) smtp.ehlo() smtp.starttls() smtp.ehlo() smtp.set_debuglevel(1) smtp.login(username, password) smtp.sendmail(sender, receiver, msg.as_string()) sleep(5) smtp.quit()
又一版本#!/usr/bin/env python
# -- coding: utf-8 --
# author: heidanine
# file: checkWapIp.py
# modified: 2016/03/20 01:40###########################################
# 检测外网的 Ip,发送到指定邮箱
###########################################
# 初期设置:
# 1. 填写 myMail -> 你的邮箱哦
# 2. 填写 mySmtp -> host 你自己的 smtp 服务器。 user/pwd 用户名和密码
# 3. 填写 testUrlParams -> 这个除了保留的地址,你可以多找几个,防止哪个网站不好用了。
# 测试脚本可否执行:
# python checkWanIp.py
# 如果没什么问题就可以把这个脚本的执行交给 cron 了。
# 配置 cron(需要 root 权限),每 10 分钟检测一次,可自己按习惯定。
# crontab -e
# 输入:
# /10 * python checkWapIp.pyimport os
import time
import httplib
import urllib
import urllib2
import smtplib
from email.mime.text import MIMEText################
## 发件箱地址
myMail = "XXXXXXXX@126.com"
################
# 收件地址
toMailList= [myMail
#,'111@163.com'
]
################
# 发邮件的 SMTP 服务器设置
mySmtp = {"host": "smtp.XXX.com"
,"user": "XXXXXXXX"
,"pwd": "XXXXXXXX"
}################
#检测外网 IP 的网站列表
testUrlParams = [{'domain': 'ifconfig.me', 'uri': '/ip'}
,{'domain': 'icanhazip.com', 'uri': ''}
]
# log 文件名
logFileName = 'checkWanIp.log'
# log 初始内容
logList = ['']
# 保存上次 IP 信息的文件
lastInfoFileName = '.lastInfo'def getWanIpInfo():
'''
取得外网 IP
'''
ipInfo = ['']
for urlParam in testUrlParams:
ipInfo.append("\r\n----------")
ipInfo.append("\r\nTest Server : http://" + urlParam['domain'] + urlParam['uri'])
ip = getRequestIpInfo(urlParam)
if ip is None:
ipInfo.append("\r\nTest Fail!!!!!!!!!!!!!!!!!")
ipInfo.append("\r\n----------")
else:
ipInfo.append("\r\nTest OK!")
ipInfo.append("\r\nResult: \r\n")
ipInfo.append(ip)
ipInfo.append("\r\n----------")
return "".join(ipInfo)def getRequestIpInfo(urlParam):
'''
从指定的测试 IP 的网站得到当前电脑所在网络的外网 IP
param['domain'] : 域名 (用 httplib 这个包访问不要加"http://")
param['uri'] : URI
'''
global logList
ip = None
try:
con = httplib.HTTPConnection(urlParam['domain'])
con.request('GET', urlParam['uri'])
res = con.getresponse()
if res.status == 200 :
ip = res.read()
con.close()
except Exception, e:
logList.append(str(e))
return ipdef sendMail(subject, info):
'''
发送邮件到指定的邮箱
subject: 主题
info: 邮件内容
'''
global logList
msg = MIMEText(info)
msg['Subject'] = subject
msg['From'] = myMail
msg['To'] = ";".join(toMailList)
try:
s = smtplib.SMTP();
s.connect(mySmtp['host'])
s.login(mySmtp['user'], mySmtp['pwd'])
s.sendmail(myMail, toMailList, msg.as_string())
s.close()
return True
except Exception, e:
logList.append(str(e))
return Falsedef readFile(fileName):
'''
读文件内容
'''
global logList
try:
# 打开文件读取文件内容
f = open(fileName, 'r')
try:
return f.read()
finally:
f.close()
except IOError:
logList.append("\r\n" + fileName + " - Can't open the file! Your maybe first run the script, or confirm the Read permission!")
return Nonedef writeFile(fileName, str):
return writeFileByMode(fileName , str, 'w') # 追加模式def writeLog(str):
'''
写 Log 文件
'''
print str
return writeFileByMode(logFileName ,str, 'a') # 追加模式def writeFileByMode(fileName, str, mode):
'''
写文件内容
'''
global logList
if mode is None:
mode = 'w' # 默认写模式
try:
# 写入文件内容
f= open(fileName, mode)
try:
f.write(str)
return True
finally:
f.close()
except IOError:
logList.append("\r\n" + fileName + " - Can't write the file! Please confirm the write permission")
return Falseif name == 'main':
try:
# 从网站上取得 IP
ipInfo = getWanIpInfo()
logList.append(ipInfo)
#读取上次保存的内容
lastInfo = readFile(lastInfoFileName)
# 判断和上次取得的内容是否有变化
if lastInfo == ipInfo:
logList.append("\r\n\r\n IP is not change!")
print "".join(logList)
else:
# 把取得的内容存入文件中,下次用来进行比较
writeFile(lastInfoFileName, ipInfo)
logList.append("\r\n\r\nWrite new IP to '" + lastInfoFileName + "'")
# 取得开始时间字符串
timeStr = time.strftime('%Y-%m-%-d %H:%M:%S', time.localtime(time.time()))
# 设置邮件主题
subject = '[Get IP]host:buhe9(' + timeStr + ')'
# 发送到指定邮箱
sendMail(subject, ipInfo)
#写入 log
logList.append("\r\n Subject: " + subject)
logList.append("\r\n Send mail ok!")
logList.append("\r\n")
writeLog("".join(logList))
except Exception, e:
writeLog(str(e))
shell 命令
假设你的邮箱是 abc@163.com,密码是 123456,你要向 def@163.com 发信:
echo -e "From: abc@163.com\nContent-Type: text/plain;\nSubject: IP\n\n"wget -O- http://ip.3322.net
| sendmail -v -Ssmtp.163.com -fabc@163.com -auabc -ap123456 def@163.com
wget -O- http://ip.3322.net | sendmail -v -S 邮件 SMTP 服务器 -f 发信人 -au 用户名 -ap 密码 邮箱
VBS 代码
<服务器 class="codetitle">
代码如下:
getIP
set http=createobject("Microsoft.XMLHTTP")
ipp="http://www.ip138.com/ip2city.asp"
http.open "get",ipp,false
http.send
ss=bytes2BSTR(Http.responsebody)
intStrA = InStr(1,ss,"[",1)+1
sss=mid(ss,intStrA)
intStrB = InStr(1,sss,"]",1)-1
ss=mid(ss,intStrA,intStrB)
wscript.echo ssFunction bytes2BSTR(vIn)
strReturn = ""
For i = 1 To LenB(vIn)
ThisCharCode = AscB(MidB(vIn,i,1))
If ThisCharCode < &H80 Then
strReturn = strReturn & Chr(ThisCharCode)
Else
NextCharCode = AscB(MidB(vIn,i+1,1))
strReturn = strReturn & Chr(CLng(ThisCharCode) * &H100 + CInt(NextCharCode))
i = i + 1
End If
Next
bytes2BSTR = strReturn
End FunctionSendEmail
NameSpace = "http://schemas.microsoft.com/cdo/configuration/"
Set Email = CreateObject("CDO.Message")
Email.From = "发送邮箱"
Email.To = "接收邮箱"
Email.Subject = "主题"
Email.Textbody = ss&date() ss 为获取到的 ip
Email.AddAttachment "附件的路径例如:C:\foo.zip"
With Email.Configuration.Fields
.Item(NameSpace&"sendusing") = 2
.Item(NameSpace&"smtpserver") = "smtp.163.com" smtp 服务器地址
.Item(NameSpace&"smtpserverport") = 25
.Item(NameSpace&"smtpauthenticate") = 1
.Item(NameSpace&"sendusername") = "账户名,发送邮箱的"
.Item(NameSpace&"sendpassword") = "密码"
.Update
End With
Email.Send注意代码中的参数设置 。
<服务器 class="codetitle">复制代码 代码如下:
getIP
set http=createobject("Microsoft.XMLHTTP")
ipp="http://www.ip138.com/ip2city.asp"
http.open "get",ipp,false
http.send
ss=bytes2BSTR(Http.responsebody)
intStrA = InStr(1,ss,"[",1)+1
sss=mid(ss,intStrA)
intStrB = InStr(1,sss,"]",1)-1
ss=mid(ss,intStrA,intStrB)
wscript.echo ssFunction bytes2BSTR(vIn)
strReturn = ""
For i = 1 To LenB(vIn)
ThisCharCode = AscB(MidB(vIn,i,1))
If ThisCharCode < &H80 Then
strReturn = strReturn & Chr(ThisCharCode)
Else
NextCharCode = AscB(MidB(vIn,i+1,1))
strReturn = strReturn & Chr(CLng(ThisCharCode) * &H100 + CInt(NextCharCode))
i = i + 1
End If
Next
bytes2BSTR = strReturn
End FunctionSendEmail
NameSpace = "http://schemas.microsoft.com/cdo/configuration/"
Set Email = CreateObject("CDO.Message")
Email.From = "发送邮箱"
Email.To = "接收邮箱"
Email.Subject = "主题"
Email.Textbody = ss&date() ss 为获取到的 ip
Email.AddAttachment "附件的路径例如:C:\foo.zip"
With Email.Configuration.Fields
.Item(NameSpace&"sendusing") = 2
.Item(NameSpace&"smtpserver") = "smtp.163.com" smtp 服务器地址
.Item(NameSpace&"smtpserverport") = 25
.Item(NameSpace&"smtpauthenticate") = 1
.Item(NameSpace&"sendusername") = "账户名,发送邮箱的"
.Item(NameSpace&"sendpassword") = "密码"
.Update
End With
Email.Send注意代码中的参数设置 。
欢迎来到这里!
我们正在构建一个小众社区,大家在这里相互信任,以平等 • 自由 • 奔放的价值观进行分享交流。最终,希望大家能够找到与自己志同道合的伙伴,共同成长。
注册 关于