Python+获取外网IP+并发送指定邮件 (一)

需求;如果我们家里或者公司有nas服务器,或者其他需要外网访问的设备及应用,我们应怎么做?

1、拉专线,运营商会给你公网ip,除大公司或企业以外不推荐。

优点;网速快,带宽高,且ip固定。

缺点;烧钱

2、使用软件做域名解析,如;某生壳、某桌互联等一系列解析软件。

优点;省事,下载软件绑定内外ip及端口即可。

缺点;需要购买带宽,和流浪,否则就像便秘一样,如果不想用赠送的域名,还需要花钱购买域名

3、如果你是普通家用网络,不想花钱,我们就按照下列即可免费白嫖。

优点;不烧钱,网速根据个人带宽决定,比域名解析快很多,

缺点;需要一定的动手能力,

1、下载Python+PyCharm

1、python官网:Welcome to Python.org

PyCharm官网:https://www.jetbrains.com/pycharm/

 下载好后;安装并运行即可

2、首先需要打开邮箱SMTP服务

python邮件发送属于第三方服务,需要邮箱开启SMTP服务,以QQ邮箱为例。
第一步:在设置中找到账户

 第二步:找到SMTP服务,点击开启(需要手机向一个号码发送短信,是要钱的,不过也就一条短信费用)。

 最好把授权码复制下来,不然还得再花一次冤枉钱再发一次。

 授权码一定不能泄露!不放心的朋友最好设置自己不常用不绑定信息的邮箱作为测试邮箱。

3、完整代码

我已经帮各位踩过坑了,代码需要更改的地方都有备注;#号标注的地方可以删除

import os
import threading
from smtplib import SMTP_SSL
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.header import Header
from urllib.request import urlopen
import logging

# smtplib模块主要负责发送邮件:是一个发送邮件的动作,连接邮箱服务器,登录邮箱,发送邮件(有发件人,收信人,邮件内容)。
# email模块主要负责构造邮件:指的是邮箱页面显示的一些构造,如发件人,收件人,主题,正文,附件等。
current_ip = urlopen('http://icanhazip.com', timeout=5).read()
current_ip = current_ip.decode(encoding='utf-8')
sender_qq = 'xxxxxxx@qq.com'  # 发送邮箱
receiver = 'xxxxxxx@@qq.com'  # 接收邮箱  
pwd = "xxxxxxxxx"  # 授权码

log_base_dir = "Z:\test\logs"   #存放日志路径
file_name = os.path.join(log_base_dir, "ip.txt")
log_name = os.path.join(log_base_dir, "get_ip.log")

if not os.path.exists(log_base_dir):
    os.mkdir(log_base_dir)

logger = logging.getLogger('logger')
logger.setLevel(level=logging.DEBUG)

formatter = logging.Formatter('%(asctime)s - %(filename)s[line:%(lineno)d] - %(levelname)s: %(message)s')

file_handler = logging.FileHandler(log_name, 'a+', encoding='utf-8')
file_handler.setLevel(level=logging.INFO)
file_handler.setFormatter(formatter)

stream_handler = logging.StreamHandler()
stream_handler.setLevel(logging.DEBUG)
stream_handler.setFormatter(formatter)

logger.addHandler(file_handler)
logger.addHandler(stream_handler)


# 发送邮件
def send_email(my_ip):
    host_server = 'smtp.qq.com'  # qq邮箱smtp服务器
    mail_title = 'IP更换提醒-python'  # 邮件标题
    # mail_content = "外网IP:{}\n发送时间:{}".format(my_ip, time)  # 邮件正文内容
    mail_content = "外网IP:{}".format(my_ip)  # 邮件正文内容
    # 初始化一个邮件主体
    msg = MIMEMultipart()
    msg["Subject"] = Header(mail_title, 'utf-8')
    msg["From"] = 'NAS<xxxxxxx@qq.com>'        # 必须改成发送者的邮箱
    # msg["To"] = Header("测试邮箱",'utf-8')
    msg['To'] = Header(receiver, 'utf-8')
    # 邮件正文内容
    msg.attach(MIMEText(mail_content, 'plain', 'utf-8'))
    smtp = SMTP_SSL(host_server)  # ssl登录

    # login(user,password):
    # user:登录邮箱的用户名。
    # password:登录邮箱的密码,像笔者用的是网易邮箱,网易邮箱一般是网页版,需要用到客户端密码,需要在网页版的网易邮箱中设置授权码,该授权码即为客户端密码。
    smtp.login(sender_qq, pwd)

    # sendmail(from_addr,to_addrs,msg,...):
    # from_addr:邮件发送者地址
    # to_addrs:邮件接收者地址。字符串列表['接收地址1','接收地址2','接收地址3',...]或'接收地址'
    # msg:发送消息:邮件内容。一般是msg.as_string():as_string()是将msg(MIMEText对象或者MIMEMultipart对象)变为str。
    smtp.sendmail(sender_qq, receiver, msg.as_string())

    # quit():用于结束SMTP会话。
    smtp.quit()
    logger.info("邮件发送成功,from = {}, to = {}, content = {}".format(sender_qq, receiver, mail_content))


# 获取ip并对比
def ip_render():
    try:
        new_ip = urlopen('http://icanhazip.com').read()
        current_ip = new_ip.decode(encoding='utf-8')
        logger.info('获取当前IP:{}'.format(current_ip))

        flag = compare_last_ip(current_ip)
        if flag:
            logger.info("发送邮件")
            # send_email(current_ip)
    except Exception as e:
        logger.error("远程调用获取IP异常:{}".format(e))

    timer = threading.Timer(1 * 10, ip_render)  # 10秒 获取IP一次
    timer.start()


# 对比上次获取的ip
def compare_last_ip(current_ip):
    with open(file_name, "a+", encoding='utf-8') as input_file:
        last_ip = read_last_ip()
        logger.info('获取到最后一次记录的IP:{}'.format(last_ip))
        if len(last_ip) == 0:
            logger.info('获取到最后一次记录的IP:首次获取')
            input_file.write(current_ip)
            return True
        if last_ip != current_ip:
            logger.info('IP地址变化')
            input_file.write(current_ip)
            return True
    logger.info('IP地址无变化')
    return False


# 读取上次保存的ip
def read_last_ip():
    try:
        with open(file_name, "r", encoding='utf-8') as read_file:
            contents = read_file.readlines()
            if (len(contents) > 0):
                return contents[-1]
            else:
                return ''
    except FileNotFoundError:
        logger.error("ip.txt文件不存在")
        return ''


if __name__ == "__main__":
    timer = threading.Timer(5, ip_render)  # 5s后开始循环线程
    timer.start()

效果;

  • 5
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值