使用expect自動化完成叢集SSH信任關係的建立
阿新 • • 發佈:2018-12-17
- 將以下指令碼存成檔案,並修改其許可權
$ chmod 775 establish-ssh.sh
- 在同一目錄下新建servers.txt檔案,並填入相關IP
[email protected]:capra(master)$ cat servers.txt
192.168.121.10
192.168.121.11
192.168.121.12
192.168.121.13
192.168.121.14
192.168.121.15
- 執行establish-ssh.sh檔案
$./establish-ssh.sh
指令碼檔案
#!/bin/bash
# The name who want to ssh without password
USER_UID=linyimin
# The System user home directory
USER_DIR=/home/linyimin
# Password of the other server user
USER_PASSWORD='password'
#################################### main #####################################
if [ -f servers.txt ]
then
:
else
echo
echo "########### Please touch File: servers.txt ##########################"
echo "########### servers.txt For example #################################"
echo "########### 192.168.1.10 ############################################"
exit 1
fi
# if expect is not installed then install it
dpkg --get-selections | grep -q expect
if [ $? -eq 0 ]
then
:
else
echo "########## Please install expect #####################################"
exit 1
fi
# if id_rsa.pub not exist,
if [ -f $USER_DIR/.ssh/id_rsa.pub ]
then
:
else
expect -c "
spawn ssh-keygen
expect \"Enter file in which to save the key*\"
send \"\r\"
expect \"Enter passphrase*\"
send \"\r\"
expect \"Enter same passphraseagain:\"
send \"\r\"
"
fi
for SSH_IP in `cat servers.txt`
do
echo "$SSH_IP"
expect -c "
spawn ssh-copy-id -i $USER_DIR/.ssh/id_rsa.pub $SSH_IP
expect \"*yes/no*\"
send \"yes\r\"
expect \"*password*\"
send \"${USER_PASSWORD}\"
"
if [ $? -eq 0 ]
then
echo "------------- $SSH_IP is ok. -----------------------"
else
echo "------------- $SSH_IP is fail ----------------------"
fi
done
存在問題
在使用的時候發現IP對應的主機不存在的時候,列印的還是------------- $SSH_IP is ok. -----------------------
,
也就是expect命令執行完成之後$?
始終是0