我可以使用heredoc在bash中输入密码吗?

时间:2010-09-26 02:18:53

标签: bash ssh expect heredoc

我知道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

2 个答案:

答案 0 :(得分:4)

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

答案 1 :(得分:0)

如果你用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"