Python:如何使用compile和split

时间:2015-06-22 09:52:47

标签: python

我需要使用re.compile编写脚本并拆分以接收cmd并打印出ip地址(last col)和日期和时间并将其转换为纪元时间。 我只是使用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'))

2 个答案:

答案 0 :(得分:0)

试试这个。不需要python。

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}'

答案 1 :(得分:0)

split()对于间距可能有点困难,所以这里是正则表达式的一个例子。它看起来落后于&#39; - &#39;接下来是空白,捕获所有非贪婪的东西,直到并包括四位数(年),跳过一切,直到&#39;)&#39;然后是更多的空格,直到它达到由&#39;分隔的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