

def 截图(save_path=None, start_x=0, start_y=0, width=None, height=None):
    import ctypes
    import pyautogui
    import os
    """
    屏幕截图函数

    参数:
        save_path (str|None): 保存路径，例如 C:\\test.png，为None则不保存
        width (int|None): 截图宽度，为None则全屏
        height (int|None): 截图高度，为None则全屏
        start_x (int): 起始X坐标
        start_y (int): 起始Y坐标

    返回:
        save_path (str) 或 PIL.Image.Image
    """

    # 修复Windows DPI缩放问题
    ctypes.windll.user32.SetProcessDPIAware()

    # 获取屏幕尺寸
    screen_width, screen_height = pyautogui.size()

    # 判断截图区域
    if width is None or height is None:
        region = (0, 0, screen_width, screen_height)
    else:
        region = (start_x, start_y, width, height)

    # 执行截图
    image = pyautogui.screenshot(region=region)

    # 保存文件（如果提供路径）
    if save_path:

        folder = os.path.dirname(save_path)

        if folder and not os.path.exists(folder):
            os.makedirs(folder)

        image.save(save_path)

    # 否则返回图像对象
    return image


def 解析ip(域名列表: list, DNS: list = None, 返回类型: str = 'list'):
    """
    解析域名IP地址
    解析ip(域名列表: list, DNS: list = None, 返回类型: str = 'list')
        域名列表：每个域名一个元素
        DNS：DNS服务器列表，默认使用常用DNS服务器
        返回类型：返回数据类型【list】
    """
    import dns.resolver
    from xiaokang.d多线程 import 多线程

    if DNS:
        DNS = DNS
    else:
        DNS = [
            "8.8.8.8",
            "8.8.4.4",
            "1.1.1.1",
            "1.0.0.1",
            "9.9.9.9",
            "149.112.112.112",
            "223.5.5.5",
            "223.6.6.6",
            "114.114.114.114",
            "114.114.115.115",
            "101.226.4.6",
            "218.30.118.6",
            "221.179.155.161",
            "211.138.180.2",
            "202.96.128.86",
            "202.96.128.166",
            "202.106.0.20",
            "202.106.196.115",
        ]
    DNS列表 = []

    def dns服务器连接(DNS):
        DNS服务器 = dns.resolver.Resolver(configure=False)
        DNS服务器.nameservers = [DNS]
        DNS服务器.lifetime = 2
        DNS服务器.timeout = 2
        return DNS服务器

    DNS列表 = 多线程(DNS, dns服务器连接, 20, False)

    # 全部数据【域名*DNS(18)*记录类型(2)】,每个域名至少跑36次DNS解析
    解析列表 = []
    for f1 in 域名列表:
        for f2 in DNS列表:
            for f3 in ["A", "AAAA"]:
                解析列表.append((f1.strip(), f2, f3))

    def 解析域名(值):
        # 值.append(str(e))
        # return 值
        try:
            域名, DNS服务器, 记录类型 = 值
            值 = list(值)
            answers = DNS服务器.resolve(域名, 记录类型)
            for rdata in answers:
                ip = rdata.to_text()
                return [域名, 记录类型, ip]
        except Exception as e:
            return [域名, 记录类型, '']

    结果 = 多线程(解析列表, 解析域名, 100)

    返回结果 = {}
    for f1 in 结果:
        if len(f1) < 3:
            continue

        if not 返回结果.get(f1[0]):
            返回结果[f1[0]] = [[], []]

        if f1[1] == "A":
            返回结果[f1[0]][0].append(f1[2])
        else:
            返回结果[f1[0]][1].append(f1[2])

    for f1, f2 in 返回结果.items():
        返回结果[f1][0] = list(set(返回结果[f1][0]))
        返回结果[f1][1] = list(set(返回结果[f1][1]))
        返回结果[f1][0].remove('')
        返回结果[f1][1].remove('')

    if 返回类型 == 'list':
        return 返回结果
    elif 返回类型 == 'dict':
        return list(返回结果.items())


def 查归属(IP列表: list):
    from bs4 import BeautifulSoup
    from xiaokang.d多线程 import 多线程
    import requests
    burp0_url = "https://ip.tool.chinaz.com:443/ipbatch"
    burp0_cookies = {
        "cz_statistics_visitor": "132d6f52-f8f1-4302-d10e-2e5678333942",
        "toolbox_urls": "www.kmmc.cn%2f%3fpc",
        "qHistory": "aHR0cDovL2lwLnRvb2wuY2hpbmF6LmNvbS9pcGJhdGNoL19JUOaJuemHj+afpeivog=="
    }
    burp0_headers = {
        "Sec-Ch-Ua": "\"Not/A)Brand\";v=\"8\", \"Chromium\";v=\"126\", \"Google Chrome\";v=\"126\"",
        "Sec-Ch-Ua-Mobile": "?0",
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36",
        "Sec-Ch-Ua-Platform": "\"Windows\"",
        "Accept": "*/*",
        "Origin": "https://ip.tool.chinaz.com",
        "Sec-Fetch-Site": "same-site",
        "Sec-Fetch-Mode": "cors",
        "Sec-Fetch-Dest": "empty",
        "Referer": "https://ip.tool.chinaz.com/",
        "Accept-Encoding": "gzip, deflate",
        "Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8",
        "Dnt": "1",
        "Sec-Gpc": "1",
        "Priority": "u=1, i"
    }

    # 读取全部ip地址
    结果字典 = {}
    list1 = []  # 拆分成300个ip一份
    sz = 0
    while 1:
        if sz > len(IP列表):
            break
        list1.append(IP列表[sz:sz+300])
        sz += 300

    def 站长解析(域名列表):
        burp0_data = {"ips": '\r\n'.join(域名列表), "submore": "\xe6\x9f\xa5\xe8\xaf\xa2"}
        r = requests.post(burp0_url, headers=burp0_headers, cookies=burp0_cookies, data=burp0_data, timeout=60)
        soup = BeautifulSoup(r.text, "html.parser")
        tr1 = soup.find('tbody', id='ipList').find_all('tr')
        jglb = []
        for f2 in tr1:
            td1 = f2.find_all('td')
            jglb.append([td1[0].text.strip(), td1[3].text.strip()])
        return jglb

    解析结果 = 多线程(列表=list1, 函数=站长解析, 线程数=3)
    返回结果 = []
    for f1 in 解析结果:
        返回结果.extend(f1)

    return 返回结果


def 获取title(url, ssl=True, timeout=10, 进程锁=''):
    from bs4 import BeautifulSoup
    import requests
    import json

    ssl = 'https' if ssl else 'http'

    headers = {
        "Pragma": "no-cache",
        "Cache-Control": "no-cache",
        "Upgrade-Insecure-Requests": "1",
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/93.0.4577.82 Safari/537.36",
        "Accept-Language": "zh-CN,zh;q=0.9",
    }
    try:
        r = requests.get(ssl+'://'+url + "/", headers=headers, verify=False, timeout=timeout)
        soup = BeautifulSoup(r.content, 'html.parser')
        if not soup.title:
            title = f'网页大小：{len(r.content)}'
        elif soup.title.string:
            title = soup.title.string.strip()
        else:
            title = f'网页大小：{len(r.content)}'
        with 进程锁:
            结果[url][ssl].append(title.replace('\r', '').replace('\n', '').replace('\t', '').strip()+'\t'+str(r.status_code))
    except requests.exceptions.ConnectionError:
        # 如果连接失败，则该 URL 不可用
        with 进程锁:
            结果[url][ssl].append('报xk错：无法连接'+'\t'+'-1')
    except requests.exceptions.RequestException as e:
        # 如果连接失败，则该 URL 不可用
        with 进程锁:
            结果[url][ssl].append(f"报xk错：请求异常: {str(e)}".replace('\r', '').replace('\n', '').replace('\t', '').strip()+'\t'+'-1')
    except requests.exceptions.SSLError:
        # 如果连接失败，则该 URL 不可用
        with 进程锁:
            结果[url][ssl].append('报xk错：SSL错误'+'\t'+'-1')
    except requests.exceptions.Timeout:
        # 如果连接超时，则该 URL 不可用
        with 进程锁:
            结果[url][ssl].append('报xk错：连接超时'+'\t'+'-1')
    except:
        # 未知报错
        with 进程锁:
            结果[url][ssl].append('报xk错：未知报错'+'\t'+'-1')
            except_type, except_value, except_traceback = sys.exc_info()
            exc_dict = {
                "报错类型": str(except_type),
                "报错信息": str(except_value),
                "报错文件": except_traceback.tb_frame.f_code.co_filename,
                "报错行数": except_traceback.tb_lineno,
            }
            print(json.dumps(exc_dict, ensure_ascii=False, indent=4, separators=(',', ':')))


def 发送邮件(发送者: str, 接收者: str, POP3: str, 邮件主题: str, 邮件内容: str):
    import smtplib
    from email.header import Header
    from email.mime.text import MIMEText
    import smtplib

    '''
    暂时只支持QQ邮箱，文本内容

    发送者: 发送者的邮箱地址
    接收者: 接收者的邮箱地址
    POP3: QQ邮箱的POP3授权码
    邮件主题: 邮件主题文本内容
    邮件内容: 邮件内容文本内容
    '''
    try:
        QQ服务器 = smtplib.SMTP_SSL('smtp.qq.com')
        QQ服务器.connect('smtp.qq.com', 465)
        QQ服务器.login(发送者, POP3)
        fsnr = MIMEText(邮件内容, 'plain', 'utf-8')
        fsnr['subject'] = 邮件主题
        fsnr['From'] = Header(发送者)  # 发送者
        fsnr['To'] = Header(接收者)  # 接收者
        QQ服务器.sendmail(发送者, 接收者, fsnr.as_string())
        QQ服务器.quit()
        return True
    except:
        return False


def 批量发送邮件(发送者: str, 接收者: list, POP3: str, 邮件主题: str, 邮件内容: str):
    import smtplib
    from email.header import Header
    from email.mime.text import MIMEText
    import smtplib

    '''
    发送者: 发送者的邮箱地址
    接收者: 接收者的邮箱地址的列表[xx@qq.com, xx@qq.com]
    POP3: QQ邮箱的POP3授权码
    邮件主题: 邮件主题文本内容
    邮件内容: 邮件内容文本内容
    '''
    try:
        QQ服务器 = smtplib.SMTP_SSL('smtp.qq.com')
        QQ服务器.connect('smtp.qq.com', 465)
        QQ服务器.login(发送者, POP3)
        fsnr = MIMEText(邮件内容, 'plain', 'utf-8')
        fsnr['subject'] = 邮件主题
        fsnr['From'] = Header(发送者)  # 发送者
        for f1 in 接收者:
            fsnr['To'] = Header(f1)  # 接收者
            QQ服务器.sendmail(发送者, f1, fsnr.as_string())
        QQ服务器.quit()
        return True
    except:
        return False


if __name__ == '__main__':
    pass
    # 截图(save_path='C:\\test.png')
    # print(解析ip(open('ip.txt', 'r', encoding='utf-8').readlines()))
    # 域名列表 = open('ip.txt', 'r', encoding='utf-8').readlines()
    # a=查归属(域名列表)

