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

相关推荐
刘一说2 分钟前
Java中基于属性的访问控制(ABAC):实现动态、上下文感知的权限管理
java·网络·python
一晌小贪欢3 分钟前
Python 操作 Excel 高阶技巧:用 openpyxl 玩转循环与 Decimal 精度控制
开发语言·python·excel·openpyxl·python办公·python读取excel
铁蛋AI编程实战6 分钟前
Falcon-H1-Tiny 微型 LLM 部署指南:100M 参数也能做复杂推理,树莓派 / 手机都能跑
java·人工智能·python·智能手机
写代码的【黑咖啡】19 分钟前
Python 中的自然语言处理工具:spaCy
开发语言·python·自然语言处理
高洁0120 分钟前
多模态融合驱动下的具身学习机制研究
python·算法·机器学习·数据挖掘·知识图谱
狗都不学爬虫_22 分钟前
JS逆向 -最新版 盼之(decode__1174、ssxmod_itna、ssxmod_itna2)纯算
javascript·爬虫·python·网络爬虫·wasm
七夜zippoe1 小时前
Dask:超越内存限制的并行计算——从任务图到分布式调度的实战指南
python·集群·task·array·dataframe·dask
serve the people1 小时前
python环境搭建 (五) Dockerfile 和 docker-compose.yml 核心作用
java·python·docker
维构lbs智能定位1 小时前
工厂人员定位(一)融合定位技术如何重构安全生产与效率管理?(含系统架构、技术选型对比、实际应用)
python·物联网·智慧工厂·厂区人员定位系统·工厂人员定位·工厂定位系统
yufuu981 小时前
进阶技巧与底层原理
jvm·数据库·python