1. 程式人生 > 其它 >ssh-host-remote-copy:Bash/Shell指令碼,自動拷貝本地主機SSH金鑰和配置資訊到遠端主機,方便在遠端主機上使用ssh命令連線其他伺服器

ssh-host-remote-copy:Bash/Shell指令碼,自動拷貝本地主機SSH金鑰和配置資訊到遠端主機,方便在遠端主機上使用ssh命令連線其他伺服器

ssh-host-remote-copy:Bash/Shell指令碼,自動拷貝本地主機SSH金鑰和配置資訊到遠端主機,方便在遠端主機上使用ssh命令連線其他伺服器
支援拷貝單個或多個主機配置資訊及金鑰:

#!/bin/bash 
SCRIPTPATH=$(realpath $0)
#SCRIPTPATH="$( cd "$(dirname "$0")" >/dev/null 2>&1 ; pwd -P )"
#SCRIPTPATH=$(dirname $(readlink -f "$0"))

display_usage() {
	echo -e "$SCRIPTPATH\n"
    echo -e "\t自動拷貝本地~/.ssh/config中指定主機配置項和對應私鑰到遠端主機."
	echo -e "\t目的:方便在遠端主機上通過ssh免密碼連線另一臺伺服器"
    echo -e "\nUsage:\n\tssh-host-remote-copy [connect hostname] [copy target host]"
	echo -e "Example:\n\tssh-host-remote-copy racknerd kunming"
	echo -e "\n\t妙用:拷貝本地所有的主機配置和私鑰到遠端伺服器可以使用以下命令(.號匹配所有主機):"
	echo -e "\tssh-host-remote-copy racknerd ."
}
# if less than two arguments supplied, display usage
if [  $# -lt 2 ]
then
    display_usage
    exit 1
fi

# check whether user had supplied -h or --help . If yes display usage
if [[ ( $* == "--help") ||  $* == "-h" ]]
then
    display_usage
    exit 0
fi

sshHost=$1
copyTarget=$2

hostInfo=$(/v/bin/sshfind.py $copyTarget)

findCount=$(echo "$hostInfo"|grep -ci 'Host ')

if [ $findCount -gt 1 ];
then
	echo "拷貝目標找到多個匹配,請注意拷貝動作是否符合預期!"
fi

sshConfigFile="/tmp/ssh_config_tmp.$$"
trap "rm -f $sshConfigFile" 0
#清除配置檔案多餘行
hostInfoFormat=$(echo "$hostInfo"|awk '/^[0-9]+$/{next};/sshfind/{exit};/以上為全字匹配結果/{exit};/^$/{next};{print}')
echo "$hostInfoFormat">$sshConfigFile

IdentityFile=$(echo "$hostInfoFormat"|awk '/IdentityFile/{print $NF}')
#echo "$IdentityFile"
ssh $sshHost 'mkdir -p ~/.ssh/'
echo -e "Copy Key Files to remote server..."
keyFiles=$(echo -e "$IdentityFile"|tr '\n' ' ')
eval scp $keyFiles $sshHost:~/.ssh/
echo -e "Copy SSH Config temp file to remote server..."
scp $sshConfigFile $sshHost:$sshConfigFile
echo -e "Configure ssh config for user..."
ssh $sshHost 'touch ~/.ssh/config;chmod 600 ~/.ssh/*;\
	awk  '\''BEGIN{while(getline line<"'$sshConfigFile'"){print line}}{print}'\'' ~/.ssh/config|tee ~/.ssh/config >/dev/null;\
	rm -f /tmp/ssh_config_tmp*'
echo -e "Done..."

本文來自部落格園,作者:晴雲孤魂,轉載請註明原文連結:https://www.cnblogs.com/cnhack/p/15619360.html