blog-site

git clone git://git.lin.moe/blog-site.git

 1---
 2title: "ssh_config 整理"
 3date: 2023-01-28T14:30:02+08:00
 4---
 5
 6
 7
 8自定义函数,将下面的脚本加入到 `bashrc`/`zshrc` 之类的配置中去。  
 9> 脚本根据我的使用习惯编写,并不完全通用,如有需要,自行修改。  
10> 值得注意的地方有:  
11> + Host/HostName/Port 大小写敏感  
12> + 使用空格缩进。  
13
14```
15sshhosts () {
16	IFS=$'\n'
17	break=''
18	for line in $(grep --ignore-case -E "^ *Host|^ *HostName |^ *Port" ~/.ssh/config)
19	do
20		line=$(sed 's/^[[:space:]]*//' <<< "$line")
21		value=$(echo $line | cut -d " " -f2- |  tr -d $'\n')
22		[[ $line =~ Host[[:space:]].* ]] && printf "%s%-10s" "$break" "$value"
23		[[ $line =~ HostName[[:space:]].* ]] && printf " %s" $value
24		[[ $line =~ Port[[:space:]].* ]] && printf ":%s" $value
25		break=$'\n'
26	done
27	echo ""
28}
29```
30
31使用示例:
32```
33> sshhosts
34ringo      10.233.2.3
35seiran     10.233.2.4
36reisen     10.233.2.6
37tei        10.233.2.2:23233
38dev        10.233.2.6:2022
39```
40
41如果你有 `Host github.com` 一类,不是用于登陆的配置,不希望它们污染 host 列表,可以通过 include 指令,将配置分割成多个文件。  
42
43```
44> head -n 5 config
45include ~/.ssh/config.d/*.conf
46
47Host ringo
48  HostName 10.233.2.3
49  User lindsay
50>
51>
52> tree
53.
54├── authorized_keys
55├── config
56└── config.d
57    ├── application.conf
58    ├── deprecated.conf
59    ├── general.conf
60    └── git.conf
61
622 directories, 6 files
63>
64>
65> cat config.d/general.conf
66Host *
67  ServerAliveCountMax 20
68  ServerAliveInterval 30
69  HostKeyAlgorithms +ssh-rsa
70  PubkeyAcceptedAlgorithms +ssh-rsa
71  IdentityFile ~/.ssh/mykey.pem
72```