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

相关推荐
Python大数据分析@19 分钟前
Origin、MATLAB、Python 用于科研作图,哪个最好?
开发语言·python·matlab
编程零零七1 小时前
Python巩固训练——第一天练习题
开发语言·python·python基础·python学习·python练习题
Zonda要好好学习1 小时前
Python入门Day4
java·网络·python
小龙在山东2 小时前
Python 包管理工具 uv
windows·python·uv
weixin_307779132 小时前
批量OCR的GitHub项目
python·github·ocr
孤狼warrior3 小时前
灰色预测模型
人工智能·python·算法·数学建模
神仙别闹3 小时前
基于Python实现LSTM对股票走势的预测
开发语言·python·lstm
机器学习之心4 小时前
小波增强型KAN网络 + SHAP可解释性分析(Pytorch实现)
人工智能·pytorch·python·kan网络
JavaEdge在掘金4 小时前
MySQL 8.0 的隐藏索引:索引管理的利器,还是性能陷阱?
python
站大爷IP4 小时前
Python办公自动化实战:手把手教你打造智能邮件发送工具
python