在Bash脚本中使用Expect为SSH命令提供密码 [英] Use Expect in a Bash script to provide a password to an SSH command

查看:106
本文介绍了在Bash脚本中使用Expect为SSH命令提供密码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在Bash脚本中使用Expect提供SSH密码.提供密码是可行的,但是我并没有像应该的那样最终进入SSH会话.它回到了Bash的海峡.

I'm trying to use Expect in a Bash script to provide the SSH password. Providing the password works, but I don't end up in the SSH session as I should. It goes back strait to Bash.

我的脚本:

#!/bin/bash

read -s PWD

/usr/bin/expect <<EOD
spawn ssh -oStrictHostKeyChecking=no -oCheckHostIP=no usr@$myhost.example.com'
expect "password"
send "$PWD\n"
EOD
echo "you're out"

我的脚本的输出:

spawn ssh -oStrictHostKeyChecking=no -oCheckHostIP=no usr@$myhost.example.com
usr@$myhost.example.com's password: you're out

我想拥有我的SSH会话,并且仅在退出时才返回我的Bash脚本.

I would like to have my SSH session and, only when I exit it, to go back to my Bash script.

之所以在Expect之前使用Bash是因为我必须使用菜单.我可以选择要连接的单元/设备.

The reason why I am using Bash before Expect is because I have to use a menu. I can choose which unit/device to connect to.

对于那些想回复我应该使用SSH密钥的人,请弃权.

推荐答案

混合Bash和Expect不是达到预期效果的好方法.我会尝试仅使用Expect:

Mixing Bash and Expect is not a good way to achieve the desired effect. I'd try to use only Expect:

#!/usr/bin/expect
eval spawn ssh -oStrictHostKeyChecking=no -oCheckHostIP=no usr@$myhost.example.com

# Use the correct prompt
set prompt ":|#|\\\$"
interact -o -nobuffer -re $prompt return
send "my_password\r"
interact -o -nobuffer -re $prompt return
send "my_command1\r"
interact -o -nobuffer -re $prompt return
send "my_command2\r"
interact

bash的示例解决方案可能是:

Sample solution for bash could be:

#!/bin/bash
/usr/bin/expect -c 'expect "\n" { eval spawn ssh -oStrictHostKeyChecking=no -oCheckHostIP=no usr@$myhost.example.com; interact }'

这将等待 Enter ,然后(暂时)返回交互式会话.

This will wait for Enter and then return to (for a moment) the interactive session.

这篇关于在Bash脚本中使用Expect为SSH命令提供密码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆