ssh_config 整理

2023-01-28 14:30 +0800

自定义函数,将下面的脚本加入到 bashrc/zshrc 之类的配置中去。

脚本根据我的使用习惯编写,并不完全通用,如有需要,自行修改。
值得注意的地方有:

sshhosts () {
	IFS=$'\n'
	break=''
	for line in $(grep --ignore-case -E "^ *Host|^ *HostName |^ *Port" ~/.ssh/config)
	do
		line=$(sed 's/^[[:space:]]*//' <<< "$line")
		value=$(echo $line | cut -d " " -f2- |  tr -d $'\n')
		[[ $line =~ Host[[:space:]].* ]] && printf "%s%-10s" "$break" "$value"
		[[ $line =~ HostName[[:space:]].* ]] && printf " %s" $value
		[[ $line =~ Port[[:space:]].* ]] && printf ":%s" $value
		break=$'\n'
	done
	echo ""
}

使用示例:

> sshhosts
ringo      10.233.2.3
seiran     10.233.2.4
reisen     10.233.2.6
tei        10.233.2.2:23233
dev        10.233.2.6:2022

如果你有 Host github.com 一类,不是用于登陆的配置,不希望它们污染 host 列表,可以通过 include 指令,将配置分割成多个文件。

> head -n 5 config
include ~/.ssh/config.d/*.conf

Host ringo
  HostName 10.233.2.3
  User lindsay
>
>
> tree
.
├── authorized_keys
├── config
└── config.d
    ├── application.conf
    ├── deprecated.conf
    ├── general.conf
    └── git.conf

2 directories, 6 files
>
>
> cat config.d/general.conf
Host *
  ServerAliveCountMax 20
  ServerAliveInterval 30
  HostKeyAlgorithms +ssh-rsa
  PubkeyAcceptedAlgorithms +ssh-rsa
  IdentityFile ~/.ssh/mykey.pem