#!/usr/bin/env python3
import os
import time
import random
import subprocess
from enum import Enum

class InterfaceState(Enum):
    DOWN = 0
    UP = 1

def ping_test():
    """执行ping测试并返回是否成功"""
    try:
        result = subprocess.run(
            ["ping", "172.21.120.100", "-c", "1"],
            check=True,
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
            timeout=5
        )
        return True
    except (subprocess.CalledProcessError, subprocess.TimeoutExpired):
        return False

def toggle_eth0():
    if os.geteuid() != 0:
        print("错误:此脚本需要root权限运行!")
        exit(1)


    try:
        subprocess.run(["ip", "link", "show", "eth0"], 
                      check=True,
                      stdout=subprocess.DEVNULL,
                      stderr=subprocess.DEVNULL)
    except subprocess.CalledProcessError:
        print("错误:网卡 eth0 不存在!")
        exit(1)

    current_state = InterfaceState.DOWN
    operation_count = 0
    ping_success_count = 0
    ping_test_count = 0  

    while operation_count < 500:
        wait_time = random.uniform(1, 5)
        time.sleep(wait_time)

        next_action = InterfaceState.DOWN if current_state == InterfaceState.UP else InterfaceState.UP
        
        try:
            if next_action == InterfaceState.DOWN:
                subprocess.run(["ip", "link", "set", "eth0", "down"], check=True)
                action_str = "关闭"
                need_ping = False
            else:
                subprocess.run(["ip", "link", "set", "eth0", "up"], check=True)
                action_str = "开启"
                need_ping = True
                time.sleep(1)

            current_state = next_action
            operation_count += 1

            if need_ping:
                ping_result = ping_test()
                ping_test_count += 1
                ping_status = "成功" if ping_result else "失败"
                if ping_result:
                    ping_success_count += 1
            else:
                ping_status = "未执行"

            print(
                f"操作#{operation_count}: eth0 {action_str} - "
                f"等待 {wait_time:.2f}秒 - "
                f"Ping测试: {ping_status} - "
                f"总成功率: {ping_success_count/ping_test_count:.1%}" if ping_test_count > 0 else "N/A"
            )

        except subprocess.CalledProcessError as e:
            print(f"操作失败: {e}")
            continue

    print(f"所有500次操作完成!Ping测试次数: {ping_test_count}, 成功率: {ping_success_count/ping_test_count:.1%}" if ping_test_count > 0 else "未执行Ping测试")

if __name__ == "__main__":
    toggle_eth0()
执行端口up/down

 

posted on 2025-06-26 17:51  Star*S  阅读(23)  评论(0)    收藏  举报