循环重启修改buildroot系统,interfaces文件mac地址

import serial
import time
import re
import threading
from serial.tools import list_ports
from time import sleep
from datetime import datetime  # 导入 datetime 模块


# 串口连接函数
def connect_serial(port, baudrate=115200, timeout=1):
    ser = serial.Serial(port, baudrate, timeout=timeout)
    return ser


# 发送命令并接收输出
def send_command(ser, command, wait_time=0.5):
    ser.write((command + '\n').encode())  # 发送命令
    time.sleep(wait_time)  # 等待命令执行
    output = ser.read_all().decode(errors='ignore')  # 读取串口返回信息,忽略解码错误
    return output


# 登录到设备
def login(ser, username, password):
    print(f"Logging in as {username}...")
    send_command(ser, username)
    time.sleep(1)  # 等待提示符
    send_command(ser, password)
    time.sleep(1)  # 等待登录完成


# 执行操作步骤
def execute_commands(ser, mac_address, log_file_path):
    # 登录
    login(ser, 'root', 'root')  # 替换为实际的 root 密码

    # 1. 以读写模式重新挂载根目录
    print("Mounting root directory as read-write...")
    send_command(ser, 'mount / -o remount,rw')

    # 2. 打印当前 /etc/network/interfaces 文件内容
    print("Current /etc/network/interfaces content:")
    cat_interfaces0 = send_command(ser, 'cat /etc/network/interfaces')
    print("修改之前的文件内容", cat_interfaces0)

    output_ifconfig0 = send_command(ser, 'ifconfig eth0', wait_time=2)  # 只检查 eth0 的信息
    print('修改之前的ifconfig内容', output_ifconfig0)

    # 3. 编辑 /etc/network/interfaces 文件
    print("Editing /etc/network/interfaces file...")
    command = (
        f'echo -e "# interface file auto-generated by buildroot\\n'
        f'auto lo\\n'
        f'iface lo inet loopback\\n\\n'
        f'auto eth0\\n'
        f'iface eth0 inet dhcp\\n'
        f'    metric 700\\n'
        f'    pre-up ifconfig eth0 hw ether {mac_address}" '
        f'> /etc/network/interfaces'
    )
    send_command(ser, command)

    # 4. 重启设备
    print("Rebooting device...")
    send_command(ser, 'reboot')

    # 等待设备重启
    time.sleep(40)  # 根据设备的重启时间调整

    # 5. 重新登录
    login(ser, 'root', 'root')  # 替换为实际的 root 密码

    # 6. 打印网络接口信息
    print("Fetching network interface information after reboot...")
    sleep(5)
    sleep_inet = send_command(ser, 'ls')
    print(sleep_inet)
    sleep(20)
    send_command(ser, 'ifconfig eth0', wait_time=2)
    sleep(20)
    send_command(ser, 'ifconfig eth0', wait_time=2)
    sleep(20)
    send_command(ser, 'ifconfig eth0', wait_time=2)
    sleep(20)
    output_ifconfig1 = send_command(ser, 'ifconfig eth0', wait_time=2)  # 只检查 eth0 的信息
    print('修改之后的ifconfig内容', output_ifconfig1)
    cat_interfaces1 = send_command(ser, 'cat /etc/network/interfaces')
    print("修改之后的文件内容", cat_interfaces1)
    # 检查 output_ifconfig1 是否包含 inet
    inet_match = re.search(r'inet (\d+\.\d+\.\d+\.\d+)', output_ifconfig1)
    mac_match = re.search(r'ether ([0-9a-fA-F:]{17})', output_ifconfig1)  # 匹配 MAC 地址

    # 准备日志信息
    timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S')  # 获取当前时间并格式化
    if inet_match and mac_match:
        ip_address = inet_match.group(1)  # 提取 IP 地址
        mac_address = mac_match.group(1)  # 提取 MAC 地址
        log_message = f"[{timestamp}] IP Address: {ip_address}, MAC Address: {mac_address}\n"
    else:
        log_message = f"[{timestamp}] MAC Address {mac_address} cannot be used.\n"

    # 将结果写入日志文件
    with open(log_file_path, 'a') as log_file:
        log_file.write(log_message)

    print("Log written to", log_file_path)

    cat_interfaces1 = send_command(ser, 'cat /etc/network/interfaces')
    print(cat_interfaces1)
    print("")


# 串口操作的多线程函数,支持无限循环
def serial_thread(port, mac_addresses, start_index, interval=60):
    # 为每个串口生成一个独立的日志文件
    log_file_path = f'network_info_{port.replace("/", "_")}.log'

    ser = connect_serial(port)
    try:
        mac_index = start_index  # 初始化 MAC 地址索引
        while True:  # 无限循环
            mac = mac_addresses[mac_index]
            print(f"Using MAC address: {mac} on port: {port}")
            execute_commands(ser, mac, log_file_path)

            # 更新 MAC 地址索引
            mac_index = (mac_index + 1) % len(mac_addresses)

            # 等待设定的时间间隔再进行下一次 MAC 地址修改
            print(f"Waiting {interval} seconds before the next MAC change...")
            time.sleep(interval)  # 设置循环时间间隔
    finally:
        ser.close()


# 获取所有可用串口
def get_available_serial_ports():
    ports = list_ports.comports()
    return [port.device for port in ports]


if __name__ == "__main__":
    # 定义 MAC 地址列表
    mac_addresses = [
        '0a:0d:97:a2:fe:d9',
        'ae:ee:0b:8e:ba:f2',
        'ae:ee:0b:8e:ba:f3',
    ]

    # 获取所有可用串口
    available_ports = get_available_serial_ports()
    print("Available serial ports:", available_ports)

    # 设置时间间隔(秒),例如每 60 秒执行一次
    interval = 5  # 可根据需要调整时间间隔

    # 为每个串口创建一个线程,并执行 MAC 地址循环修改
    threads = []
    for idx, port in enumerate(available_ports):
        # 每个串口从不同的 MAC 地址开始
        start_index = idx % len(mac_addresses)
        t = threading.Thread(target=serial_thread, args=(port, mac_addresses, start_index, interval))
        threads.append(t)
        t.start()

    # 等待所有线程执行完毕
    for t in threads:
        t.join()

 

posted @ 2024-12-27 16:13  江米小团子  阅读(38)  评论(0)    收藏  举报