ssh登陆脚本
ssh长连接
在~/.ssh/config中添加如下配置(该配置的含义是和同一个目的主机的连接使用长连接,避免多次输入密码)
Host *
ControlMaster auto
ControlPath ~/.ssh/%h-%p-%r
ControlPersist yes
ServerAliveInterval 30
ssh登录脚本
使用expect脚本实现,适用于macbook(先安装brew,在通过brew安装expect,window不支持expect脚本)。
#文件 login.sh 包一层,避免rzsz传文件失败
#!/bin/bash
#echo $*
#echo "$*"
#echo $@
#echo "$@"
export LC_CTYPE=en_US
echo "$@"
expect xxxxx/login.exp "$@"
#end of file
#文件 login.exp
#!/usr/bin/expect
set server [lindex $argv 0];
set timeout 30
switch $server {
default {
spawn ssh xxx@relay.baidu-int.com
expect {
"bash-baidu-ssl" {
switch $server { #$server是传给login.exp的参数
"abc" {
send "ssh yyy@zzz\r" # ssh命令
expect "password:"
send "ppp\r" # 密码
}
default {
send "echo invalid param args\r"
}
}
}
"password:" {
switch $server {
default {
send "\r"
}
}
}
}
}
}
interact
#end of file
有了上面两个脚本,执行 bash login.sh abc会发生以下行为:
- ssh xxx@relay.baidu-int.com
- 如果未登录跳板机,会提示输入密码。
- 如果已登录,会继续执行 ssh yyy@zzz 并发送密码ppp。
在profile中使用命令。配置命令:sh login.sh abc。即可直接登录目标机器。