ubuntu - 与期望级联ssh

标签 ubuntu expect

我是 expect 的新手命令。

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

#!/usr/bin/expect

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

问题是如何进行。如何连接到 server1来自 server2 .

最佳答案

基本上,到 Expect ,您只需发送一些命令并获得响应。来自 Expect的观点,你必须产生一个 ssh session 然后你可以发送任何你想要的命令。任何命令也可以是 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 引用:https://stackoverflow.com/a/15161956

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

关于ubuntu - 与期望级联ssh,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30333561/

相关文章:

docker - 无法使用 docker 驱动程序启动 minikube

ruby-on-rails - 程序 'rails' 当前未安装在 Rails 应用程序文件夹的根目录中

linux - 如何使用shell脚本root登录远程机器

ubuntu - 相当于 Fedora 上的 packages.ubuntu.com

php - ubuntu litespeed php7.0 有一个奇怪的 php.ini 路径

google-chrome - Ubuntu 16.04 上的 Tensorboard 问题

tcl - 预期 Tcl 脚本 - 使用生成传递带引号的参数时出错

linux - 期望脚本在成功登录 ssh 后不发送命令

linux - 如何在期望中发送 BACKSPACE?

linux - 期望自动登录成功,但无法执行任何命令