mac 无密码登录远程服务器

mac 无密码登录远程服务器

记录贴 使用expect 脚本 快速通过跳板机连接远程服务器

新建脚本 login.exp
示例如下:

#!/usr/bin/expect

#定义数组
#连接枚举
set connection_enum(1) "179"
set connection_enum(2) "gpu线上机器)"
set connection_enum(3) "ocr开发)"
set connection_enum(4) "ocr线上)"

#用户枚举
set connection_user(1) "seven"
set connection_user(2) "ubuntu"
set connection_user(3) "ubuntu"
set connection_user(4) "ubuntu"

#连接密码
set connection_passwd(1) "xxxxx"
set connection_passwd(2) "xxxx"
set connection_passwd(3) "xxxxxx"
set connection_passwd(4) "xxxxxxxxx"

#连接ip
set connection_ip(1) "10.10.0.0"
set connection_ip(2) "0.0.0.1"
set connection_ip(3) "127.0.0.1"
set connection_ip(4) "127.0.0.2"

#函数定义必须在使用前面否则会报错
#列出可用的host以及枚举
proc connectionlist {} {
    global connection_enum
    #[array size connection_enum]命令是求数组connection_enum的长度
    for {set i 1} {$i <= [array size connection_enum]} {incr i} {
        puts "signin \[$i\] for $connection_enum($i)"
    }
}

#登录host
proc connecthost { enum } {
    global connection_passwd
    global connection_ip
    global connection_user

    #免密登录跳板机,所以注释掉下面三行,如果不是免密登录跳板机就需要打开注释
    spawn ssh -l dingxz 106.75.22.248
    #expect {
    #         "*password*" { send "$PASSWORD\r" }
    #       }
    #接收到跳板机登录成功的消息后登录目标机器
    expect "*Last login*" {send "ssh -l $connection_user($enum) $connection_ip($enum)\r"}
    expect {
            "yes/no" {send "yes\r";exp_continue;}
            "*password:*" { send "$connection_passwd($enum)\r" }
           }
    interact
}

if {[llength $argv] == 0} {
    puts "choice your login host:"
    connectionlist

    expect {
        #正则匹配输入的值,1或2
        "\[1234\]" {
            set num $expect_out(buffer); #$expect_out(buffer)获取输入值,set进行类型转换
            connecthost $num;
        }
        # "1" { connecthost 1 }
        # "2" { connecthost 2 }
    }
}

运行 expect ~/.ssh/login.exp 即可自动跳转连接
也可在bash配置文件bash_profile中添加 alias connect=”expect ~/login.exp” 从而自动加载且有快捷启动命令

你可能感兴趣的:(工具相关)