簡體   English   中英

在 while 循環中使用 if 存儲值 BASH

[英]Storing values using if inside while loop BASH

我正在使用一個新腳本,該腳本從日志文件中讀取,然后存儲與以下兩種模式之一匹配的 ip:要么是失敗的嘗試,要么是使用 ssh 的失敗嘗試。

我的代碼運行良好,但問題是當 while 條件結束時,當我想調用存儲所有 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

當前output:

1 183.3.202.111
1 218.25.208.92

它應該真正打印什么:

2 183.3.202.111
2 218.25.208.92

每次為x賦值時,都會覆蓋以前的版本:

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

假設您的意圖是將 append 新 ip 放到x的末尾,您有幾個選擇,例如:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM