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

相关推荐
进击的松鼠16 小时前
从对话到动作:用 Function Calling 把 LLM 接到真实 API(含流程拆解)
python·llm·agent
Polar__Star16 小时前
HTML函数在多GPU系统中如何调用_显卡切换机制说明【汇总】
jvm·数据库·python
2301_8135995516 小时前
mysql为什么不要在索引列上做运算_mysql函数索引使用场景
jvm·数据库·python
好家伙VCC17 小时前
**发散创新:基于FFmpeg的视频编码优化实践与实战代码解析**在现代多媒体系统中,
java·python·ffmpeg·音视频
人工干智能17 小时前
科普:CountVectorizer、TF、TF-IDF,三者层层递进
python·tf-idf
qq_3422958217 小时前
如何监控集群 interconnect_ping与traceroute验证心跳通畅
jvm·数据库·python
qq_3422958217 小时前
Go语言错误处理如何做_Go语言error错误处理教程【实用】
jvm·数据库·python
qq_3345635517 小时前
如何在phpMyAdmin中执行多条SQL语句_分号分隔与批量执行解析
jvm·数据库·python
2401_8971905517 小时前
Golang如何做Clean Architecture_Golang整洁架构教程【详解】
jvm·数据库·python
qq_1898070317 小时前
如何在网页中实现国际象棋棋子的拖拽与格点吸附功能
jvm·数据库·python