问题
I am trying to test a specific server is up and running on a certain port so I am using
$result = `echo exit | telnet 127.0.0.1 9443`; print $result;
Here I am using localhost for privacy issues The expected behavior is that it should print "...Could not open connection to the host, on port 9443: Connect failed", this way I know that the server is not running. but it prints an empty string
Any help on this
回答1:
The failure message is printed to STDERR
, while backticks return only what goes to STDOUT
.
You can redirect the STDERR
stream to the STDOUT
stream
$result = `echo exit | telnet 127.0.0.1 9443 2>&1`;
See I/O redirection.
There are more rounded ways to do this, using various forms of open
. See it in perlfaq8. There are also various modules for this. The Capture::Tiny makes it rather easy.
use warnings 'all';
use strict;
use Capture::Tiny qw(capture);
my $cmd = 'echo exit | telnet 127.0.0.1 9443';
my ($stdout, $stderr) = capture {
system ( $cmd );
};
print "STDOUT: $stdout";
print "STDERR: $stderr";
This prints for me
STDOUT: Trying 127.0.0.1... STDERR: telnet: connect to address 127.0.0.1: Connection refused
The module has many more capabilities. From the docs
Capture::Tiny provides a simple, portable way to capture almost anything sent to STDOUT or STDERR, regardless of whether it comes from Perl, from XS code or from an external program.
来源:https://stackoverflow.com/questions/40080797/using-telnet-with-pipe-with-backticks-in-perl