expect批量免密登录🐝🐝🐝
expect批量免密登录🐝🐝🐾
一、准备工作
安装expect
[root@localhost ~]# yum -y install expect
生成密钥对
[root@localhost ~]# ssh-keygen -t rsa -P '' -f ~/.ssh/id_rsa
二、批量推送密钥
编写shell脚本
[root@localhost ~]# vim sshpush.sh
#!/usr/bin/bash
# 1. 自动安装 expect (若不存在)
if ! command -v expect >/dev/null 2>&1; then
echo "正在安装依赖 expect..."
yum install -y expect 2>/dev/null || { echo "安装失败,请手动安装 expect"; exit 1; }
fi
# 2. 生成SSH密钥对(若不存在)
if [ ! -f "$HOME/.ssh/id_rsa" ]; then
ssh-keygen -t rsa -N "" -f "$HOME/.ssh/id_rsa"
fi
# 3. 推送公钥
user="root"
passwd='123456'
hosts='192.168.66.189 192.168.66.161 192.168.66.244'
for host in $hosts (或者提前生成ip列表文件;for host in `cat iplist.txt`)
do
echo "===============$host================"
expect <<EOF
set timeout 10
spawn ssh-copy-id -f "$user@$host"
expect {
"yes/no" { send "yes\n"; exp_continue}
"password:" { send "$passwd\n"}
}
expect eof;
EOF
done
执行shell脚本
[root@localhost ~]# shellcheck sshpush.sh (可以先检查shell语法,yum -y install shellcheck)
[root@localhost ~]# sh sshpush.sh
输出:
[root@localhost ~]# sh sshpush.sh
===============192.168.66.189================
spawn ssh-copy-id -f root@192.168.66.189
/usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/root/.ssh/id_rsa.pub"
root@192.168.66.189's password:
Number of key(s) added: 1
Now try logging into the machine, with: "ssh 'root@192.168.66.189'"
and check to make sure that only the key(s) you wanted were added.
===============192.168.66.161================
spawn ssh-copy-id -f root@192.168.66.161
/usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/root/.ssh/id_rsa.pub"
root@192.168.66.161's password:
Number of key(s) added: 1
Now try logging into the machine, with: "ssh 'root@192.168.66.161'"
and check to make sure that only the key(s) you wanted were added.
===============192.168.66.244================
spawn ssh-copy-id -f root@192.168.66.244
/usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/root/.ssh/id_rsa.pub"
root@192.168.66.244's password:
Number of key(s) added: 1
Now try logging into the machine, with: "ssh 'root@192.168.66.244'"
and check to make sure that only the key(s) you wanted were added.
三、验证
[root@localhost ~]# ssh 192.168.66.244
Activate the web console with: systemctl enable --now cockpit.socket
Last login: Wed Apr 2 15:05:35 2025 from 192.168.66.189
[root@localhost ~]# exit
logout
Connection to 192.168.66.244 closed.

浙公网安备 33010602011771号