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

我们的想法是让这个脚本运行而无需键入主机的任何密码(写在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" 

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

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

 sshpass -p 'footbar' ... 

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

 sshpass -f "/path/to/passwordfile" ... 

在此处输入图像描述


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

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

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

  • 生成RSA密钥但不输入密码

     mkdir ~/.ssh chmod 700 ~/.ssh ssh-keygen -t rsa -b 4096 chmod 600 ~/.ssh/id_rsa 
  • 将客户密钥转移到每个主机(请注意引号):

     ssh-copy-id "@ -p " 
  • 现在您应该能够在没有密码的情况下连接到服务器:

     ssh @ -p  
  • 一旦这样做,您可以通过以这种方式编辑每台主机的文件/etc/ssh/sshd_config来禁用密码validation(这是一种不太安全的方法):

     #PasswordAuthentication yes PasswordAuthentication no 

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

  • 文件~/.ssh/config的内容看起来像这样( host-i是你选择的对象):

     Host host-1 HostName  IdentityFile ~/.ssh/id_rsa User  Port 2222 # other parameters... Host host-2 HostName  IdentityFile ~/.ssh/id_rsa User  Port 2222 # other parameters... Host host-3... 
  • 更改文件权限:

     chmod 600 ~/.ssh/config 
  • 现在,您应该能够通过以下命令连接到每个主机:

     ssh host-1 

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" 

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

 host-1 host-2 host-3 

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