【shell脚本】从跳板机上登录其他服务器/home/alice/jumpserver.sh

脚本内容

[root@rhel8 shell]# cat /home/alice/jumpserver.sh 
#!/bin/bash
##########################################################################
# jumpserver跳板机登录其他服务器                                         #
# by author tanbaobao 2020/06/17                                         #
##########################################################################
# 脚本编写完成后将脚本路径写入开机启动的配置文件中:[alice@rhel8 ~]$ vi .bash_profile
# 前提是alice用户,需要登录过去的服务器也必须要有alice或和跳板机相同的用户
# 可以是root,但一般不用root
# 然后每次登录跳板机就会运行此脚本供用户选择要登录的服务器主机
# 记得运行脚本之前将ssh的秘钥传输到其他服务器上,这样就可以免密登录

# 防止退出脚本
# trap "" HUP INT OUIT TSTP

# variables
SERVER1=ip1
SERVER2=iP2
U_PWD=`pwd`

clear

while :
do
    # 输出选项
    cat <<-EOF
    +---------------------------------------------------------------------+
    |    1.rhel8.tourby.cn                          |
    |    2.tanbaobao                                                   |
    +---------------------------------------------------------------------+
    EOF
    
    # 不换行输出颜色
    echo -en "33[32mPlease Input Number: 33[0m"
    # 让用户输入选项
    read NUM

    case "$NUM" in
        1)
#            ssh-copy-id ip1
            ssh alice@$SERVER1
            ;;
        2)
#            ssh-copy-id ip2
            ssh alice@$SERVER2
            ;;
        "")
            ;;
        *)
            echo -e "33[34mError.33[0m"
            ;;
    esac
done

这里同步秘钥到其他服务器上可以参考我了一篇博客:https://www.cnblogs.com/HeiDi-BoKe/p/13072979.html。生成的秘钥文件默认在家目录下的.ssh文件

设置一登录跳板机就运行脚本

在用户家目录下的.bash_profile文件中添加脚本路径,在之前需要为脚本添加执行权限,不然登录时会提示权限不足

[root@rhel8 shell]# cat /home/alice/.bash_profile 
# .bash_profile

# Get the aliases and functions
if [ -f ~/.bashrc ]; then
    . ~/.bashrc
fi

# User specific environment and startup programs
/home/alice/jumpserver.sh
原文地址:https://www.cnblogs.com/HeiDi-BoKe/p/13163100.html