邮件效果和配置文件
邮件效果.jpg (39.66 KB, 下载次数: 0)
下载附件
2023-2-20 18:15 上传
INI配置说明.jpg (60.38 KB, 下载次数: 0)
下载附件
2023-2-20 18:15 上传
[color=]python 3.10,使用了psutil和zmail模块
[Python] 纯文本查看 复制代码import configparser
import socket
import time
import getpass
import zmail
import psutil
def get_remote_ips(port, wl_list):
remote_ips = [conn.raddr[0] for conn in psutil.net_connections()
if conn.raddr and conn.status == 'ESTABLISHED'
and not conn.raddr[0].startswith('127.')
and ':' not in conn.raddr[0]
and conn.laddr[1] == port
]
return [ip for ip in set(remote_ips)
if not any(ip.startswith(wl) for wl in wl_list if wl.strip())] or []
def send_mail(remote_ips_dict, config):
aa1, aa2 = socket.gethostname(), getpass.getuser()
aa3 = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
content = [
f'检测时间: {aa3}
主机名: {aa1}
用户名: {aa2}
'
]
for port, remote_ips in remote_ips_dict.items():
if remote_ips:
content.append(
f'连接端口"{port}"的IP地址:
'
f'{"
".join(remote_ips)}
'
f'查询IP归属地
====================
'
)
content = "".join(content)
from_addr, pwd = config.get('Mail', 'from_addr'), config.get('Mail', 'pwd')
title = config.get('Mail', 'title')
to_addr = config.get('to_addr', 'add').split(',')
server = zmail.server(from_addr, pwd)
server.send_mail(to_addr, {'subject': title, 'content_html': content})
config = configparser.ConfigParser()
config.read('Mail.ini', encoding='utf-8-sig')
wl_list = config.get('WL', 'add').split(',')
remote_ips_dict = {}
for port_key, port in config.items('port'):
if port_key.startswith('net_port') and (port := port.strip()).isdigit():
remote_ips = get_remote_ips(int(port), wl_list)
if remote_ips:
remote_ips_dict[int(port)] = remote_ips
if remote_ips_dict.values():
send_mail(remote_ips_dict, config)