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

相关推荐
Narutolxy33 分钟前
Python 单元测试:深入理解与实战应用20240919
python·单元测试·log4j
Amo Xiang1 小时前
2024 Python3.10 系统入门+进阶(十五):文件及目录操作
开发语言·python
liangbm31 小时前
数学建模笔记——动态规划
笔记·python·算法·数学建模·动态规划·背包问题·优化问题
B站计算机毕业设计超人1 小时前
计算机毕业设计Python+Flask微博情感分析 微博舆情预测 微博爬虫 微博大数据 舆情分析系统 大数据毕业设计 NLP文本分类 机器学习 深度学习 AI
爬虫·python·深度学习·算法·机器学习·自然语言处理·数据可视化
羊小猪~~1 小时前
深度学习基础案例5--VGG16人脸识别(体验学习的痛苦与乐趣)
人工智能·python·深度学习·学习·算法·机器学习·cnn
waterHBO3 小时前
python 爬虫 selenium 笔记
爬虫·python·selenium
编程零零七4 小时前
Python数据分析工具(三):pymssql的用法
开发语言·前端·数据库·python·oracle·数据分析·pymssql
AIAdvocate6 小时前
Pandas_数据结构详解
数据结构·python·pandas
小言从不摸鱼6 小时前
【AI大模型】ChatGPT模型原理介绍(下)
人工智能·python·深度学习·机器学习·自然语言处理·chatgpt
FreakStudio8 小时前
全网最适合入门的面向对象编程教程:50 Python函数方法与接口-接口和抽象基类
python·嵌入式·面向对象·电子diy