python 监控电脑的IP变化

# setup
$ ifconfig eno1 |grep "inet addr"| cut -f 2 -d ":"|cut -f 1 -d " " > /home/moonx/watch_ip_change/old_ip.txt

# 每分钟查看ip, 如果ip变了就把新ip发到邮箱
$ crontad -e
# 添加以下
*/1 * * * * bash /home/moonx/watch_ip_change/run.sh

run.sh

#!/bin/bash
device_name="eno1"

/sbin/ifconfig $device_name |grep "inet addr"| cut -f 2 -d ":"|cut -f 1 -d " " > /home/moonx/watch_ip_change/new_ip.txt
cd /home/moonx/watch_ip_change/; python3 send_ip.py
/sbin/ifconfig $device_name |grep "inet addr"| cut -f 2 -d ":"|cut -f 1 -d " " > /home/moonx/watch_ip_change/old_ip.txt

send_ip.py

import os
import datetime
import smtplib
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication

def read_ip(ip_txt):
    with open(ip_txt, 'r') as f:
        ip = f.read().strip() 
    return ip

def send_email(send_email_flag, old_ip, new_ip):
    if send_email_flag == False:
        return

    fromaddr = '782679034@qq.com'
    password = '****************'
    toaddrs = ['782679034@qq.com']

    content = '新IP: ' +  new_ip

    textApart = MIMEText(content)
    m = MIMEMultipart()
    m.attach(textApart)
    m['Subject'] = 'Rui的IP变了'

    now_time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')

    try:
        server = smtplib.SMTP('smtp.qq.com')
        server.login(fromaddr, password)
        server.sendmail(fromaddr, toaddrs, m.as_string())
        print('success')

        with open("email.log", "a") as f:
            f.write(now_time + ' 邮件发送成功!' + '之前IP: ' + old_ip + ' 变为: ' + new_ip +  '\n')

        server.quit()
        
    except smtplib.SMTPException as e:
        print('error:', e)
        with open("email.log", "a") as f:
            f.write(now_time + ' 邮件发送失败: ' + str(e) + '\n')
   
def main():
    old_ip = read_ip("old_ip.txt")
    new_ip = read_ip("new_ip.txt")
    send_email_flag = old_ip != new_ip
    send_email(send_email_flag, old_ip, new_ip)

if __name__ == "__main__":
    main()    
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值