开发者社区> 问答> 正文

用于检查Linux绑定状态的Python脚本

我有下面的python代码,用于确定Linux绑定/团队状态。此代码可以正常工作。我不擅长对齐输出格式,因此很少打little。

我希望将“打印格式”转换为“某种格式”,希望能对同一格式有所帮助。

下面是代码练习: #!/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

问题来源:stackoverflow

展开
收起
is大龙 2020-03-23 23:57:40 470 0
1 条回答
写回答
取消 提交回答
  • 我试图以一种非常基本的方式格式化,如下所示:

    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()期间出现“索引不足”问题,因为在极少数情况下,例如仅具有一个接口的键会报告索引错误,而因此,拆分很容易获得变量中的值,并在这些情况下将索引不足抑制为异常。

    回答来源:stackoverflow

    2020-03-23 23:57:46
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
From Python Scikit-Learn to Sc 立即下载
Data Pre-Processing in Python: 立即下载
双剑合璧-Python和大数据计算平台的结合 立即下载