【问题标题】:Can I use a heredoc to enter a password in bash?我可以使用heredoc在bash中输入密码吗?
【发布时间】:2011-04-17 07:36:07
【问题描述】:

我知道 RSA 身份验证,但出于我的目的,我想使用 heredoc 来指定密码。我想要类似下面的东西,但我无法让它工作。这甚至可能吗?

#!/bin/bash
echo -n "Enter Password: "
read -s password
ssh myhost << EOL
$password
echo "I'm logged onto myhost"
EOL
echo done

这是我尝试后得到的结果:

$ ./testssh 
Enter Password: 
Pseudo-terminal will not be allocated because stdin is not a terminal.
user@myhost's password: 
Warning: No xauth data; using fake authentication data for X11 forwarding.
Warning: no access to tty (Bad file descriptor).
Thus no job control in this shell.
mypassword: Command not found.
I'm logged onto myhost
done

编辑:

根据 bmargulies 的回答,我重新编写了我的脚本并提出了以下内容:

#!/bin/bash
echo -n "Enter the Host: "
read HOST
echo -n "Enter Username: "
read USER
echo -n "Enter Password: "
read -s PASS
VAR=$(expect -c "
spawn ssh $USER@$HOST
expect \"password:\"
send \"$PASS\r\"
expect \">\"
send \"ls\r\"
send \"echo 'I\'m on $HOST'\r\"
expect -re \"stuff\"
send \"logout\"
")
echo -e "\n\n\n========"
echo VAR = "$VAR"
echo done

【问题讨论】:

  • 引用您的变量以保留换行符:echo VAR = "$VAR"

标签: bash ssh expect heredoc


【解决方案1】:

读取密码的程序通常会专门打开 /dev/tty 来阻止重定向。在这种情况下,您需要的工具是“expect”,它将在伪 tty 后面运行一个。

【讨论】:

  • @B Johnson 从字面上看,自从我使用 expect 以来已经有好几年了。我看到丹尼斯在细节方面帮助了你。
  • 请记住,Expect 是一种通用语言,它可以完成 bash 所做的所有事情,而且可以说更容易。我们这些选择编写 Expect 脚本而不是 Expect-embedded-uncomfortably-in-bash 的人避免了上面示例中明显的许多“引用地狱”。
【解决方案2】:

如果你在 w/perl 中混入,你可以做一些“干净”的事情(从不需要引用的角度来看):

#!/bin/bash
cmd="ssh myhost << EOL"
echo -n "Enter Password: "
read -s password
# answer password prompt
#   note we use ctl-A as our quote delimeter around the password so we run
#   no risk of it escaping quotes
script='
use Expect;
use ysecure;
my $exp = new Expect;
$exp->raw_pty(1);
$exp->spawn(q|<CMD>|);
$exp->expect(30,">");
$exp->send(q^A<PASSWORD>^A . "\n");
$exp->soft_close();
$exp->exitstatus() && die;
'

script=${script//<CMD>/$cmd}
script=${script//<PASSWORD>/$password}

perl -e "$script"

【讨论】:

    猜你喜欢
    • 2011-01-21
    • 2015-02-21
    • 2016-10-28
    • 2020-02-12
    • 2020-04-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-29
    相关资源
    最近更新 更多