danrodi
danrodi

Reputation: 296

Echo results from a grep search in shell script

I have a shell script which searches for authentication fails. For example if the given file contains the following row:

Mar 19 15:54:18 precise3 sshd[16516]: Failed password for lotte from 127.0.0.1 port 47384 ssh2

The shell script will find it and write the results in a separate file as:

date: date    username: username    client IP: ip-address

Now I have the script which finds the authentication fails, but how can I write the data from the fail into the file? The script itself is:

#!/bin/bash
if egrep "sshd\[[0-9]+\]: Failed password for \w+ from [0-9.]+ port [0-9]+ ssh2$" /var/log/auth.log
then
    echo "date: date    username: username    client IP: ip-address" > /root/failedauth
else
    echo "No failed authentications found."
fi

Upvotes: 0

Views: 1028

Answers (3)

Josh Jolly
Josh Jolly

Reputation: 11786

Using awk:

awk '/Failed password/ {print "Date: "$1" "$2" "$3"\tUsername: "$9"\t\tClient IP: "$11 }' /var/log/auth.log >> /root/failedauth

The above will simply find all the failed auth attempts and log them in /root/failedauth - if you want an line to be echoed if there are no results, you could do something like:

failures=$(awk '/Failed password/ {print "Date: "$1" "$2" "$3"\tUsername: "$9"\t\tClient IP: "$11 }' /var/log/auth.log)
test -n "$failures" && echo "$failures" >> /root/failedauth || echo "No failed auths found"

Upvotes: 1

tripleee
tripleee

Reputation: 189357

Trivial with Awk.

awk '/sshd\[[0-9]+\]: Failed password for [-A-Za-z0-9_]+ from [0-9.]+ port [0-9]+ ssh2$/ {
    print "date: $1 $2 $3  user: $9  ip: $11" }' /var/log/auth.log >>/root/failedauth

If there are no failed authentications, the script will print nothing. (The date of the failedauth file will still be updated, though.)

Upvotes: 0

user3394487
user3394487

Reputation: 35

First, yout grep can return several results, so your script can't work, or just for the first result.

I think you must save grep's result in a file and process each line of this file.

Upvotes: 0

Related Questions