公司有很多测试服务器,经常需要登录这些服务器测试来查看服务日志。由于这些测试服务器只能通过账号+密码的方式登录,Windows下可以通过Xshell实现自动登录,但在MacOS中并没有发现比较好的工具,
在终端通过SSH方式登录时每次都需要输入密码,十分麻烦,经过一番搜索,最终实现了使用expect在终端直接ssh自动登录,并在登录成功后执行指定脚本。

安装expect

MacOS:

直接通过Homebrew来安装:

1
brew install expect

Linux系统

请自行搜索

编写脚本

/usr/local/bin目录下新建脚本auth_ssh.shdo_ssh.sh

auto_ssh.sh

1
2
3
4
5
6
7
8
9
10
11
12
13
#!/bin/bash
host=$1
port=$2
user=$3
pswd=$4
cmd=$5

if [ -z "$cmd" ];
then
cmd = "cd ~/"
fi

do_ssh.sh $host $port $user $pswd "$cmd"

do_ssh.sh

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#!/usr/bin/expect

set timeout 30
set host [lindex $argv 0]
set port [lindex $argv 1]
set user [lindex $argv 2]
set pswd [lindex $argv 3]
set cmd [lindex $argv 4]

spawn ssh -p $port $user@$host
expect {
"(yes/no)?"
{send "yes\n";exp_continue}
"password:"
{send "$pswd\n"}
"Password:"
{send "$pswd\n"}
}
expect {
"login"
{send "$cmd\n"}
}
interact

注意:第20行的login表示期待登录成功后的输出会包含字符串login,请根据实际情况做修改

之后在终端执行命令 auto_ssh <host> <port> <user> <pswd> "<cmd>"即可。

为登录命令配置别名

~/.bash_profile添加命令别名,例如:

1
alias ss76="auto_ssh.sh 192.168.12.76 22 root abcd \"cd /home/tomcat/\""

然后执行

1
source ~/.bash_profile

之后在终端ss76即可自动登录到192.168.12.76并切换到/home/tomcat/目录中

参考

  1. iterm2 配合 expect 实现 SSH 自动登陆
  2. linux expect详解(ssh自动登录,部署)