windows下自动获取IP并发到邮箱——python脚本
windows下自动获取IP并发到邮箱——python脚本python脚本windows下自动执行python脚本参考:linux服务器开机发送本机ip地址到指定邮箱import socketimport jsonimport osimport smtplibfrom email.header import Headerfrom email.mime.multipart import MIMEMu
·
windows下自动获取IP并发到邮箱——python脚本
python脚本
import socket
import json
import os
import smtplib
from email.header import Header
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from time import asctime
# only IPv4
# ipv4 = socket.gethostbyname(socket.gethostname())
# print(ipv4)
def send_an_email(email_content): # email_content是一个字符串
mail_host = "smtp.qq.com" # 这个去邮箱找
mail_user = "xxxxxx@qq.com" # 邮箱名
mail_auth_code = "xxxxxxxxxxxxxxxx" # 授权码
mail_sender = mail_user # 用mail_user 作为发送人
mail_receivers = ["xxxxxx@qq.com"]
message = MIMEMultipart()
message['From'] = Header(mail_sender) # 寄件人
message['Subject'] = Header("笔记本当前ip地址")
message.attach(MIMEText(asctime(), 'plain', 'utf-8'))
message.attach(MIMEText(email_content, 'plain', 'utf-8'))
print("message is {}".format(message.as_string())) # debug用
smtpObj = smtplib.SMTP(mail_host)
# smtpObj.set_debuglevel(1) # 同样是debug用的
smtpObj.login(mail_user, mail_auth_code) # 登陆
smtpObj.sendmail(mail_sender, mail_receivers, message.as_string()) # 真正发送邮件就是这里
# 判断ip是否有变化,仅在变化时发送
def get_temp_ip(current_ip):
temp_ip_json_path = "D:\\MySoftware\\ip.json"
if not os.path.exists(temp_ip_json_path):
print("No {}, dump it.".format(temp_ip_json_path))
with open(temp_ip_json_path, 'w') as jo:
json.dump(current_ip, jo)
return True, current_ip
else:
with open(temp_ip_json_path, 'r') as jo:
origin_ip = json.load(jo)
if origin_ip == current_ip:
print("Current ip {} do not change, no need to send".format(current_ip))
return False, current_ip
else:
print("The ip updated from {} to {}, update it.".format(origin_ip, current_ip))
os.remove(temp_ip_json_path)
with open(temp_ip_json_path, 'w') as jo:
json.dump(current_ip, jo)
return True, current_ip
def get_ip():
hostname = socket.gethostname()
addr_infos = socket.getaddrinfo(hostname, None)
ips = set([addr_info[-1][0] for addr_info in addr_infos])
global_ips = [ip for ip in ips]
ipv4 = [ip for ip in ips if ":" not in ip][-1]
ipv6 = [ip for ip in ips if ":" in ip][0]
ipv6_local = [ip for ip in ips if ":" in ip][1]
whether_to_send, send_ip = get_temp_ip(ipv4)
send_ip = json.dumps(send_ip)
return whether_to_send, send_ip
if __name__ == "__main__":
whether_to_send, ipv4 = get_ip()
if whether_to_send:
send_an_email("\nipv4 address:" + ipv4)
else:
print("wait and no send")
windows下自动执行
更多推荐
所有评论(0)