Python3 判断IPv4网络适配器是否在运行

这个Python脚本用于检查指定IP的网络接口是否处于活动状态,支持Windows和Linux系统。通过调用操作系统命令`ipconfig`或`ifconfig`来获取信息,对于未支持的操作系统,它会返回错误信息。若需要跨平台解决方案,建议寻找可靠的第三方库。
摘要由CSDN通过智能技术生成

 

这是一个简单实现,仅支持 Windows 和 Linux 系统,对操作系统的基础指令存在强依赖,或可导致结果误报。

如有可靠三方包支持该功能,烦请@maozexijr,不胜感激!!

 

# !/usr/bin/python3
# coding: utf-8
import os
import sys


def is_adapter_up(ip):
    """
    ip like 127.0.0.1
    """
    if 'win32' == sys.platform:
        cmd = 'ipconfig |findstr "%s"'
        # Using `ipconfig -all` to show all, includes not running
    elif 'linux' == sys.platform:
        cmd = 'ifconfig |grep "%s"'
        # Using `ifconfig -a` to show all, includes not running
        # Using `ifconfig NAME up` to start
        # Using `ifconfig NAME down` to close
    else:
        print('Unsupported system type %s' % sys.platform)
        return False

    with os.popen(cmd % ip, 'r') as f:
        if '' != f.read():
            # UP and RUNNING
            return True
        else:
            print('Network adapter %s is not running' % ip)
            return False

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值