级联 ssh 与 expect

cascading ssh with expect

我是 expect 命令的新手。

我正在尝试通过 server2 连接到 server1。以下脚本连接到 server2.

#!/usr/bin/expect

spawn ssh user2@server2
set prompt ":|#|\$"
interact -o -nobuffer -re $prompt return
send "password2\r"
interact

问题是如何进行。如何从 server2.

连接到 server1

基本上,To Expect,你只需要发送一些命令并得到响应。从 Expect 的角度来看,您必须生成一个 ssh 会话,然后您可以发送任何您想要的命令。 whatever 命令也可以是 ssh 命令。

方法一:

#!/usr/bin/expect
set server1 190.x.x.x
set user1 root
set pwd1 "mypwd1"
set server2 130.x.x.x
set user2 dinesh
set pwd2 "mypwd2"
spawn ssh $user2@$server2
expect "password:"
send "$pwd2\r";
expect "\$"
send "pwd\r"; # Just executing the 'pwd' command
expect "\$"
send "hostname\r" ; # Also executing 'hostname' command for your reference
expect "\$"
send "ssh $user1@$server1\r"
expect "password:"
send "$pwd1\r";
expect "# $"
send "pwd\r"
expect "# $"
send "hostname\r"
expect "# $"

方法二:

令人惊讶的是,还有一种更简单的方法。 ssh 本身将通过在其中添加 -t 标志来支持级联命令。

 ssh -t user@outerhost ssh root@innerhost

在我们的代码中应用这个逻辑,我们可以得到,

#!/usr/bin/expect
set pwd1 "mypwd1"
set pwd2 "mypwd2"
spawn ssh -t user@outerhost  ssh user@innerhost
expect "password:"
send "$pwd2\r"
expect "password:"
send "$pwd1\r";
expect "# $"
send "pwd\r"; # Just executing 'pwd' command
expect "# $"

方法 2 参考:

注意:如果您的主要目的是仅在内部主机中执行命令,而外部主机就像一个旁路,那么方法 2 更可取。