Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
known_hostsに保存されているホストキーを更新する。詳細はこちら→http://qiita.com/kawaz/items/20983ec286088a1ae5c7
#!/bin/bash
# ssh設定値の取得関数
sshconf() {
local key=$1 targethost=$2
local value inhost f k v m
[[ -z $key ]] && { echo "Usage: $FUNCNAME key [hostname]"; return 1; }
for f in ~/.ssh/config /etc/ssh_config; do
[[ -r $f ]] || continue
inhost=1
while read k v; do
if [[ $k == Host ]]; then
inhost=
for m in $v; do
[[ $m =~ ^# ]] && break # skip comment
m=${m//./\\.}; m=${m//\*/.*}; m=${m//\?/.}; m="^$m$" # wildcard -> regexp
if [[ $targethost =~ $m ]]; then
inhost=1
break
fi
done
continue
fi
[[ -z $inhost ]] && continue # 不一致Host内の設定は無視
if [[ $k == $key ]]; then
value=$v
fi
if [[ -n $value ]]; then
break # 最初に見つけた設定優先なのでbreak
fi
done < <(cat $f | grep -v '^$' | egrep -v '^\s*#')
if [[ -n $value ]]; then
break # 最初のファイル優先なのでbreak
fi
done
[[ -z $value ]] && return 1
printf "%s\n" "$value"
}
# main
[[ -z $1 ]] && { echo "Usage: $0 hostname [hostname...]"; exit 1; }
hashopt=
if [[ $(sshconf HashKnownHosts) == yes ]]; then
hashopt=-H
fi
for h in "$@"; do
ssh-keygen -R "$h"
ssh-keyscan $hashopt "$h" >> ~/.ssh/known_hosts
done
# ssh設定値の取得関数
sshconf() {
local key=$1 targethost=$2
local value inhost f k v m
[[ -z $key ]] && { echo "Usage: $0 key [hostname]"; return 1; }
for f in ~/.ssh/config /etc/ssh_config; do
[[ -r $f ]] || continue
inhost=1
while read k v; do
if [[ $k == Host ]]; then
inhost=
for m in $v; do
[[ $m =~ ^# ]] && break # skip comment
m=${m//./\\.}; m=${m//\*/.*}; m=${m//\?/.}; m="^$m$" # wildcard -> regexp
if [[ $targethost =~ $m ]]; then
inhost=1
break
fi
done
continue
fi
[[ -z $inhost ]] && continue # 不一致Host内の設定は無視
if [[ $k == $key ]]; then
value=$v
fi
if [[ -n $value ]]; then
break # 最初に見つけた設定優先なのでbreak
fi
done < <(cat $f | grep -v '^$' | egrep -v '^\s*#')
if [[ -n $value ]]; then
break # 最初のファイル優先なのでbreak
fi
done
[[ -z $value ]] && return 1
printf "%s\n" "$value"
}
@kawaz

This comment has been minimized.

Copy link
Owner Author

@kawaz kawaz commented Jul 25, 2014

sshの設定取得関数単体でも便利そうなので、sshconf.sh として独立したファイルに分離してみた。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment