问题
I am working with a new script that reads from a log file and then stores the ips which match one of the two patterns: Either its a failed attempt or its a failed attempt using ssh.
My code runs good, but the problem is that when the while condition finishes, when I want to call the variable which stores all the IPs it only shows the last one.
#!/bin/bash
while IFS=";" read -r p || [ -n "$p" ]
do
first=$(echo $p | sed -E -e "s/[[:blank:]]+/;/g" | cut -d ";" -f 6)
if [[ $first == "Failed" ]];
then
echo "ADVERTENCIA - ATAC DDOS - !"
x="$(echo $p | sed -E -e "s/[[:blank:]]+/;/g" | awk -F ";" '{print $11}') "
elif [[ $first == "pam_unix(sshd:auth):" ]];
then
echo "ADVERTENCIA - LOGUEIG DE SSH - ! !"
y="$(echo $p | sed -E -e "s/[[:blank:]]+/;/g" | awk -F ";" '{print $15}' | cut -b 7-19)"
fi
done < syslog.txt
(IFS=""; sort <<< "$x") | uniq -c
#This comand only prints the last ip, but I want to print the whole IP list.
My syslog text:
Apr 15 00:00:11 spark sshd[7812]: pam_unix(sshd:auth): authentication failure; logname= uid=0 euid=0 tty=ssh ruser= rhost=218.25.208.92 user=root
Apr 15 11:38:58 spark sshd[13924]: Failed password for root from 183.3.202.111 port 22064 ssh2
Apr 15 11:38:58 spark sshd[13924]: Failed password for root from 183.3.202.111 port 22064 ssh2
Apr 15 00:00:11 spark sshd[7812]: pam_unix(sshd:auth): authentication failure; logname= uid=0 euid=0 tty=ssh ruser= rhost=218.25.208.92 user=root
Current output:
1 183.3.202.111
1 218.25.208.92
What it should be really printing:
2 183.3.202.111
2 218.25.208.92
回答1:
Each time you assign a value to x
you're overwriting the previous version:
x="$(echo $p | sed -E -e "s/[[:blank:]]+/;/g" | awk -F ";" '{print $11}') "
Assuming your intention is to append new ip's onto the end of x
, you have a few options, eg:
# use "+=" to append to variable
x+="$(echo $p | sed -E -e "s/[[:blank:]]+/;/g" | awk -F ";" '{print $11}') "
# reference variable in the assignment, eg, x="${x}..."
x="${x}$(echo $p | sed -E -e "s/[[:blank:]]+/;/g" | awk -F ";" '{print $11}') "
来源:https://stackoverflow.com/questions/65174501/storing-values-using-if-inside-while-loop-bash