- 脚本源代码
#!/bin/bash
if [ $UID -ne 0 ];then
echo "请使用root用户执行此脚本"
exit
fi
which expect
if [ $? -ne 0 ];then
yum install -y expect
fi
ls .ssh/ | grep id
if [ $? -ne 0 ];then
#创建公钥 -P:密码为空 -f:指定公钥位置(实现无交互创建公钥)
ssh-keygen -P "" -f ~/.ssh/id_rsa
fi
read -p "请输入你远程连接主机的密码:" password
read -p "请输入你想远程连接主机网段:(例:192.168.80)" wd
bj=$(ifconfig ens33|awk -F '[ :]+' 'NR==2 {print $3}')
echo $bj
##判断主机是否在线
for i in {2..254}
do
{
ip=$wd.$i
ping -c1 -W1 $ip &> /dev/null
if [ $? -eq 0 ];then
echo "$ip" >> ip.txt
# if [ $bg -eq $ip ];then
# continue
# fi
#调用expect
/usr/bin/expect <<-EOF
spawn ssh-copy-id $ip
expect {
"*yes/no*" { send "yes\r"; exp_continue }
"*password:" { send "$password\r" }
}
expect eof
EOF
fi
}&
done
- 脚本使用方法
[root@localhost ~]# bash ssh.sh
(这时候肯定有der说:哎,expect的环境变量是/usr/bin/expect,你bash的环境变量是 /bin/bash,不能执行,大哥,看好了,我这写的是shell脚本,中间特意写了expect的环境变量,用于shell调用)
[root@localhost ~]# bash ssh.sh
/usr/bin/expect
id_rsa
id_rsa.pub
请输入你远程连接主机的密码:123456 #输入密码
请输入你想远程连接主机网段:(例:192.168.80)192.168.80 #输入网段
ssh.sh: line 18: ifconfig: command not found
[root@localhost ~]# spawn ssh-copy-id 192.168.80.21
spawn ssh-copy-id 192.168.80.31
spawn ssh-copy-id 192.168.80.254
/usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/root/.ssh/id_rsa.pub"
/usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/root/.ssh/id_rsa.pub"
/usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/root/.ssh/id_rsa.pub"
/usr/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed
/usr/bin/ssh-copy-id: ERROR: ssh: connect to host 192.168.80.254 port 22: Connection refused
expect: spawn id exp6 not open
while executing
"expect eof"
/usr/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed
/usr/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed
/usr/bin/ssh-copy-id: INFO: 1 key(s) remain to be installed -- if you are prompted now it is to install the new keys
root@192.168.80.31's password:
/usr/bin/ssh-copy-id: WARNING: All keys were skipped because they already exist on the remote system.
(if you think this is a mistake, you may want to use -f option)
expect: spawn id exp6 not open
while executing
"expect eof"
Permission denied, please try again.
root@192.168.80.31's password: #这边因为shell脚本把自己也算进去了,所以会连接自己,这边需要手动ctrl +c 打断
[root@localhost ~]# cat ip.txt #存活的ip
192.168.80.21 #本机
192.168.80.31 #另一台主机
192.168.80.254 #网关
[root@localhost ~]# ssh 192.168.80.21
Activate the web console with: systemctl enable --now cockpit.socket
Last login: Sun Jun 6 01:05:14 2021 from 192.168.80.31
[root@z1 ~]# #成功登录