Python邮件通知本地外网IP

每天去公司、去实验室,又想用宿舍电脑上的资料,SSH、远程自然是不二选择。但是每次开机CMD,IPCONFIG自己的IP有点太麻烦,还是用强大Python来方便自己吧。

Python代码如下,保存为PYW文件,添加到开机启动项,开机后登陆用户,便可获取自己外网IP,邮件通知指定邮箱。

 

#!/usr/bin/env python # -*- coding:utf-8 -*- # -*- coding: gbk -*- #导入smtplib和MIMEText import smtplib from email.mime.text import MIMEText import re,urllib2 import datetime import time dateToday=str(datetime.date.today()) mailto_list=["[email protected]","[email protected]"] #to WHOM #设置服务器,用户名、口令以及邮箱的后缀 mail_host="smtp.126.com" mail_user="lxl_pc" mail_pass="123456" mail_postfix="126.com" ###################### def send_mail(to_list,sub,content): ''' to_list:发给谁 sub:主题 content:内容 send_mail("[email protected]","sub","content") ''' me=mail_user+"<"+mail_user+"@"+mail_postfix+">" msg = MIMEText(content) msg['Subject'] = sub msg['From'] = me msg['To'] = ";".join(to_list) try: s = smtplib.SMTP() s.connect(mail_host) s.login(mail_user,mail_pass) s.sendmail(me, to_list, msg.as_string()) s.close() return True except Exception, e: print str(e) return False class Getmyip: def getip(self): try: myip = self.visit("http://www.ip138.com/ip2city.asp") except: try: myip = self.visit("http://www.bliao.com/ip.phtml") except: try: myip = self.visit("http://www.whereismyip.com/") except: myip = "So sorry!!! Please check proxy setting!" return myip def visit(self,url): opener = urllib2.urlopen(url) if url == opener.geturl(): str = opener.read() return re.search('/d+/./d+/./d+/./d+',str).group(0) if __name__ == '__main__': getmyip = Getmyip() localip=0 while(1): time.sleep(600) if localip !=getmyip.getip(): localip = getmyip.getip() if send_mail(mailto_list,dateToday,"IP:"+localip+" From Winxp!"): print "发送成功" else: print "发送失败"  

代码不足的地方:

1. 本地使用代理,获取IP肯定失败,改进。。。。

2. Windows平台要是注册为service,就不需要开机登录用户,就可以实现功能了

你可能感兴趣的:(exception,list,python,user,url,import)