我門(mén)在通過(guò)SSH連接服務(wù)器的時(shí)候,如果有很多機(jī)器的話(huà),不容易記住,下面這個(gè)簡(jiǎn)單的工具可以解決問(wèn)題。
程序是一個(gè)Shell腳本sc,列出服務(wù)器,選擇服務(wù)器序號(hào)后直接連接服務(wù)器。先看一下效果。
$ sc
1. yang@111.229.112.37 my CentOS server
2. admin@111.229.128.6 my Ubuntu server
Plese input number: 1
Last login: Sun Oct 18 08:37:09 2020 from 112.97.57.235
[xd@VM-0-10-centos ~]$
sc代碼兼容ZSH和BASH,如下
#!/bin/bash
n=0
# 數(shù)據(jù)以空格分割,格式為:序號(hào) user@IP地址 注釋
# 程序只會(huì)處理序號(hào)前兩列,注釋中可以有空格
data=('1. yang@111.229.112.37 my CentOS server'
'2. admin@111.229.128.6 my Ubuntu server')
# 根據(jù)特性判斷數(shù)組索引從 0 開(kāi)始還是從 1 開(kāi)始
array_delta(){
local arr=('a' 'b')
if [ ${arr[1]} = "b" ]; then
return 1
else
return 0
fi
}
read_input_to_n() {
array_delta
local delta=$?
echo -n "Plese input number: "
read n
# BASH 數(shù)組索引從0開(kāi)始,ZSH 數(shù)組索引從1開(kāi)始,BASH 要在輸入的數(shù)值減 1
n=$((n-$delta))
}
print_data(){
local old_ifs=$IFS
# BASH 的分隔符是空格,更改分隔符防止顯示錯(cuò)亂
IFS='|'
for pc in ${data[@]}; do
echo $pc
done
IFS=$old_ifs
}
print_data
read_input_to_n
cmd=$(echo ${data[n]} | cut -d' ' -f2)
ssh $cmd
注意:如果在連接的時(shí)候提示輸入密碼,你可以使用ssh-copy-id命令,再連接就不用輸入密碼了。
ssh-copy-id使用演示如下:
$ ssh-copy-id yang@111.229.112.37
/usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/Users/xd/.ssh/id_rsa.pub"
/usr/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed
/usr/bin/ssh-copy-id: INFO: 1 key(s) remain to be installed -- if you are prompted now it is to install the new keys
yang@111.229.112.37's password:
Number of key(s) added: 1
Now try logging into the machine, with: "ssh 'yang@111.229.112.37'"
and check to make sure that only the key(s) you wanted were added.