批量建立linux机器之间的ssh互信的自动化脚本

手工建立ssh互信需要好几个步骤,并且中途人工交互(输入密码等),如果机器数目多,则很繁琐,为了节省自己的时间,写了个自动化脚本,供参考。

1、在其中一台机器上新建一个可执行的文件(假设文件名为ssh_auth.sh),在该文件中添加以下内容:


#!/bin/sh
DEST_USER=$1
PASSWORD=$2
HOSTS_FILE=$3
if [ $# -ne 3 ]; then
    echo "Usage:"
    echo "$0 remoteUser remotePassword hostsFile"
    exit 1
fi

SSH_DIR=~/.ssh
SCRIPT_PREFIX=./tmp
echo ===========================
# 1. prepare  directory .ssh
mkdir $SSH_DIR
chmod 700 $SSH_DIR

# 2. generat ssh key
TMP_SCRIPT=$SCRIPT_PREFIX.sh
echo  "#!/usr/bin/expect">$TMP_SCRIPT
echo  "spawn ssh-keygen -b 1024 -t rsa">>$TMP_SCRIPT
echo  "expect *key*">>$TMP_SCRIPT
echo  "send \r">>$TMP_SCRIPT
if [ -f $SSH_DIR/id_rsa ]; then
    echo  "expect *verwrite*">>$TMP_SCRIPT
    echo  "send y\r">>$TMP_SCRIPT
fi
echo  "expect *passphrase*">>$TMP_SCRIPT
echo  "send \r">>$TMP_SCRIPT
echo  "expect *again:">>$TMP_SCRIPT
echo  "send \r">>$TMP_SCRIPT
echo  "interact">>$TMP_SCRIPT

chmod +x $TMP_SCRIPT

/usr/bin/expect $TMP_SCRIPT
rm $TMP_SCRIPT

# 3. generat file authorized_keys
cat $SSH_DIR/id_rsa.pub>>$SSH_DIR/authorized_keys

# 4. chmod 600 for file authorized_keys
chmod 600 $SSH_DIR/authorized_keys
echo ===========================
# 5. copy all files to other hosts
for ip in $(cat $HOSTS_FILE)  
do
    if [ "x$ip" != "x" ]; then
        echo -------------------------
        TMP_SCRIPT=${SCRIPT_PREFIX}.$ip.sh
        # check known_hosts
        val=`ssh-keygen -F $ip`
        if [ "x$val" == "x" ]; then
            echo "$ip not in $SSH_DIR/known_hosts, need to add"
            val=`ssh-keyscan $ip 2>/dev/null`
            if [ "x$val" == "x" ]; then
                echo "ssh-keyscan $ip failed!"
            else
                echo $val>>$SSH_DIR/known_hosts
            fi
        fi
        echo "copy $SSH_DIR to $ip"
                
        echo  "#!/usr/bin/expect">$TMP_SCRIPT
        echo  "spawn scp -r  $SSH_DIR $DEST_USER@$ip:~/">>$TMP_SCRIPT
        echo  "expect *assword*">>$TMP_SCRIPT
        echo  "send $PASSWORD\r">>$TMP_SCRIPT
        echo  "interact">>$TMP_SCRIPT
        
        chmod +x $TMP_SCRIPT
        #echo "/usr/bin/expect $TMP_SCRIPT" >$TMP_SCRIPT.do
        #sh $TMP_SCRIPT.do&
    
        /usr/bin/expect $TMP_SCRIPT
        rm $TMP_SCRIPT
        echo "copy done."                
    fi
done

echo done.

2、在该可执行文件的同目录下新建名为host的文件,将要建立ssh互信的机器名或ip地址添加到该文件中,每个机器名或ip占一行,如:

192.168.1.2
192.168.1.3
192.168.1.4
192.168.1.5


3、运行可执行脚本ssh_auth.sh文件,ssh_auth.sh接受三个参数,远程机器用户名、密码和host文件名(相对路径或绝对路径均可)。


阅读更多
个人分类: linux
上一篇搭建WEB服务器集群(apache+tk+tomcat)
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭
关闭