- 安装expect
yum install -y expect
- 使用的脚本 ssh_batch_conf.sh
#!/bin/bash
if [ $# -ne 2 ]; then
echo "there are no enough arguments!"
echo "Usage: $0 username password"
exit 1
fi
# define account
username=$1
password=$2
# creating key-pair if there is not one
if [ ! -f $HOME/.ssh/id_rsa.pub ] ; then
ssh-keygen -t rsa -P '' -f $HOME/.ssh/id_rsa &>/dev/null
echo "---------- creating id_rsa.pub on local ----------"
echo
fi
# get local ip list
# or using command "hostname -i"
ip_list=`ip a | grep -w inet | awk '{print $2}' | grep -P -o "\d+\.\d+\.\d+\.\d+" | xargs`
echo "---------- local ip: [$ip_list] ----------"
echo
# loading ip files and login
for ip in `cat ./host_ip.txt`; do
if [[ $ip_list =~ $ip ]]; then
continue
fi
echo "---------- copying $username public key to $ip ----------"
/usr/bin/expect <<EOF
# copying public key to target host
spawn ssh-copy-id -i $HOME/.ssh/id_rsa.pub $username@$ip
# input password via expect (automatically)
expect {
"yes/no" { send "yes\n"; exp_continue}
"password" { send "$password\n"}
}
expect eof
EOF
echo
done
echo "---------- finished ----------"
echo
注:ssh-copy-id 命令把公钥写入文件 .ssh/authorized_keys 时是追加 “ >> ”。
- 存放ip的文件 host_ip.txt
192.168.74.201
192.168.74.202
192.168.74.203
192.168.74.204
192.168.74.205
- 通过hostname登陆主机并将公钥添加到本地known_hosts文件。
脚本文件 addpubkey.sh
#!/bin/bash
if [ $# -lt 2 ]; then
echo "Usage: $0 <width of number> <number of hosts>"
echo -e "\033[31mwidth >= 2\033[0m"
exit 1
fi
if [ $1 -lt 2 ]; then
echo "Usage: $0 <width of number>"
echo -e "\033[31mwidth >= 2\033[0m"
exit 1
fi
width=$1
hosts_no=$2
echo "----- adding the node to the list of known hosts -----"
host=`hostname`
for i in $(seq $hosts_no) ; do
str=`printf "node%0${width}d" $i`
if [[ $str = $host ]] ; then
continue
fi
echo "------ adding $str public key to local known_hosts ------"
/usr/bin/expect <<EOF
spawn ssh $str hostname
expect {
"yes/no" { send "yes\n"}
}
expect eof
EOF
echo
done
echo "---------- finished ----------"
echo
- 接下来可以直接ssh登陆设备
ssh 192.168.74.204 #使用当前用户名登陆
或者
ssh bee@192.168.74.204
或者
ssh node03
登陆过程无需输入密码。