import subprocess
import time
from curl_cffi import requests
import random

def is_internet_available():
    targets = [
        "http://www.baidu.com",
        "https://www.sogou.com/",
        "http://www.qq.com",
        "https://www.bing.com/",
        "http://114.114.114.114",
    ]
    for url in targets:
        try:
            requests.get(url, timeout=5)
            return True
        except:
            continue
    return False

def pppoe_ip():
    nums = 0
    while True:
        try:
            print('开始切换ip')
            result = subprocess.run(['sh', '/root/pppoe.sh'], capture_output=True, text=True, check=True)
            print(result.stdout)
            time.sleep(2)
            print(result.stderr)  # 捕获stderr输出
            print('执行 sh 脚本 完成')
            time.sleep(1)
            # 要执行的系统命令
            # 调用函数检测网络连接是否可用
            if is_internet_available():
                print("有网络连接")
                # 设置共享值为True，表示操作已经完成
                break
            else:
                print("没有网络连接", nums)
                nums = min(nums + 10, 60)  # 最多等待120秒，不无限增长
                time.sleep(nums * 2)
        except Exception as e:  # 捕获所有异常，不只是 CalledProcessError
            print('切换ip 失败', e)
            time.sleep(10)
            continue

if __name__ == '__main__':
    pppoe_ip()