Snippets

Kunzhipeng Python版的pppoe-status

Created by Qi Peng last modified
# coding: utf-8
# pppoe-status.py
# Python版的pppoe-status

import sys
import os
import re
import glob
import time
import subprocess

def find_iface_by_pppoe_conf(pppoe_conf):
    """寻找配置文件(pppoe账号)对应的ppp网络接口
    """
    # pppd pid文件路径
    pppd_pidfile = os.path.join('/var/run/', os.path.basename(pppoe_conf) + '-pppoe.pid.pppd')
    if os.path.exists(pppd_pidfile):
        # pppd进程id
        pppd_pid = open(pppd_pidfile).read().strip()
        # 寻找匹配的ppp进程
        for ppp_pidfile in glob.glob('/var/run/ppp*.pid'):
            if open(ppp_pidfile).read().strip() == pppd_pid:
                # 找到匹配
                return os.path.splitext(os.path.basename(ppp_pidfile))[0]

def pppoe_status_check(pppoe_conf, times_to_check=1):
    ret_code = 1
    for i in range(times_to_check):
        print 'Checking pppoe status for "{}", #{}.'.format(pppoe_conf, i + 1)
        # 直接去找匹配的网络接口
        iface = find_iface_by_pppoe_conf(pppoe_conf=pppoe_conf)
        if iface:
            try:
                print 'ifconfig {}'.format(iface)
                cmd_result = subprocess.check_output(['ifconfig', iface])
            except subprocess.CalledProcessError as exc:
                print 'Status : FAIL. {} {}'.format(exc.returncode, exc.output)
            print cmd_result
            if re.compile(r'inet addr:([^\s]+)').search(cmd_result):
                print "pppoe-status: Link({}) is up and running on interface {}".format(pppoe_conf, iface)
                ret_code = 0
                break
            else:
                print "pppoe-status: Link({}) is attached to {}, but {} is down".format(pppoe_conf, iface, iface)
                if times_to_check > 1:
                    time.sleep(3)
        else:
            print "pppoe-status: Link({}) is down -- could not find interface corresponding to".format(pppoe_conf)
    return ret_code

def test():
    print find_iface_by_pppoe_conf(pppoe_conf=sys.argv[1])

if __name__ == '__main__':
    if '--test' in sys.argv:
        test()
    else:
        pppoe_conf = None
        try:
            pppoe_conf = sys.argv[1]
        except IndexError:
            print 'Usage: python pppoe-status.py pppoe.conf'
        else:
            sys.exit(pppoe_status_check(pppoe_conf=pppoe_conf))

Comments (0)