尝试运行使用“sshpass”的脚本时权限被拒绝

Lud*_*vig 2 ssh permissions command-line bash

这个想法是让这个脚本运行而不需要输入主机的任何密码(写在Hosts.txt文件中)。现在,当我运行这个时,我得到一个Permission denied, please try again.答案。

#!/bin/bash

[[ -z "${1}" ]] && OUT_FILE="WhereTheAnswearIsGoing.txt" || OUT_FILE="$1"
[[ -z "${2}" ]] && IN_FILE="Hosts.txt" || IN_FILE="$2"

while IFS= read -r host; do
        indication="$(sshpass -pfootbar ssh -p 2222 -o StrictHostKeyChecking=no -n "$host" 'who -b' | awk '{print $(NF-1)" "$NF}')"
        printf '%-14s %s\n' "$indication" "$host" >> "$OUT_FILE"
done < "$IN_FILE"
Run Code Online (Sandbox Code Playgroud)

对不起,如果这个问题不清楚,但我对这些事情了解不多。

pa4*_*080 9

看起来该消息Permission denied, please try again.是由 SSH 客户端生成的。密码应被引用逃脱字符的特殊含义$!等(参考):

sshpass -p 'footbar' ...
Run Code Online (Sandbox Code Playgroud)

或者您可以使用要存储密码的文件():

sshpass -f "/path/to/passwordfile" ...
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明


但是,我记得,这是我之前的回答中提到的一个脚本:“注意这里假设存在不需要的~/.ssh/config文件和其他参数-p 2222参考)。” 我的意思是:

更好的解决方案是 (1) 设置基于密钥的 SSH 身份验证,(2) 创建~/.ssh/config文件和 (3) 修改脚本以使用此设置。

1.设置基于密钥的 SSH 身份验证(来源)。

2.创建~/.ssh/config文件。(另阅读:如何将多台具有相同配置的机器添加到 ~/.ssh/config?

3.A. 你可以继续使用上面的脚本,稍作修改:

#!/bin/bash

[[ -z "${1}" ]] && OUT_FILE="WhereTheAnswearIsGoing.txt" || OUT_FILE="$1"
[[ -z "${2}" ]] && IN_FILE="Hosts.txt" || IN_FILE="$2"

while IFS= read -r host; do
        indication="$(ssh -n "$host" 'who -b' | awk '{print $(NF-1)" "$NF}')"
        printf '%-14s %s\n' "$indication" "$host" >> "$OUT_FILE"
done < "$IN_FILE"
Run Code Online (Sandbox Code Playgroud)

在这种情况下,Hosts.txt文件应该是:

host-1
host-2
host-3
Run Code Online (Sandbox Code Playgroud)

3.B. 或者您可以以更通用的方式修改脚本:

#!/bin/bash

# Collect the user's input, and if it`s empty set the default values
[[ -z "${1}" ]] && OUT_FILE="WhereTheAnswearIsGoing.txt" || OUT_FILE="$1"
# Provide the list of the hosts as an array
HOSTS=("host-1" "host-2" "host-3")

for host in "${HOSTS[@]}"; do
    indication="$(ssh -n "$host" 'who -b' | awk '{print $(NF-1)" "$NF}')"
    printf '%-14s %s\n' "$host" "$indication" >> "$OUT_FILE"
done
Run Code Online (Sandbox Code Playgroud)