一个简单的SSH的连接工具

我门在通过SSH连接服务器的时候,如果有很多机器的话,不容易记住,下面这个简单的工具可以解决问题。

程序是一个Shell脚本sc,列出服务器,选择服务器序号后直接连接服务器。先看一下效果。

$ 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
# 数据以空格分割,格式为:序号 user@IP地址 注释
# 程序只会处理序号前两列,注释中可以有空格
data=('1. yang@111.229.112.37 my CentOS server'
      '2. admin@111.229.128.6 my Ubuntu server')

# 根据特性判断数组索引从 0 开始还是从 1 开始
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 数组索引从0开始,ZSH 数组索引从1开始,BASH 要在输入的数值减 1
    n=$((n-$delta))
}

print_data(){
    local old_ifs=$IFS
    # BASH 的分隔符是空格,更改分隔符防止显示错乱
    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

注意:如果在连接的时候提示输入密码,你可以使用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.
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容