試著讓 printf 語句在 bash for 迴圈中執行一次

試著讓 printf 語句在 bash for 迴圈中執行一次

我想知道我將如何做

printf "Credentials found!"

當找到多個憑證時僅一次。

螢幕截圖

Attempting Dictionary Attack on 192.168.91.130

Credentials Found!

Log into the telnet server by running telnet -l admin 192.168.91.130

When prompted enter the password found 'admin'

Credentials Found!

Log into the telnet server by running telnet -l sfx 192.168.91.130

When prompted enter the password found 'toor'

循環bash

for i in "${!user[@]}"; do
    printf "The Username & Password is %s : %s\n\n" "${user[i]}" "${pass[i]}" >> SSH-Credentials.txt

    printf "${NCB}Credentials Found!${NC}\n\n"

    printf "Log into the SSH server by running ${YELLOW}ssh ${user[i]}@$ip${NC}\n\nWhen prompted enter the password found ${YELLOW}'${pass[i]}'\n"
    printf "${NC}\n"
done

答案1

$i您可以進行以下測試:

    [[ "$i" -lt 1 ]] && printf "I am only printed once\n"

    # OR
    (( i < 1 )) && printf "I am only printed once\n"

    # OR
    ! (( i )) && printf "I am only printed once\n"

    # OR
    [ "$i" -lt 1 ] && printf "I am only printed once\n"

    # OR
    if [[ "$i" -lt 1 ]]; then
        printf "I am only printed once\n"
    fi

假設你不使用關聯 bash 數組

簡而言之:如果索引小於 1,則列印。


為了方便閱讀,我也會分解這些行。路寬。請注意,您也可以說:

printf '%s %s some long text' \
"$var1" "$var2"

使用大寫字母表示變數也是一個壞習慣。

資訊通常也應列印在stderr, 所以>&2

還會使用:

prinf '%s@%s' "${user[i]}" "$ip" >&2

代替:

prinf "${user[i]}@$ip" >&2

答案2

user如果數組中有元素,則輸出標頭。

if [[ ${#user[@]} -gt 0 ]]; then
    printf '%sCredentials Found!%s\n\n' "$NCB" "$NC"
fi

然後做你的循環。

for i in "${!user[@]}"; do
    printf 'The Username & Password is %s : %s\n\n' "${user[i]}" "${pass[i]}" >> SSH-Credentials.txt

    cat <<END_MESSAGE
Log into the SSH server using ${YELLOW}ssh ${user[i]}@$ip$NC
When prompted, enter the password found: ${YELLOW}${pass[i]}$NC

END_MESSAGE
done

相關內容