【问题标题】:Perl: open-ing a pipe for writing but program is not "waiting" for STDINPerl:打开管道进行写入,但程序没有“等待”STDIN
【发布时间】:2012-07-28 10:49:52
【问题描述】:

我正在尝试从 perl 脚本运行程序。 我将 STDOUT 和 STDERR 重定向到两个不同的文件。 我正在运行的程序要求输入密码,我尝试将其打印到进程句柄,但这不起作用,因为程序会立即打印身份验证错误,警告我没有向 STDIN 写入任何内容。

我使用的代码是这样的:

my $s = qq(some_program > someprogram.out 2> someprogram.err);
open(my $f, "|$s") or die "Couldn't run program: $! $?";
# print `cat someprogram.out`; # An error has already been printed here!
print $f "password\n";
close $f or die "$!: $?";

我在 perl 调试器中运行了这个,发现当调试器运行 open 行时,我可以运行注释掉的打印行,并且错误已经在输出文件中。

那么,我忘记做什么才能让它发挥作用? 如何告诉 open “等待 STDIN”?

---更新!

我在命令行中做了这样的测试:

echo password | some_program

并且打印了验证错误。所以看起来 some_program 实际上不是从 STDIN 读取,而是从 tty 读取。

有没有办法打印到 tty 以便程序可以在 Perl 中从那里读取密码?

【问题讨论】:

  • 您确定some_program 正在从标准输入读取密码吗?如果some_program 是 ssh,举一个例子,它可能试图从终端读取,这不一定与标准输入相同。
  • 嗨,暴徒。我不确定,但看起来情况就是这样。我有什么选择?
  • Ssh 不能很好地与您的管道配合使用 - 使用 Expect。
  • @mob @Len 我的意思是“看起来是这种情况”是some_program 不是从 STDIN 读取并从终端执行它;并不是说它是 ssh。我在命令行中进行了这样的测试:echo password | some_program 并出现身份验证错误。所以程序没有从 STDIN 读取。

标签: perl pipe stdout stdin


【解决方案1】:

考虑到some_program 是一个在其命令行上接受密码的bash 脚本(Shell),这可以使用perl 中的system 调用来完成。系统调用,即 Perl 中的程序执行不会因为密码而停止,最好的办法是在使用系统调用调用程序之前询问用户密码。使用反引号来执行系统调用,如下所示;

my $outfile="/path/to/someprogram.out";
my $errfile="/path/to/someprogram.err";
print "Enter password:\n";
$passwd=<>;
print "some_program $passwd\n";
`some_program $passwd > $outfile 2> $errfile`;

或使用system();

my $outfile="/path/to/someprogram.out";
my $errfile="/path/to/someprogram.err";
print "Enter password:\n";
$passwd=<>;
my $command="some_program $passwd > $outfile 2> $errfile";
print "$command\n";
system($command);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-24
    • 1970-01-01
    • 2014-08-10
    • 1970-01-01
    相关资源
    最近更新 更多