簡體   English   中英

用於檢查 Linux 綁定狀態的 Python 腳本

[英]Python script to check bond status for Linux

我有下面的 python 代碼,我用它來確定 Linux 綁定/團隊狀態。 這段代碼工作得很好 我不擅長對齊輸出格式,因此很少打嗝。

我希望將打印格式轉換為某種格式,希望得到任何幫助。

下面是代碼練習:

#!/usr/bin/python
# Using below file to process the data
# cat /proc/net/bonding/bond0

import sys
import re

def usage():
        print '''USAGE: %s [options] [bond_interface]

Options:
        --help, -h      This usage document

Arguments:
        bond_interface  The bonding interface to query, eg. 'bond0'. Default is 'bond0'.
''' % (sys.argv[0])
        sys.exit(1)

# Parse arguments
try:
        iface = sys.argv[1]
        if iface in ('--help', '-h'):
                usage()
except IndexError:
        iface = 'bond0'

# Grab the inf0z from /proc
try:
        bond = open('/proc/net/bonding/%s' % iface).read()
except IOError:
        print "ERROR: Invalid interface %s\n" % iface
        usage()

# Parse and output
active = 'NONE'
Link = 'NONE'
slaves = ''
state = 'OK'
links = ''
bond_status = ''
for line in bond.splitlines():
        m = re.match('^Currently Active Slave: (.*)', line)
        if m:
                active = m.groups()[0]

        m = re.match('^Slave Interface: (.*)', line)
        if m:
                s = m.groups()[0]
                slaves += ', %s' % s

        m = re.match('^Link Failure Count: (.*)', line)
        if m:
                l = m.groups()[0]
                links += ', %s' % l

        m = re.match('^MII Status: (.*)', line)
        if m:
                s = m.groups()[0]
                if slaves == '':
                        bond_status = s
                else:
                        slaves += ' %s' % s

                if s != 'up':
                        state = 'FAULT'

print "%s %s (%s) %s %s %s"  % (iface, state, bond_status, active, slaves, links)

結果:

$ ./bondCheck.py
bond0 OK (up) ens3f0 , ens3f0 up, ens3f1 up , 0, 0

預期的:

bond0: OK (up), Active Slave: ens3f0 , PriSlave: ens3f0(up), SecSlave: ens3f1(up) , LinkFailCountOnPriInt: 0, LinkFailCountOnSecInt: 0

我嘗試以一種非常基本的方式進行格式化,如下所示:

print "%s: %s (%s), Active Slave: %s, PriSlave: %s (%s), SecSlave: %s (%s), LinkFailCountOnPriInt: %s, LinkFailCountOnSecInt: %s"  % (iface, state, bond_status, active, slaves.split(',')[1].split()[0], slaves.split(',')[1].split()[1], slaves.split(',')[2].split()[0], slaves.split(',')[2].split()[1], links.split(',')[1], links.split(',')[2])

結果:

bond0: OK (up), Active Slave: ens3f0, PriSlave: ens3f0 (up), SecSlave: ens3f1 (up), LinkFailCountOnPriInt:  1, LinkFailCountOnSecInt:  1

但是,我建議先將值放入變量中,然后在 print 語句中使用它們,以避免在 print() 期間出現“索引不足”問題,因為在極少數情況下,例如只有一個接口的債券會報告索引錯誤,而拆分因此很好地獲取變量中的值並將索引外的值抑制為這些情況的異常。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM