千恋*万花

  • 首页
  • 个人简历
  • 文章分类
    • 后端开发
    • 运维
    • 基础知识
    • 笔记
    • 工作运维记录
    • 随笔
    • 未分类文章
萌奈の笔记簿
分享我的努力,希望为你助力
  1. 首页
  2. 运维
  3. bash
  4. 正文

多IP服务器 ssh 远程连接 自动选择IP脚本

2022-09-29 3807点热度 1人点赞 0条评论

需求

从前,有一只萌奈,她有这样一个需求:

萌奈有一台家用的 NAS 服务器,每次萌奈要 ssh 连接到这台服务器上时,都需要自己手动选择一个合适的 IP 地址

在家的时候,需要选择NAS的内网IP直接连接;在户外的时候,又需要根据情况选择直接连接到NAS或者是通过FRP转发连接到NAS。
萌奈觉得这样太麻烦了,想用一个脚本来解决这个问题。

代码

萌奈酱双手一挥,写下了这段脚本:

#!/bin/bash

IP_LIST="192.168.1.161 example.moemona.com another.example.moemona.com"

declare -A PORT_MAP
PORT_MAP["192.168.1.161"]="22"
PORT_MAP["example.moemona.com"]="10022"
PORT_MAP["another.example.moemona.com"]="20022"

for ip in $IP_LIST; do    #for循环遍历数组
    if ping -c 1 -W 1 $ip > /dev/null
        then
            echo "$ip Ping is success, Connect."  # if 判断如果ping通 则返回success
            echo "ssh connect port is ${PORT_MAP[${ip}]}."
            ssh userName@$ip -p ${PORT_MAP[${ip}]}
            break
        else
            echo "$ip Ping is faild, pass."
        fi
done

Windows Terminal 配置

使用基于WSL2的 bash shel 来运行本脚本
启动命令行:wsl.exe /home/user/path_to_shell_script.sh

本作品采用 知识共享署名-非商业性使用-相同方式共享 4.0 国际许可协议 进行许可
标签: bash linux shell ssh 服务器 脚本 自动
最后更新:2022-10-11

初音萌奈

我是练习时长 三年半 的后端开发程序员 谢谢你参观我的博客! 本网站现已支持IPv6 ☞ 个人简历 ☜

点赞
< 上一篇

文章评论

razz evil exclaim smile redface biggrin eek confused idea lol mad twisted rolleyes wink cool arrow neutral cry mrgreen drooling persevering
取消回复
文章目录
  • 需求
  • 代码
  • Windows Terminal 配置

COPYRIGHT © 2025 HatsuneMona ALL RIGHTS RESERVED.

Theme Kratos Made By Seaton Jiang

晋ICP备17007130号-4