繁体   English   中英

Python:如何使用编译和拆分来解析 linux 命令的输出

[英]Python: how to parse the output of a linux command using compile and split

我需要使用 re.compile 和 split 编写一个脚本以接收 cmd 并打印出 ip 地址(最后一个列)以及日期和时间并将其转换为纪元时间。 我只是使用 re.compile 但有人提到我使用 split 命令使它更容易..只是在寻找一些指导? 这就是输出的样子

host:~ # last -a -F | egrep -v "boot|wtmp|tty"
root     pts/2        Fri Jun 19 10:32:13 2015   still logged in                       xx.x.xx.xx
root     pts/0        Fri Jun 19 08:22:29 2015   still logged in                       xx.xx.xx.xx
root     pts/5        Thu Jun 18 10:09:30 2015 - Thu Jun 18 17:20:52 2015  (07:11)     xx.xx.xx.xx
root     pts/4        Thu Jun 18 09:53:33 2015 - Thu Jun 18 17:04:53 2015  (07:11)     xx.xx.xx.xx
    last_re = re.compile(r'(?P<user>\S+)\s+(?P<pts>\/.+)\s(?P<day>\S+)\s+(?P<month>)\s+(?P<date>\d+)\s+(?P<stime>(\d\:\d)\s+(?P<hyphen>(\s|-)\s+(?P<endtime>(\d\:\d)\s+(?P<user>)\s+(?P<duration>(\(\d\:\d\))\s+(?P<ipaddress>(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$)')
    cmd = 'last -a -F | egrep -v "boot|wtmp|tty"'

    try:
            status, output = commands.getstatusoutput(cmd)
            print last_re;
            if not status:
                    output_lines = output.split('\n')
                    m = last_re.search(output_lines[1])
                    if m:
                            print "<day='%s' month='%s' time='%s' external_ip='%s'/>" % (m.group('day'), m.group('month'), m.group('stime'), m.group('ipaddress'))

尝试这个。 不需要蟒蛇。

last -a -F | egrep -v "boot|wtmp|tty" | awk '/[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}/{print $0}'

split()的间距可能有点困难,所以这里有一个使用正则表达式的例子。 它在后面寻找一个 '-' 后跟空格,在此之后捕获所有非贪婪的内容,直到并包括四位数字(年份),跳过所有内容直到一个 ')' 然后更多的空格,直到它遇到前两个八位字节由“.”分隔的 IP,在行尾之前与 IP 的其余部分一起捕获。

import re
import time

str = "root     pts/4        Thu Jun 18 09:53:33 2015 - Thu Jun 18 17:04:53 2015  (07:11)     192.168.0.10"

rx = re.compile(r'(?<=-)\s+(.*?\d{4}).*?(?<=\))\s+(\d{1,3}\.\d{1,3}.*)$')

date, ip = rx.search(str).group(1,2)
epoch = int(time.mktime(time.strptime(date.strip(), "%a %b %d %H:%M:%S %Y")))

print(ip, epoch)

输出:

192.168.0.10 1434668693

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM