在 Bash 脚本中使用 Expect 为 SSH 命令提供密码 [英] Use Expect in a Bash script to provide a password to an SSH command
问题描述
我正在尝试在 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
"
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
"
interact -o -nobuffer -re $prompt return
send "my_command1
"
interact -o -nobuffer -re $prompt return
send "my_command2
"
interact
bash 的示例解决方案可能是:
Sample solution for bash could be:
#!/bin/bash
/usr/bin/expect -c 'expect "
" { 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屋!