簡體   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