利用Shell开发跳板机功能脚本案例
方法1:
1)首先做好SSH密钥验证(跳板机地址192.168.33.128)。
以下操作命令在所有机器上操作:
[root@oldboy~]#useraddjump#<==要在所有机器上操作。[root@oldboy~]#echo123456|passwd--stdinjump#<==要在所有机器上操作。Changingpasswordforuserjump.passwd:allauthenticationtokensupdatedsuccessfully.
以下操作命令仅在跳板机上操作:
[root@oldboy~]#su-jump[jump@oldboy~]$ssh-keygen-tdsa-P''-f~/.ssh/id_dsa>/dev/null2>&1#<==生成密钥对。[jump@oldboy~]$ssh-copy-id-i~/.ssh/id_dsa.pub192.168.33.130#<==将公钥分发到其他服务器。Theauthenticityofhost'192.168.33.130(192.168.33.130)'can'tbeestablished.RSAkeyfingerprintisfd:2c:0b:81:b0:95:c3:33:c1:45:6a:1c:16:2f:b3:9a.Areyousureyouwanttocontinueconnecting(yes/no)?yesWarning:Permanentlyadded'192.168.33.130'(RSA)tothelistofknownhosts.jump@192.168.33.130'spassword:Nowtryloggingintothemachine,with"ssh'192.168.33.130'",andcheckin:.ssh/authorized_keystomakesurewehaven'taddedextrakeysthatyouweren'texpecting.[jump@oldboy~]$ssh-copy-id-i~/.ssh/id_dsa.pub192.168.33.129#<==将公钥分发到其他服务器。Theauthenticityofhost'192.168.33.129(192.168.33.129)'can'tbeestablished.RSAkeyfingerprintisfd:2c:0b:81:b0:95:c3:33:c1:45:6a:1c:16:2f:b3:9a.Areyousureyouwanttocontinueconnecting(yes/no)?yesWarning:Permanentlyadded'192.168.33.129'(RSA)tothelistofknownhosts.jump@192.168.33.129'spassword:Nowtryloggingintothemachine,with"ssh'192.168.33.129'",andcheckin:.ssh/authorized_keystomakesurewehaven'taddedextrakeysthatyouweren'texpecting.
2)实现传统的远程连接菜单选择脚本。
菜单脚本如下:
cat<<menu1)oldboy-192.168.33.1292)oldgirl-192.168.33.1303)exitmenu
3)利用linux信号防止用户中断信号在跳板机上操作。
1 2 3 |
|
4)用户登录跳板机后即调用脚本(不能命令行管理跳板机),并只能按管理员的要求选单。
以下为实战内容。
脚本放在跳板机上:
[root@oldboy~]#echo'[$UID-ne0]&&./server/scripts/jump.sh'>/etc/profile.d/jump.sh[root@oldboy~]#cat/etc/profile.d/jump.sh[$UID-ne0]&&./server/scripts/jump.sh[root@oldboyscripts]#cat/server/scripts/jump.sh#!/bin/sh#oldboytrainingtrapper(){trap':'INTEXITTSTPTERMHUP#<==定义需要屏蔽的信号,冒号表示啥都不做。}main(){while:dotrapperclearcat<<menu1)Web01-192.168.33.1292)Web02-192.168.33.130menuread-p"Plsinputanum.:"numcase"$num"in1)echo'loginin192.168.33.129.'ssh192.168.33.129;;2)echo'loginin192.168.33.130.'ssh192.168.33.130;;110)read-p"yourbirthday:"charif["$char"="0926"];thenexitsleep3fi;;*)echo"selecterror."esacdone}main
执行效果如下:
[root@oldboy~]#su-jump#<==切到普通用户即弹出菜单,工作中直接用jump登录,即弹出菜单。1)Web01-192.168.33.1292)Web02-192.168.33.130Plsinputanum.:1)Web01-192.168.33.1292)Web02-192.168.33.130Plsinputanum.:1#<==选1进入Web01服务器。loginin192.168.33.129.Lastlogin:TueOct1117:23:522016from192.168.33.128[jump@littleboy~]$#<==按ctrl+d退出到跳板机服务器再次弹出菜单。1)Web01-192.168.33.1292)Web02-192.168.33.130Plsinputanum.:2#<==选2进入Web02服务器。loginin192.168.33.130.Lastlogin:WedOct1223:30:142016from192.168.33.128[jump@oldgirl~]$#<==按ctrl+d退出到跳板机服务器再次弹出菜单。1)Web01-192.168.33.1292)Web02-192.168.33.130Plsinputanum.:110#<==选110进入跳板机命令提示符。yourbirthday:0926#<==需要输入特别码才能进入的,这里管理员通道,密码要保密呦。[root@oldboyscripts]##<==跳板机管理命令行。原文链接:https://www.f2er.com/bash/387816.html