inside while循环bash存储值

xlpyo6sf  于 2021-05-16  发布在  Spark
关注(0)|答案(1)|浏览(897)

我正在使用一个新脚本,该脚本从日志文件中读取内容,然后存储匹配两种模式之一的ip:要么尝试失败,要么尝试使用ssh失败。
我的代码运行良好,但问题是当while条件完成时,当我想调用存储所有ip的变量时,它只显示最后一个ip。


# !/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.

我的系统日志文本:

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

电流输出:

1 183.3.202.111
1 218.25.208.92

它真正应该打印的内容:

2 183.3.202.111
2 218.25.208.92
tv6aics1

tv6aics11#

每次为“x”赋值时,都会覆盖以前的版本:

x="$(echo $p | sed -E -e "s/[[:blank:]]+/;/g" | awk -F ";" '{print $11}') "

假设您的意图是在“x”的末尾附加新的ip,那么您有几个选项,例如:


# 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}') "

相关问题