如何通过 python 脚本识别我是否有 PPP 连接,如果有,请打开 LED



我使用的是Orange Pi 2g物联网板,没有图形界面和发行版Ubuntu 16.04。该板有一个调制解调器2G,通常可以通过Python脚本将URL发送到我的Firebase应用程序,但有时无法建立连接。它是通过wvdial的pppd连接。我想在硬件方面(avulse LED 开/关)了解我的调制解调器 2G 是否已连接。

谁能帮我解决这个问题?

非常感谢!

如果你可以使用外部python包:pip安装netifaces。

使用此软件包,您可以测试该接口是否存在,然后测试是否可以访问Google。 此代码未经测试,但应该会让您非常接近。

import netifaces
import requests
ppp_exists = False
try:
    netifaces.ifaddresses('ppp0') # this assumes that you only have one ppp instance running
    ppp_exists = True
except:
    ppp_exists = False
# you have an interface, now test if you have a connection
has_internet = False
if ppp_exists == True:
    try:
        r = requests.get('http://www.google.com', timeout=10) # timeout is necessary if you can't access the internet
        if r.status_code == requests.codes.ok:
            has_internet = True
        else:
            has_internet = False
    except requests.exceptions.Timeout:
        has_internet = False
if ppp_exists == True and has_internet == True:
    # turn on LED with GPIO
    pass
else:
    # turn off LED with GPIO
    pass

更新

您可以使用以下命令将 ifconfig 的输出记录到文本文件中

os.system('ifconfig > name_of_file.txt')

然后,您可以根据需要解析它。 下面是一种方法,也可以检查以确保 ppp 接口存在。

import os
import netifaces
THE_FILE = './ifconfig.txt'
class pppParser(object):
    """
    gets the details of the ifconfig command for ppp interface
    """
    def __init__(self, the_file=THE_FILE, new_file=False):
        """
        the_file is the path to the output of the ifconfig  command
        new_file is a boolean whether to run the os.system('ifconfig') command
        """
        self.ppp_exists = False
        try:
            netifaces.ifaddresses('ppp0') # this assumes that you only have one ppp instance running
            self.ppp_exists = True
        except:
            self.ppp_exists = False
        if new_file:
            open(the_file, 'w').close() # clears the contents of the file
            os.system('sudo ifconfig > '+the_file)
        self.ifconfig_text = ''
        self.rx_bytes = 0
        with open(the_file, 'rb') as in_file:
            for x in in_file:
                self.ifconfig_text += x
    def get_rx_bytes(self):
        """
        very basic text parser to gather the PPP interface data.
        Assumption is that there is only one PPP interface
        """
        if not self.ppp_exists:
            return self.rx_bytes
        ppp_text = self.ifconfig_text.split('ppp')[1]
        self.rx_bytes = ppp_text.split('RX bytes:')[1].split(' ')[0]
        return self.rx_bytes

只需调用 pppParser().get_rx_bytes()

我不知道

这方面的python功能。但我建议你使用python(如果你必须的话)用一个系统实用程序来分叉一个进程,为你提供网络设备的当前状态。你可以遵循这一行:在Python中调用外部命令,并调用例如"ifconfig"。您的 ppp 设备应该显示在那里。

相关内容

最新更新