2000人QQ群 : 67842417
Join us if you will.

linux 脚本中变量与expect变量传递问题

需求

新的环境增加一台专门的备份服务器,然后通过ssh-key密钥生产的机器通信,将数据拷贝到本地.

由于机器太多想通过脚本批量实现,我通过kickstart[在初始化的时候已经与所有机器完成了密钥登录],执行脚本,完成所有服务器和备份服务器之间的免密钥登录.

脚本如下:

#!/bin/bash
#
########################################################
#author: sptty
#  mail: 747824617@qq.com
#date Fri Dec 25 14:57:49 CST 2015
#automic add bachup server ssh-key to all servers 
########################################################


if [ `id -nu` != 'root' ];then
	echo -e "\033[31mYou do not have permission to excute $0 \033[0m"
	exit 9
fi


#define variables BACKUP_SERVER_IP=172.19.1.201      #新增备份服务器地址
TMP_PATH=/tmp
PUBLIC_KEY_PATH=/root/.ssh
PUBLIC_KEY_NAME=id_dsa.pub    

while read LINE;do   #通过while循环完成和所有的生产服务器的IP的设定

	#copy client ssh-key to backup sever and test !
	
	/usr/bin/expect << EOF
	set LINE_E [ exec ${LINE} ]
	set PUBLIC_KEY_PATH_E [ exec echo ${PUBLIC_KEY_PATH} ]
	set PUBLIC_KEY_NAME_E [ exec echo ${PUBLIC_KEY_NAME} ]
	set TMP_PATH_E [ exec echo ${TMP_PATH} ]
	set BACKUP_SERVER_IP_E [ exec echo ${BACKUP_SERVER_IP} ]
	
	spawn scp ${LINE_E}:${PUBLIC_KEY_PATH_E}/${PUBLIC_KEY_NAME_E}  ${TMP_PATH_E}/
	expect "yes"
	set timeout 3
	send "yes\r"
	ssh-copy-id -i ${TMP_PATH_E}/${PUBLIC_KEY_NAME_E} ${BACKUP_SERVER_IP_E}
		expect "yes"
	set timeout 3
	send "yes\r"
	expect eof
EOF


rm -f ${TMP_PATH}/${PUBLIC_KEY_NAME}

	#copy backup server ssh-key to client sever and test !	
	
	
		/usr/bin/expect << EOF
	set LINE_E [ exec ${LINE} ]
	set PUBLIC_KEY_PATH_E [ exec echo ${PUBLIC_KEY_PATH} ]
	set PUBLIC_KEY_NAME_E [ exec echo ${PUBLIC_KEY_NAME} ]
	set TMP_PATH_E [ exec echo ${TMP_PATH} ]
	set BACKUP_SERVER_IP_E [ exec echo ${BACKUP_SERVER_IP} ]
	
	spawn scp ${BACKUP_SERVER_IP}:${PUBLIC_KEY_PATH}/${PUBLIC_KEY_NAME}  ${TMP_PATH}/
	expect "yes"
	set timeout 3
	send "yes\r"
	ssh-copy-id -i ${TMP_PATH}/${PUBLIC_KEY_NAME} ${LINE}
		expect "yes"
	set timeout 3
	send "yes\r"
	expect eof
EOF
	
	rm -f ${TMP_PATH}/${PUBLIC_KEY_NAME}
	

	
done < host         #所有的生产服务器的IP列表

Leave a comment

电子邮件地址不会被公开。 必填项已用*标注