公司有个需求,好多台服务器需要通过一个跳板机免密码登录,如果一个个复制那就坑爹了,于是想到了利用脚本批量处理吧
单独复制
ssh-copy-id -i ~/.ssh/id_rsa -p 22 root@192.168.1.1
准备
利用sshpass
这个软件可以实现,首先安装软件
yum -y install sshpass
apt-get -y install sshpass
如果找不到,update一下源即可
操作
修改ssh_config
配置文件,让id_rsa.pub
秘钥复制不提示
vim /etc/ssh/ssh_config
在末尾添加
StrictHostKeyChecking no
或者执行脚本进行替换操作
sed -i '/StrictHostKeyChecking/s/^#//; /StrictHostKeyChecking/s/ask/no/' /etc/ssh/ssh_config
然后准备两个文件
- 主机账号密码文件
hosts.txt
- 执行脚本
run.sh
主机账号密码格式如下hosts.txt
:
192.168.1.10:22:passwd123456
192.168.1.20:22:passwd123456
执行脚本 run.sh
内容:
for host in $(cat hosts.txt)
do
ip=$(echo ${host} | cut -f1 -d ":")
port=$(echo ${host} | cut -f2 -d ":")
password=$(echo ${host} | cut -f3 -d ":")
arg=$(echo -p ${port} root@${ip})
echo sshpass -p ${password} ssh-copy-id ${arg}
sshpass -p ${password} ssh-copy-id ${arg}
done
之后运行
bash run.sh
即可批量完成公钥复制了
报错
确认公钥
如果出现如下提示,
/usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/root/.ssh/id_rsa.pub"
说明确认公钥,只需要执行如下命令即可
sed -i '/StrictHostKeyChecking/s/^#//; /StrictHostKeyChecking/s/ask/no/' /etc/ssh/ssh_config
因为ssh-copy-id使用非默认端口时,需要加双引号,没有找到地的办法,取了个巧,先将整个命令放至一个临时文件。再执行该临时文件,执行之后,再删除。
for host in $(cat remote-hosts)
do
ip=$(echo ${host} | cut -f1 -d ":")
port=$(echo ${host} | cut -f2 -d ":")
password=$(echo ${host} | cut -f3 -d ":")
arg=$(echo -p ${port} -o StrickHostKeyChecking=no root@${ip})
echo sshpass -p ${password} ssh-copy-id '"'${arg}'"' >> tmp.sh
done
sh tmm.sh
rm -f tmp.sh
报错二
gitlab@0e1348820704:~$ bash run.sh
sshpass -p Happybird360#api ssh-copy-id -p 22 root@192.168.1.10
Usage: /usr/bin/ssh-copy-id [-h|-?|-f|-n] [-i [identity_file]] [-p port] [[-o <ssh -o options>] ...] [user@]hostname
-f: force mode -- copy keys without trying to check if they are already installed
-n: dry run -- no keys are actually copied
-h|-?: print this help
sshpass -p Happybird360#message ssh-copy-id -p 22 root@192.168.1.20
Usage: /usr/bin/ssh-copy-id [-h|-?|-f|-n] [-i [identity_file]] [-p port] [[-o <ssh -o options>] ...] [user@]hostname
-f: force mode -- copy keys without trying to check if they are already installed
-n: dry run -- no keys are actually copied
-h|-?: print this help
执行上面的脚本报错了,后来我去掉了一个 -p
的端口的参数,就没有问题了,也不知道什么原因,可能是有两个-p
产生了冲突
执行脚本 run.sh
内容:
for host in $(cat remote-hosts)
do
ip=$(echo ${host} | cut -f1 -d ":")
port=$(echo ${host} | cut -f2 -d ":")
password=$(echo ${host} | cut -f3 -d ":")
arg=$(echo root@${ip})
echo sshpass -p ${password} ssh-copy-id "${arg}"
sshpass -p ${password} ssh-copy-id "${arg}"
done
更新
原来是 ssh-copy-id
的缘故,因为ssh-copy-id
如果指定端口的情况下,因为后面加上引号,导致ssh-copy-id
复制出错。
删除引号即可
也就是把"${arg}"
变成${arg}
即可正常了
参看:
https://blog.csdn.net/qq43748322/article/details/82771847
https://www.cnblogs.com/panchong/p/6027138.html