互信是指配置免密登录另一台主机,常用于自动化脚本!
以下分享个互信脚本:
DEST_USER=$1PASSWORD=$2HOSTS_FILE=$3if [ $#-ne3 ]; thenecho"Usage:"echo"$0remoteUser remotePassword hostsFile"exit1fiif [ "${DEST_USER}"!="root" ]; thencd/home/"${DEST_USER}"/||returnfiSSH_DIR=~/.sshSCRIPT_PREFIX=./tmpecho===========================#1.preparedirectory .sshmkdir$SSH_DIRchmod700$SSH_DIR#2.generatsshkeyTMP_SCRIPT=$SCRIPT_PREFIX.sh { echo"#!/usr/bin/expect"echo"spawn ssh-keygen -b 1024 -t rsa"echo"expect *key*"echo"send \r" } >>$TMP_SCRIPTif [ -f$SSH_DIR/id_rsa ]; then { echo"expect *verwrite*"echo"send y\r" } >>$TMP_SCRIPTfi { echo"expect *passphrase*"echo"send \r"echo"expect *again:"echo"send \r"echo"interact" } >>$TMP_SCRIPTchmod+x$TMP_SCRIPT/usr/bin/expect$TMP_SCRIPTrm-rf$TMP_SCRIPT#3.generatfileauthorized_keyscat$SSH_DIR/id_rsa.pub>>$SSH_DIR/authorized_keys#4.chmod600forfileauthorized_keyschmod600$SSH_DIR/authorized_keysecho===========================#5.copyallfilestootherhostsforipin$(<"${HOSTS_FILE}"); doif [ "x$ip"!="x" ]; thenecho-------------------------TMP_SCRIPT=${SCRIPT_PREFIX}.$ip.sh#checkknown_hostsval=$(ssh-keygen-F"${ip}") if [ "x$val"=="x" ]; thenecho"$ipnot in $SSH_DIR/known_hosts, need to add"val=$(ssh-keyscan"${ip}"2>/dev/null) if [ "x$val"=="x" ]; thenecho"ssh-keyscan $ipfailed!"elseecho"${val}">>$SSH_DIR/known_hostsfifiecho"copy $SSH_DIRto $ip" { echo"#!/usr/bin/expect"echo"spawn scp -r $SSH_DIR$DEST_USER@$ip:~/"echo"expect *assword*"echo"send $PASSWORD\r"echo"interact" } >"$TMP_SCRIPT"chmod+x"$TMP_SCRIPT"/usr/bin/expect"$TMP_SCRIPT"rm-rf"$TMP_SCRIPT"echo"copy done."fidone#6.datesshforipin$(<"$HOSTS_FILE"); doif [ "x$ip"!="x" ]; then { echo"#!/usr/bin/expect"echo"spawn ssh $DEST_USER@$ipdate"echo"expect *yes*"echo"send yes\r"echo"interact" } >"$TMP_SCRIPT"chmod+x"$TMP_SCRIPT"/usr/bin/expect"$TMP_SCRIPT"rm-rf"$TMP_SCRIPT"echo"copy done."fidone
创建一个脚本 sshtrust.sh
,将以上内容写入脚本!
支持多台主机进行互信,创建一个 sshhostList.cfg
文件,将需要配置互信的主机IP写入:
10.211.55.10010.211.55.10110.211.55.102
执行如下命令互信:
shsshtrust.sh互信用户互信用户密码sshhostList.cfg
执行完成后,即配置互信成功!