shell腳本實現:基於key驗證的公鑰批量推送

自動化運維工具ansible需要基於ssh key驗證免密登錄。

#!/bin/bash
#
#========================================================================
#
#	author: 9528
#	mail: [email protected]
#	date: 2019-7-24
#
#------------------------------------------------------------------------
#	簡述:
#		腳本實現批量推送公鑰,實現ssh key驗證免密登陸,ip地址由ip.txt文件
#	導入,success_ip.txt存放推送成功的ip地址,failed_ip.txt存放推送失敗的ip
#	地址。
#    
#       待改進:
#            明文存放密碼風險
#
#========================================================================
#

. /etc/init.d/functions
#被推送主機的密碼
password="7654321"  
#創建文件,存放推送成功的ip
>success_ip.txt		
#創建文件,存放推送失敗的ip
>failed_ip.txt		


#
#檢查是否按照了expect軟件包
#
rpm -q expect &>/dev/null || (echo "------start install expect!------" && yum install expect -y &> /dev/null)
if [ $? -ne 0 ]
then
	echo -e "\033[31m------install expect failed!------\033[0m"
	echo -e "\033[31m------end exit!------\033[0m"
	exit 2
fi


#
#檢查本機密鑰是否丟失,若丟失則重新生成密鑰
#
if [ ! -f ~/.ssh/id_rsa ] || [ ! -f ~/.ssh/id_rsa.pub ]
then
	rm -f ~/.ssh/id_rsa*
	echo "------start ssh-keygen!------"
	ssh-keygen -P "" -f ~/.ssh/id_rsa &> /dev/null 
	if [ $? -ne 0 ]
	then
		echo -e "\033[31m------ssh-keygen failed!------\033[0m"
		echo -e "\033[31m------end exit!------\033[0m"
		exit 2
	fi
fi


#
#檢查ip是否能ping通,能ping通才推送祕鑰
#
echo "------start ssh-copy-id!------"
while read ip
do
	ping -c1 -W3 $ip &> /dev/null
	if [ $? -eq 0 ]
	then
		expect &> key.log <<- EOF
		spawn ssh-copy-id $ip
		set timeout 10
		expect {
			"yes/no" { send "yes\r"; exp_continue}
			"password" { send "$password\r" }
		}
		expect eof
		EOF

		sleep 0.5
		#
		#通過每次執行後的信息區分下面三種情況:
		#	1.正常推送成功
		#	2.原來的密鑰已推送過,這種情況我們也標記成推送成功
		#	3.password驗證錯誤導致推送失敗
		#
		if fgrep -q "try logging into the machine" key.log
		then
			echo $ip >> success_ip.txt
			action "$ip" /bin/true
		elif fgrep -q "they already exist on the remote system." key.log
		then
			echo $ip >> success_ip.txt
			action "$ip" /bin/true
		else fgrep -q "Permission denied, please try again." key.log
			echo $ip >> failed_ip.txt
			action "$ip" /bin/false
		fi
	#
	#ping不通的情況
	#
	else 
		action "$ip" /bin/false
		echo $ip >> failed_ip.txt
	fi
done < ip.txt

echo -e "\n\033[34m------------finish!------------\033[0m\n"

執行結果

[root@localhost ~]$bash  key.sh
------start install expect!------
------start ssh-keygen!------
------start ssh-copy-id!------
192.168.1.77                                               [  OK  ]
192.168.1.88                                               [  OK  ]

------------finish!------------

相關文件

[root@localhost ~]$ls *txt
failed_ip.txt  ip.txt  success_ip.txt

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章