Link to home
Start Free TrialLog in
Avatar of LAME-ER
LAME-ER

asked on

Check shell login by ip

I need to make a small bash script that checks shell logins from the last N days and tells me if a certain IP address has been connected to my machine in that period of time.

The script would have 2 arguments:
- argument1 - the past number of days you want to check. That means look at today's date minus argument1 days.

- argument2 - the IP address that may or may not have connected to the shell in that period of time.

E.g: check.sh 5 192.168.1.5 would tell me if 192.168.1.5 has been connected to the shell in the last 5 days
Avatar of MikeOM_DBA
MikeOM_DBA
Flag of United States of America image

You can find that information using the 'last' command (man last).
 
 
 
 
Hi there

exactly you have the last command, just do

last |grep 192.168.x.y or any IP as the output might scroll down a few pages
Avatar of woolmilkporc
Note -
last alone will display hostnames, where possible.

To search for IP numbers only, as you requested, you should use the -i flag of last,
so it displays the IP number in numbers-and-dots notation instead of the hostname.
last -i | grep [IP]
 wmp
Now for the "last N days" stuff - check this:
#!/bin/bash
last -i | grep $2 | while read line
  do
    let days=$(echo $line | date -d "$(awk '{print $5, $6}')" +"%s")/86400
    let start=$(date +"%s")/86400-\(${1}+1\)
    [ $days -ge $start ] && echo "$line"
  done
exit
Remarks -
1) the script expects month and day in columns 5 and 6, respectively. In some systems it's columns 4 and 5. Please adjust, if necessary.
2) some systems do not support the -i flag. In this case, you'll have to take it away and search for hostnames, unfortunately.
3) you need GNU date
4) I had not much time to make it really "elegant" - sorry for that.
Have fun
wmp
... OK, take the "let start=" line out of the loop (put it just after the "#!/bin/bash" line). It's nonsense to have that statement inside the loop.
A corrected version to handle the year shift in a (nearly) consistent manner. There is probably a blur with leap years, however.
#!/bin/bash
let today=$(date +"%s")/86400
let start=$today-\(${1}+1\)
last -i | grep $2 | while read line
 do
  let days=$(echo $line | date -d "$(awk '{print $5, $6}')" +"%s")/86400
  [ $days -gt $today ] && let days=days-365
 [ $days -ge $start ] && echo "$line"
 done
exit
@woolmilkporc:
Unfortunately your script ignores sessions later than 'N' days which are still login.
 
 
ASKER CERTIFIED SOLUTION
Avatar of woolmilkporc
woolmilkporc
Flag of Germany image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of LAME-ER
LAME-ER

ASKER

Thank you for your solution and sorry about the delay! This really helped me a lot! Much appreciate!