sshpass命令详解,sshpass使用
使用sshpass 和 ssh-copy-id批量拷贝公钥到远程主机
操作过程
包含主机的IP、端口、密码
使用sshpass将密码传递给ssh-copy-id , 使得当需要输入密码时, 能够自动读取变量进行输入并完成验证:
脚本cat copy_ssh_id.sh如下:
也可以使用单条命令:
注意:
没有提示要求输入yes 进行确认,是我之前就在ssh_config文件中设置了不进行确认:
或者
CentOS下使用sshpass输入密码时特殊字符的处理
sshpass的密码输入时默认不能使用特殊字符。当遇到有特殊字符的ssh密码时, 需要对密码做特殊处理:加单引号:例如:密码为:12365@3$#@!
使用sshpass命令时这样使用即可避免,在密码前后加上单引号:'12365@3$#@!'
命令行如下:sshpass -p '12365@3$#@!' ssh root@10.0.1.45 即可解决!
如何自动输入密码ssh连接到其他机器
主要的解决方法有三种:
1. 生成ssh公钥,建立和对方机器的信任关系;
2. 使用expect脚本;
3. 使用sshpass。
这里介绍一下sshpass相关内容
下载并安装sshpass):
# tar zxvf sshpass-xxxx.tar.gz
# cd sshpass-xxxx
# ./configure
# make make install
基本用法:sshpass -p [密码] ssh [user]@[host]
免去第一次登录机器时的确认提示(Are you sure you want to continue connecting (yes/no)):
sshpass -p [密码] ssh [user]@[host] -o StrictHostKeyChecking=no
后面也可以跟上其他ssh命令,如scp等
例1,公司的一个环境,大部分机器的login密码是"1root",少部分是"123qwe",新建一个hssh.sh文件,按如下修改,copy到/usr/bin/目录下。
[cpp] view plain copy
#!/bin/sh
#_main_
temp_file=/tmp/hssh.1
ip=192.168.$1
case "$1" in
"204.188"|"207.31"|"205.199") password="123qwe";;
*) password="1root"
esac
sshpass -p $password ssh root@$ip -o StrictHostKeyChecking=no 2$temp_file
if [ $? != 0 ];then
#for some reason,machine had reinstall, we need to delete that IP address in known_hosts file before ssh it.
grep -q "REMOTE HOST IDENTIFICATION HAS CHANGED" $temp_file
if [ $? = 0 ];then
key_file=`grep "Offending key in" $temp_file | cut -d' ' -f 4 | cut -d ':' -f1 2/dev/null`
cat $key_file | grep -v "$ip" $temp_file
sudo cp -v $temp_file $key_file
sshpass -p $password ssh root@$ip -o StrictHostKeyChecking=no 2$temp_file
fi
fi
那么我们每次只要输入hssh XXX.XXX 等就可以ssh到对应机器上了
