尝试让 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

相关内容