import subprocess
import time
import requests
import random

def is_internet_available():
    try:
        print('判断是否有网')
        n = random.randint(70, 114)
        ua = f'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/{n}.0.{random.randint(1000, 5000)}.{random.randint(1, 181)} Safari/537.36'
        headers = {
            'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7',
            'Accept-Encoding': 'gzip, deflate, br',
            'Accept-Language': 'zh-CN,zh;q=0.9',
            'Cache-Control': 'no-cache',
            'User-Agent': ua,
        }
        r = requests.get("https://www.baidu.com", timeout=5,headers=headers)
        print('请求Google：',r.status_code)
        return True
    except Exception as e:
        print(e)
        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 += 10
                time.sleep(nums * 2)
        except subprocess.CalledProcessError as e:
            print('切换ip 失败',e)
            continue

if __name__ == '__main__':
    is_internet_available()