在Perl中将telnet与带有反引号的管道一起使用 [英] Using telnet with pipe with backticks in perl

查看:81
本文介绍了在Perl中将telnet与带有反引号的管道一起使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试测试特定服务器是否在某个端口上启动并正在运行,所以我正在使用 $result = `echo exit | telnet 127.0.0.1 9443`; print $result;

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;

我在这里使用本地主机解决隐私问题 预期的行为是它应该显示"...无法打开主机到端口9443的连接:连接失败",这样我就知道服务器未在运行.但它会打印一个空字符串

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

对此有任何帮助

推荐答案

失败消息将打印到STDERR,而反引号仅返回到STDOUT的内容.

The failure message is printed to STDERR, while backticks return only what goes to STDOUT.

您可以将STDERR流重定向到STDOUT

$result = `echo exit | telnet 127.0.0.1 9443 2>&1`; 

请参见 I/O重定向.

使用各种形式的open可以采用多种方法来完成此操作.请参见在perlfaq8中的内容.也有用于此的各种模块. Capture :: Tiny 使它变得相当简单.

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";

这为我打印


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提供了一种简单,可移植的方式来捕获几乎所有发送到STDOUT或STDERR的内容,无论它是来自Perl,来自XS代码还是来自外部程序.

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.

这篇关于在Perl中将telnet与带有反引号的管道一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆