#!/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注:脚本优先做主机别名全字匹配,没有结果再尝试模糊匹配."
echo -e "\nUsage:\n\tsshfind [keyword]"
echo -e "Example:\n\tsshfind racknerd"
}
# if less than two arguments supplied, display usage
if [ $# -lt 1 ]
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
hoststr=$1
##优先做主机别名全字匹配,如果查找不到,再做模糊匹配
##特别注意,主机别名中带有短横线-或者英文句号.等特殊符号可能会影响全字匹配(尝试sshfind n1;sshfind inner\\-n1)
if [[ $(sed -nr '/Host .*[^\-\.]*\b'$hoststr'\b.*/,/Host /{/Host .*\b'$hoststr'\b.*/{=};/Host [^\b'$hoststr'\b]/b;p}' ~/.ssh/config|wc -l) > 1 ]];then
sed -nr '/Host .*[^\-\.]*\b'$hoststr'\b.*/,/Host /{/Host .*\b'$hoststr'\b.*/{=};/Host [^\b'$hoststr'\b]/b;p}' ~/.ssh/config
echo -e "\n\t以上为全字匹配结果"
#echo -e "=========================================="
else
#下面这行匹配不是很精准,备用;改用 sshfindline 依次进行精准匹配
#sed -nr '/Host .*'$hoststr'.*/,/Host /{/Host .*'$hoststr'.*/{=};/Host [^'$hoststr']/b;p}' ~/.ssh/config
hostlines=$(sed -nr '/Host .*'$hoststr'.*/,/Host /{/Host .*'$hoststr'.*/{=}}' ~/.ssh/config)
for host in $(echo "$hostlines"|tr '\n' ' ');
do
echo -e "$host"
sshfindline $host
done
fi
#sed -nr '/Host .*'$hoststr'.*/,/Host /{/Host .*'$hoststr'.*/{=;D;N};/Host [^'$hoststr']/b;p}' ~/.ssh/config