标签:subject utf-8 from 检查 conf eve 功能 email eth
需求:
从外网通过VPN访问内网,并登录电脑A。在电脑A通过共享文件夹(需要\\IP的方式访问)访问到内网电脑B,由于电脑B的WI-FI的IP地址会变化,所以当电脑B的I访问路径需要获知电脑B的最新IP
import socket
import smtplib
import json
from email.header import Header
from email.mime.text import MIMEText
from email.utils import parseaddr, formataddr
import threading
now_ip = ""
mail_param_json = ""
# 内网B为win7操作系统,内网IP以10开头,取WIFI-IP def _get_ip_win(): ips = socket.gethostbyname_ex(socket.gethostname()) for s in ips[2]: if s.startswith(‘10‘): return s
#发送邮件到指定的邮箱 #配置文件为json字符串:‘{"from_addr": "", "password": "", "to_addr": "", "smtp_server":""}‘ def _format_addr(s): name, addr = parseaddr(s) return formataddr((Header(name, ‘utf-8‘).encode(), addr)) def send_mail(json_param_str=None): if json_param_str != None and isinstance(json_param_str, str): e_param = json.loads(json_param_str) from_addr = e_param.get(‘from_addr‘) password = e_param.get(‘password‘) to_addr = e_param.get(‘to_addr‘) smtp_server = e_param.get(‘smtp_server‘) msg = MIMEText(‘ip address changed to : ‘ + _get_ip_win() + ‘\r\n‘, ‘plain‘, ‘utf-8‘) msg[‘From‘] = _format_addr(‘Reboot <%s>‘ % from_addr) msg[‘To‘] = _format_addr(‘Reboot <%s>‘ % to_addr) msg[‘Subject‘] = Header(‘NOTICE!!!--PC IP CHANGED‘, ‘utf-8‘).encode() server = smtplib.SMTP(smtp_server, 25) server.set_debuglevel(1) server.login(from_addr, password) server.sendmail(from_addr, [to_addr], msg.as_string()) server.quit() else: pass
#定时检查IP是否有变化 def checkIP(start_ip): global now_ip if start_ip != now_ip: global mail_param_json send_mail(mail_param_json) print("发送邮件,旧IP:",now_ip,"---新IP:",start_ip) now_ip = start_ip else: print("IP地址未发生变化,旧IP:", start_ip, "---新IP:", now_ip) new_ip = _get_ip_win() t = threading.Timer(3600.0, checkIP,(new_ip,)) t.start()
#初始化 读取配置文件 if __name__ == ‘__main__‘: with open(‘./config‘, ‘r‘) as f: mail_param_json = f.read() start_ip,now_ip = _get_ip_win(),_get_ip_win() checkIP(start_ip)
PS:
1、仅实现的基本功能,代码不够规范
2、待修改增加log记录,配置文件写入到sqlLite中
3、方法需要重构,不灵活
标签:subject utf-8 from 检查 conf eve 功能 email eth
原文地址:http://www.cnblogs.com/GYoungBean/p/6510508.html