使用Python解析Linux命令

时间:2018-07-04 12:04:55

标签: python linux

以下是我使用pexpect的代码的简短摘要:

child.expect('tc@')
child.sendline('ps -o args | grep lp_ | grep -v grep | sort -n')
child.expect('tc@')
print(child.before)
child.sendline('exit')

,然后输出:

user@myhost:~/Python$ python tctest.py 
tc-hostname:~$ ps -o args | grep lp_ | grep -v grep | sort -n
/usr/local/bin/lp_server -n 5964 -d /dev/usb/lp1
/usr/local/bin/lp_server -n 5965 -d /dev/usb/lp0
{lp_supervisor} /bin/sh /usr/local/lp/lp_supervisor /dev/usb/lp0 SERIAL#1 /var/run/lp/lp_pid/usb_lp0
{lp_supervisor} /bin/sh /usr/local/lp/lp_supervisor /dev/usb/lp1 SERIAL#2 /var/run/lp/lp_pid/usb_lp1

user@myhost:~$

有4行输出。前两行显示USB设备已分配给打印机端口(例如:第一行显示5964端口已分配给lp1)

第三行和第四行显示将哪个设备序列号分配给哪个USB端口。 (例如:SERIAL#1已分配给lp0)

我需要以某种方式解析该输出,以便执行以下操作:

If SERIAL#1 is not assigned to 5964:
    run some command
else:
    do something else
If SERIAL#2 is not assigned to 5965:
    run some command
else:
    do something else

我不确定如何操作该输出,以便获取所需的变量。任何帮助表示赞赏。

2 个答案:

答案 0 :(得分:0)

您可以使用re.findall从pexpect数据中提取端口和串行信息,并执行类似的操作

import re
data = child.before
ports = re.findall(r'lp_server -n (\d+)', data)
# ['5964', '5965']
serials = re.findall(r'(SERIAL#\d+)', data)
# ['SERIAL#1', 'SERIAL#2']

list(zip(ports, serials))
# [('5964', 'SERIAL#1'), ('5965', 'SERIAL#2')]

for serial, port in zip(ports, serials):
    # Check if serial and port matches expectation

答案 1 :(得分:0)

另一种实现方法是使用字典在设备序列号和打印机端口之间建立关系:

inString = """/usr/local/bin/lp_server -n 5964 -d /dev/usb/lp1
/usr/local/bin/lp_server -n 5965 -d /dev/usb/lp0
{lp_supervisor} /bin/sh /usr/local/lp/lp_supervisor /dev/usb/lp0 SERIAL#1 /var/run/lp/lp_pid/usb_lp0
{lp_supervisor} /bin/sh /usr/local/lp/lp_supervisor /dev/usb/lp1 SERIAL#2 /var/run/lp/lp_pid/usb_lp1"""

inString = inString.split("\n")

matches = dict()
serials = dict()

for i in range(len(inString[:2])):
    lp = inString[i][-3:]
    printerPort = int(inString[i].split("-n ")[1][:4])
    matches.update({lp:printerPort})

for i in range(2,len(inString)):
    t = inString[i].split(" ")
    lp = t[3][-3:]
    serial = t[4]
    serials.update({serial:lp})

finalLookup = dict((k,matches[v]) for k,v in serials.items())
print(finalLookup)

输出:

{'SERIAL#1': 5965, 'SERIAL#2': 5964}

那么您可以做:

if not finalLookup['SERIAL#1'] == 5964:
    run some command
else:
    do something else
if not finalLookup['SERIAL#2'] == 5965:
    run some command
else:
    do something else