Fragments of verbose memory

冗長な記憶の断片 - Web技術のメモをほぼ毎日更新(準備中)

Jan 26, 2021 - コメント - 日記

sshconf ver2改

以前書いた記事~/.ssh/configを分割して管理する ver2 のスクリプトsshconf改良をしましました。以前といってもたった数週間前であり、そもそもその記事自体が改良記事でしたが改良の改良ということでお許しください。

OpenSSHの古くないバージョンからは~/.ssh/configIncludeが使えるよという情報を得たからです。

古くないっていうのは5年前…。以前のsshconf~/.ssh/configを生成していましたがそれが必要なくなりました。つまり、以下のように~/.ssh/configを書いておけば自動的に~/.ssh/conf.d/*.confを読んでくれます。

~/.ssh/config

1
2
3
4
5
6
# 共通な設定
Host *
  UseKeychain yes

# conf.d以下を読む
Include ~/.ssh/conf.d/*.conf

改良したスクリプトは以下です、ずいぶんすっきりしました。

sshconf

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
#!/bin/bash
command=$1
ssh_config_dir=~/.ssh
ssh_configs_dir=${ssh_config_dir}/conf.d
ssh_config_file=${ssh_config_dir}/config

function usage()
{
    echo "Usage: `basename $0` user@ipaddress alias"
}

function add()
{
  dest=$1
  name=$2
  file="${ssh_configs_dir}/${name}.conf"
  user=
  host=
  if [ -f $file ] ;then
    echo "${file} exists"
    exit
  fi
  a=(${dest//@/ })

  echo "Host ${name}" > $file
  if [ ${#a[@]} = 1 ]; then
    host=${a[0]}
    echo "  HostName ${host}" >> $file
  fi
  
  if [ ${#a[@]} -eq 2 ]; then
    user=${a[0]}
    host=${a[1]}
    echo "  User ${user}" >> $file
    echo "  HostName ${host}" >> $file
  fi

  echo $file

}

[ $# -eq 2 ] && command='add'

case $command in
  add)
    add $1 $2
    ;;
  *)
    usage
    ;;
esac

使い方は以前とは異なっていて、sshconf user@example.com exampleのようにsshconf 接続先 別名とします。