Search code examples
bashawkgrepfile-manipulation

Row manipulation in files, bash


I have a file called SSH which contains two lines of information. It looks like this:

src=192.168.60.111 ttl: 64 last_seen: 4295187854 oldest_pkt: 16 4295157111, 4295168442, 4295172078, 4295172078, 4295172328, 4295172328, 4295172829, 4295172829, 4295173830, 4295173830, 4295175834, 4295175834, 4295179838, 4295179838, 4295187854, 4295187854
src=10.0.98.2 ttl: 64 last_seen: 4295868429 oldest_pkt: 16 4295845135, 4295848540, 4295851694, 4295851694, 4295853197, 4295853197, 4295856201, 4295856201, 4295859226, 4295859226, 4295862420, 4295862420, 4295865425, 4295865425, 4295868429, 4295868429

I want to make a script which controlls weather the last_seen number + number of packets sent * 10 is smaller than current time.
for example: if($currenttime >= 4295187854+16*10) for the first line.
IF current time is bigger, the line should be removed. It is a try to make a delay on the login via SSH and the SSH-file notes every IP that has written wrong password more than 3 times.

I am very new to scripting and tried solve this with awk but did not make any progress. Do you guys have any idea of how I can scan the file line by line, analyze the different fields and depending on answer from the if-statement remove it?

EDIT This is what i produced, this probably doesn't make any sense since i can't understand what's actually going on with awk.

#!/bin/sh
currenttime=$(date +%s)
awk  '{if ($currenttime >= $5+10*$7) print $0 > "temp.txt";}' SSH
cp -f temp.txt SSH
rm temp.txt

Solution

  • Something like this?:

    $ awk 'strftime("%s")<=$5+$7*10' SSH
    

    strftime("%s") returns The time as a decimal timestamp in seconds since the epoch which is compared against the $5+$7*10. If the comparison is true record is printed.

    Edit: Thank you @EdMorton for pointing out that the %s specifier is not supported by all systems (see Gnu awk documentation on the issue) and on those unsupported systems systime() should be used instead (it's shorter so just use it on all systems anyway!):

    awk 'systime()<=$5+$7*10' SSH