sshpass 是一个允许用户在非交互式 SSH 会话中自动输入密码的工具,这使得它在自动化脚本和批量处理任务中非常有用,SSH使用直接TTY访问来确保密码确实是由交互式键盘用户发出的。sshpass在专用的TTY中运行SSH,让SSH认为它是从交互式用户那里获取密码的。
下面我们来看下使用方法,使用前我们需要进行安装
apt install -y sshpass
sshpass使用有如下参数
sshpass -h
Usage: sshpass [-f|-d|-p|-e] [-hV] command parameters
-f filename Take password to use from file
-d number Use number as file descriptor for getting password
-p password Provide password as argument (security unwise)
-e Password is passed as env-var "SSHPASS"
With no parameters - password will be taken from stdin
-P prompt Which string should sshpass search for to detect a password prompt
-v Be verbose about what you're doing
-h Show help (this screen)
-V Print version information
At most one of -f, -d, -p or -e should be used
从上面参数中可以看到我们把密码设置为SSHPASS变量以后可以直接使用-e参数来使用
sshpass免交互登录服务器
export SSHPASS='admin123'
sshpass -e ubuntu@${host}
我经常用于面交互设置免密登录的密钥复制,当首次连接到一个 SSH 服务器时,可能会提示你确认服务器的 RSA 指纹。可以使用 -o StrictHostKeyChecking=no 选项来忽略这个警告
sshpass -p "${PASSWORD}" ssh-copy-id -o StrictHostKeyChecking=no -i ~/.ssh/id_rsa.pub ubuntu@${host}
也可以使用sshpass在远程服务器上执行命令或者脚本
sshpass -p "${PASSWORD}" ssh ubuntu@${hosts} 'ls -l /'
sshpass -p "${PASSWORD}" ssh ubuntu@${hosts} 'bash setup.sh'
如果是大段脚本内容可以使用<<定界符来配合使用,例如我在远端服务器上生成密钥
sshpass -p ${HOST_PASSWORD} ssh ubuntu@${hosts} << EOF
ssh-keygen -t rsa -N '' -f ~/.ssh/id_rsa
chmod 700 ~/.ssh
touch ~/.ssh/authorized_keys
chmod 600 ~/.ssh/authorized_keys
cat ~/.ssh/id_rsa.pub >>~/.ssh/authorized_keys
EOF
内容版权声明:除非注明,否则皆为本站原创文章。
转载注明出处:https://sulao.cn/post/1134
评论列表