Site icon moneyslow.com

Mac下用iTerm2登陆跳板机后登陆服务器,用expect来实现

iTerm2技巧

iTerm2技巧

Mac本地的用户生成一个ssh的密钥对:

sherry@ifengdeMacBook-Air ~ % id
uid=502(sherry) gid=20(staff) groups=20(staff),12(everyone),61(localaccounts),100(_lpoperator),702(com.apple.sharepoint.group.2),701(com.apple.sharepoint.group.1)
sherry@ifengdeMacBook-Air ~ % ssh-keygen -t rsa
Generating public/private rsa key pair.
Enter file in which to save the key (/Users/sherry/.ssh/id_rsa):
Created directory '/Users/sherry/.ssh'.
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /Users/sherry/.ssh/id_rsa
Your public key has been saved in /Users/sherry/.ssh/id_rsa.pub
The key fingerprint is:
SHA256:mvkGsPtn2TbtmTUGEp9MCCzXS2xE4I50T3MkvpvVpt0 sherry@ifengdeMacBook-Air.local
The key's randomart image is:
+---[RSA 3072]----+
|       .o*+ .    |
|      ..oo=+     |
|      .ooo*.o    |
|    .. + o.O o   |
|     o. S + * o  |
|    . .+   = = . |
|     .+. oo.. = E|
|    .  .= + .= . |
|     ..+.. o+    |
+----[SHA256]-----+
sherry@ifengdeMacBook-Air ~ %

Mac下的用户,建立一个.ssh目录,在.ssh目录下建一个shell脚本,login_jump.sh,内容如下:

#!/usr/bin/expect
set host [lindex $argv 0]

set TERMSERV jumpserver_iP
set USER ubuntu
set PASSWORD jumpserverpassword
set UATUN ubuntu
set UATPWD destpassword

# 登录跳板机
spawn ssh -l $USER $TERMSERV
expect {
        "yes/no" {send "yes\r";exp_continue;}
         "*password:*" { send "$PASSWORD\r" }
        }
# 登录目标服务器
expect "*ubuntu@*" {send "ssh -l $UATUN $host\r"}
expect {
        "yes/no" {send "yes\r";exp_continue;}
        "*password:*" { send "$UATPWD\r" }
        }
interact

其中,jumpserver_iP 替换为跳板机ip,jumpserverpassword替换为跳板机的密码,这里假设跳板机和目标服务器的用户名都是ubuntu,destpassword是目标机器的密码

加脚本的执行权限: 
chmod -R a+x login_jump.sh

下面在iTerm2中新建profile:
假设要通过调拌机登录目标机器 123.123.123.123
Command 选择 login shell
Send text start输入
/Users/ubuntu/.ssh/login_jump.sh 123.123.123.123

Exit mobile version