0

Normally I can detect user's last logon time if last return anything via below function. My question is : if last doesn't return anything then I want to look in the user's home directory date and time for the most recently modified file.

lastlogLatest() {
    last -n 1 "${userName}"  | awk ' {
    for( i=1;i<=NF;i++ ) {
        if ( $i ~ /Mon|Tue|Wed|Thu|Fri|Sat|Sun/ ) {
            j = 0
            str = ""
            for ( j=i; j<=NF;j++ ) {
                str = ( str ? (str FS $j):$j )
            }
            print str
            break
        }
    }
}'
}

1 Answer 1

1

The following modification of your script appears to work:

lastlogLatest() {
    last -n 1 "${userName}"  | awk ' $1 != "wtmp" {
    for( i=1;i<=NF;i++ ) {
        if ( $i ~ /Mon|Tue|Wed|Thu|Fri|Sat|Sun/ ) {
            j = 0
            str = ""
            for ( j=i; j<=NF;j++ ) {
                str = ( str ? (str FS $j):$j )
            }
            print str
            break
        }
    }
}'
}
userName=somebody
lastlogin=$(lastlogLatest)
if [[ -z "$lastlogin" ]]; then
    echo "${userName} not found in lastlog"
   if cd /home/${userName} 2> /dev/null; then
      date -d "@$(find . -type f -printf '%T@\n' 2> /dev/null | sort -n | head -n1)"
   else
      echo "No home directory found for ${userName}" 1>$2
   fi
else
    echo "$lastlogin"
fi

I added a small tweak to the awk script that strips out the line telling us when the wtmp log begins, so that it doesn't pull that date out and assume it's for the specified user.

Also, note that this requires whichever user executing it to have permission to inspect the specified user's home directory and the files therein.

4
  • First of all , thank you so much. But I have a question too. I have uploaded my script to hastebin.com/siqefusixi.bash Now I have plugged (line 105) your function into the my bash script. Am I correct ? So I am using lastlogin variable as output printf command.
    – Cell-o
    Commented Mar 20, 2018 at 19:06
  • Well, what I do is I run the funciton and capture its output into the lastlogin variable. If it's empty, that means nothing was found in the lastlog. You could change function to reassign lastlogin rather than handling the output itself as written. lastlogin will only have content if you do not end up having to look at file modification timestamps.
    – DopeGhoti
    Commented Mar 20, 2018 at 19:22
  • OK. BTW, Have you had a chance look my above uploaded bash script ? So Am I correct?
    – Cell-o
    Commented Mar 20, 2018 at 19:28
  • Since your original code would simply print the date, my answer is a drop-in replacement which will in summation print the date, yes.
    – DopeGhoti
    Commented Mar 20, 2018 at 20:09

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .