modify_mac_address.py 文件源码

python
阅读 27 收藏 0 点赞 0 评论 0

项目:Network 作者: Momingcoder 项目源码 文件源码
def set_mac_address(new_mac):
    """
    set the device's MAC address
    """
    # Locate adapter's registry and update network address (mac)
    reg_hdl = winreg.ConnectRegistry(None, winreg.HKEY_LOCAL_MACHINE)
    key = winreg.OpenKey(reg_hdl, WIN_REGISTRY_PATH)
    info = winreg.QueryInfoKey(key)

    # Find adapter key based on sub keys
    adapter_key = None
    adapter_path = None
    target_index = -1

    for index in range(info[0]):
        subkey = winreg.EnumKey(key, index)
        path = WIN_REGISTRY_PATH + "\\" + subkey

        if subkey == 'Properties':
            break

        # Check for adapter match for appropriate interface
        new_key = winreg.OpenKey(reg_hdl, path)
        try:
            adapterDesc = winreg.QueryValueEx(new_key, "DriverDesc")
            if adapterDesc[0] == target_device:
                adapter_path = path
                target_index = index
                break
            else:
                winreg.CloseKey(new_key)
        except (WindowsError) as err:
            if err.errno == 2:  # register value not found, ok to ignore
                pass
            else:
                raise err

    if adapter_path is None:
        print 'Device not found.'
        winreg.CloseKey(key)
        winreg.CloseKey(reg_hdl)
        return

    # Registry path found update mac addr
    adapter_key = winreg.OpenKey(reg_hdl, adapter_path, 0, winreg.KEY_WRITE)
    winreg.SetValueEx(adapter_key, "NetworkAddress", 0, winreg.REG_SZ, new_mac)
    winreg.CloseKey(adapter_key)
    winreg.CloseKey(key)
    winreg.CloseKey(reg_hdl)

    # Adapter must be restarted in order for change to take affect
    # print 'Now you should restart your netsh'
    restart_adapter(target_index)

# regex to MAC address like 00-00-00-00-00-00 or 00:00:00:00:00:00 or
# 000000000000
评论列表
文章目录


问题


面经


文章

微信
公众号

扫码关注公众号