天天看点

shell 写登录跳板机

准备3台机器

1.linux-node1  ip:10.89.3.108 (跳板机)

2.weblamp      ip:10.89.3.100

3.weblnmp      ip:10.89.3.101

3台系统环境如下:

[jump@linux-node1 ~]$ cat /etc/redhat-release 
CentOS release 6.8 (Final)      

1)首先做好SSH密钥验证

在所有的3台机器上执行下面操作

 [root@linux-node1 ~]#useradd jump
 [root@linux-node1 ~]#echo 123456|passwd --stdin jump      

在跳板机上执行下面操作,生成密钥。

[jump@linux-node1 ~]$ ssh-keygen -t dsa -P '' -f ~/.ssh/id_dsa      

Generating public/private dsa key pair.

Created directory '/home/jump/.ssh'.

Your identification has been saved in /home/jump/.ssh/id_dsa.

Your public key has been saved in /home/jump/.ssh/id_dsa.pub.

The key fingerprint is:

15:4d:94:d8:a8:0d:e9:d4:e1:70:09:0c:8b:de:2c:96 [email protected]

The key's randomart p_w_picpath is:

+--[ DSA 1024]----+

|      .oo++Xo.   |

|     . .=+=.+    |

|    . .o +o      |

|   . +  o..      |

|    E o S        |

|   . .           |

|                 |

+-----------------+

查看生成的密钥

[jump@linux-node1 ~]$ ll /home/jump/.ssh      

total 8

-rw------- 1 jump jump 672 Apr 12 09:49 id_dsa

-rw-r--r-- 1 jump jump 618 Apr 12 09:49 id_dsa.pub  (公钥)

将公钥分发到其他2台服务器

[jump@linux-node1 ~]$ ssh-copy-id -i ~/.ssh/id_dsa.pub 10.89.3.101      

The authenticity of host '10.89.3.101 (10.89.3.101)' can't be established.

RSA key fingerprint is 01:e7:d2:70:fc:a8:1a:ee:88:07:ef:9b:37:40:29:2d.

Are you sure you want to continue connecting (yes/no)? yes

Warning: Permanently added '10.89.3.101' (RSA) to the list of known hosts.

[email protected]'s password: (此处输入的是jump的密码)

Now try logging into the machine, with "ssh '10.89.3.101'", and check in:

  .ssh/authorized_keys

to make sure we haven't added extra keys that you weren't expecting.

[jump@linux-node1 ~]$ 

2)实现传统的远程连接菜单选择脚本

菜单脚本如下:

cat <<menu

    1)weblamp-10.89.3.100

    2)weblnmp-10.89.3.101

    3)administrator

menu

3)利用linux 信号屏蔽防止用户中断信号在跳板机上操作

function trapper(){

trap ':' INT EXIT TSTP TERM HUP

}

4)用户登录跳板机后即调用脚本(不能使用命令行管理跳板机),并只能按管理员的要求选单

脚本如下(跳板机上操作)

[root@linux-node1 ~]# cat /etc/profile.d/jump.sh 
[ $UID -ne 0 ] && /server/scripts/jump.sh      
[root@linux-node1 ~]# cat /server/scripts/jump.sh      
#!/bin/bash
#Alvin training
trapper(){
    trap ':' INT EXIT TSTP TERM HUP
}

main(){
    while :
    do
    trapper
    clear
    cat <<menu
    1)weblamp-10.89.3.100
    2)weblnmp-10.89.3.101
    3)administrator
menu
    
read -p "Pls input a num.:" num
case "$num" in
   1)
   echo "login in 10.89.3.100"
   ssh 10.89.3.100
   ;;
   2)
   echo "login in 10.89.3.101"
   ssh 10.89.3.101
  ;;
   3)
   stty -echo
   read -p "your privite passwd:" char
    if [ "$char" = "111111" ]; then
    stty echo
    echo "\n"
     exit
     sleep 3
   fi
  ;;
   *)
    echo "select error."
   esac
 done

}

main      
[root@linux-node1 ~]# chmod +x /server/scripts/jump.sh      
[root@linux-node1 ~]# su - jump
    1)weblamp-10.89.3.100
    2)weblnmp-10.89.3.101
    3)administrator
Pls input a num.: