python——遍历网卡并禁用/启用

一、遍历网卡

注意:只能遍历到启用状态的网卡,如果网卡是禁止状态,则遍历不到!!!

python 复制代码
import os
import time
import psutil
import logging

def get_multi_physical_network_card():
    physical_nic_list = []
    try:
        interfaces = psutil.net_if_addrs()
        for interface_name, interface_addresses in interfaces.items():
            if all(virtual_pick not in interface_name.lower() for virtual_pick in {"virtual", "vmware", "hyperv"}):
                for address in interface_addresses:
                    if any(cur_ip in address.address for cur_ip in {"10.", "100.", "169."}):
                        physical_nic_dict = {}
                        physical_nic_dict['name'] = interface_name
                        physical_nic_dict['address'] = address.address
                        physical_nic_list.append(physical_nic_dict)
                        log_str = '当前机器连接网络的网卡名字为:{}, ip:{}'.format(interface_name, address.address)
                        print("\n{}".format(log_str))
        return physical_nic_list
    except Exception as e:
        logging.exception(e)
        return physical_nic_list

physical_nic_list = get_multi_physical_network_card()
for nic_dict in physical_nic_list:
    print(nic_dict )

二、禁用网卡

cmd命令:netsh interface set interface "网卡名" admin=enable/disable

python 复制代码
import os
import time
import psutil
import logging

def disable_multi_physical_network_card():
    try:
        # 注意此处是引用上面的遍历网卡的函数
        physical_nic_list = get_multi_physical_network_card()
        for nic_dict in physical_nic_list:
            address_ip = nic_dict['address']
            physical_nic_name = nic_dict['name']
            disable_cmd = 'netsh interface set interface \"{}\" admin=disable'.format(physical_nic_name)
            os.system(disable_cmd)
            logging.info("physical_nic_name: {}, address_ip: {}".format(physical_nic_name, address_ip))
    except Exception as e:
        logging.exception(e)

三、启用网卡

以上方法是遍历网卡名,然后执行cmd命令逐一禁用

由于目前无法遍历出已禁用的网卡名,所以如果想要启用网卡的话,用上面的方法行不通,建议提前确定好网卡名,不遍历直接cmd

相关推荐
好开心啊没烦恼1 小时前
Python 数据分析:计算,分组统计1,df.groupby()。听故事学知识点怎么这么容易?
开发语言·python·数据挖掘·数据分析·pandas
lljss20202 小时前
Python11中创建虚拟环境、安装 TensorFlow
开发语言·python·tensorflow
空中湖2 小时前
tensorflow武林志第二卷第九章:玄功九转
人工智能·python·tensorflow
CodeCraft Studio3 小时前
CAD文件处理控件Aspose.CAD教程:使用 Python 将绘图转换为 Photoshop
python·photoshop·cad·aspose·aspose.cad
Python×CATIA工业智造5 小时前
Frida RPC高级应用:动态模拟执行Android so文件实战指南
开发语言·python·pycharm
onceco6 小时前
领域LLM九讲——第5讲 为什么选择OpenManus而不是QwenAgent(附LLM免费api邀请码)
人工智能·python·深度学习·语言模型·自然语言处理·自动化
狐凄6 小时前
Python实例题:基于 Python 的简单聊天机器人
开发语言·python
悦悦子a啊7 小时前
Python之--基本知识
开发语言·前端·python
笑稀了的野生俊9 小时前
在服务器中下载 HuggingFace 模型:终极指南
linux·服务器·python·bash·gpu算力
Naiva9 小时前
【小技巧】Python+PyCharm IDE 配置解释器出错,环境配置不完整或不兼容。(小智AI、MCP、聚合数据、实时新闻查询、NBA赛事查询)
ide·python·pycharm