I need to write a script using re.compile and split to take in the cmd and print out the ip address(last col) and the date and time and convert it to epoch time. I was using just re.compile but was mentioned to me to use the split command to make it easier.. just looking for some guidance? this is what the output looks like
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'))
Try this. No need of 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}'
split()
might be a bit difficult with the spacing, so here's an example with regex. It looks behind for a '-' followed by whitespace, captures everything non-greedy after that up to and including four digits (year), skips everything up to a ')' and then more whitespace until it hits what is the first two octets of an IP separated by a '.', which is captured along with the rest of the IP before the end of line.
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)
Output:
192.168.0.10 1434668693
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.