管理するサーバが増減するたびに変更を加えるOpenSSHの設定ファイル~/.ssh/config
長くなりすぎて管理しづらくなると何とかこれを分割したくなりますね?ファイルが分割できれば、gitで管理したり、一部をメンバーとプロジェクトで共有できたりできて便利そうです。ここでは私が利用している~/.ssh/config
の分割方法をご紹介します。
本編は以前Qiitaに似たような記事 を書きましたが、そのパワーアップ?バージョンです。
sshconfのインストール
以下のシェルスクリプトをsshconf
と言う名前で保存して、実行権限つけて(chmod +x sshconf
)どこかPATHの通ったところに置いてください。
#!/bin/bash | |
command=$1 | |
ssh_config_dir=~/.ssh | |
ssh_configs_dir=${ssh_config_dir}/conf.d | |
ssh_config_file=${ssh_config_dir}/config | |
ssh_base_config_file=${ssh_configs_dir}/config | |
function usage() | |
{ | |
echo "Usage: `basename $0` [update [go]] [add user@ipaddress alias]" | |
} | |
function generate() | |
{ | |
cat ${ssh_base_config_file} ${ssh_configs_dir}/*.conf > ${ssh_config_file}.new | |
} | |
function diff_w_new() | |
{ | |
diff -uN ${ssh_config_file} ${ssh_config_file}.new | |
} | |
function update() | |
{ | |
cp ${ssh_config_file} ${ssh_config_file}.old | |
cp ${ssh_config_file}.new ${ssh_config_file} | |
} | |
if [ -z "$command" ]; then | |
generate | |
diff_w_new && exit | |
while true; do | |
read -p "Do you wish to overwrite ${ssh_config_file}? [Y] " yn | |
case $yn in | |
[Yy]* ) update; break;; | |
* ) exit;; | |
esac | |
done | |
exit | |
fi | |
case $command in | |
update) | |
generate | |
update | |
;; | |
*) | |
usage | |
;; | |
esac | |
既存の設定の退避(重要)
sshconf
は~/.ssh/config
を上書きしますので、コピーして既存の設定を残すようにします。
$ cp ~/.ssh/config ~/.ssh/base_config
サーバの追加
接続先のサーバを追加するには以下のコマンドを実行してください
$ sshconf add user@ipaddress alias
ユーザalis
でbob.example.com
にssh bob
で繋げるようにするには以下のようになります。
$ sshconf add alis@bob.example.com bob
このコマンドにより、以下のファイルが作られます。
~/.ssh/conf.d/bob.conf
Host bob
User alis
HostName bob.example.com
また、~/.ssh/conf.d/bob.conf
の内容が~/.ssh/base_config
とマージされて~/.ssh/config
に上書きされます。
これによりssh bob
とすることで、alis@bob.example.com
へのsshを実現しています。
sshオプションの変更
~/.ssh/conf.d/bob.conf
にsshオプションを追加したい場合はファイルを直接変更して、sshconf update
を実行してください。
例えば、sshポートを10022
に変えたい場合、以下のように直接ファイルを修正
~/.ssh/conf.d/bob.conf
Host bob
User alis
HostName bob.example.com
Port 10022
そして、sshconf update
を実行
$ sshconf update
これで~/.ssh/config
が更新されます。