【问题标题】:wget script to connect, wait if successful, continue if no connectionwget脚本连接,如果成功则等待,如果没有连接则继续
【发布时间】:2016-01-13 20:02:36
【问题描述】:

我必须创建一个脚本,将 wget 联系消息发送到我们网络上的所有设备。 wget 连接到一个 url,这会触发端点联系服务器。

我遇到的问题是我需要能够将命令发送到网络上的每个 IP 地址,如果连接成功,请注意 30 秒,然后转到列表中的下一个 url。但是,如果连接不成功,我希望脚本继续前进到下一个 url 而不会暂停。

目前,我正在使用 bash 脚本发送命令,其中 url 之间有一个 pause=30,连接尝试设置为 1,超时设置为 1。这适用于成功的连接,但它也挂在不是的地址上。

有什么建议可以让我暂停成功并在死地址超时后继续前进吗?

这是我当前正在运行的命令,

wget --connect-timeout=1 --tries=1 http://xx.xx.xx.xx:8085/contact_dls.html/ContactDLS
睡觉 30
wget --connect-timeout=1 --tries=1 http://xx.xx.xx.xx:8085/contact_dls.html/ContactDLS
等等等等等等

谢谢

【问题讨论】:

  • 欢迎来到 SO,请展示您的编码工作。

标签: bash perl wget


【解决方案1】:

您不需要 wget 来完成这项任务 - 一切都可以在 Perl 中完成。

只需使用如下代码:

use LWP::UserAgent;
use HTTP::Request;

my $ua = new LWP::UserAgent;
$ua->timeout(1);
my $req = new HTTP::Request(GET => $url);
my $res = $ua->request($req);
if ($res->is_success()) {
    print("Connection to '$url' was OK");
    sleep(30);
} else {
    print("Cannot access '$url'");
    sleep(1);
}

这将访问您的网址,但会在 1 秒后超时。

【讨论】:

  • 你好,这会点击 url 并在一秒钟后继续,但如果连接正常,我需要添加 30 秒的暂停,但如果设备关闭/响应,我需要添加 1 秒的暂停。谢谢,李
  • 只需检查$res->is_success() - 我将其添加到代码 sn-p
  • 太棒了,我明天回到办公室时会试试这个。谢谢!
【解决方案2】:

我可能会将 url 加载到一个数组中并遍历该数组。像这样的

#!/usr/bin/perl

use warnings;
use strict;

my @urls = qw(test.com url.com 123abc.com fail.aa);

foreach my $url (@urls){
    my $check = `wget --server-response $url 2>&1 | grep HTTP/ | awk '{print \$2}'`;
    #if there is a successful response you can set the sleep(3) to sleep(30) for your instance.
    if($check){
        print "Found $url -- sleeping 3 seconds\n";
        sleep(3);
    }
    else{
        print "$url does not exist\n";
        #If the url does not exist or respond it will move on to the next item in the array.  You could add a sleep(1) before the next for a 1 second pause
        next;
    }
}

当然,这是假设您使用的是 linux。网址也可以通过另一种方式加载,我不知道您当前的脚本是如何获取它们的。以上是一个例子,你当然需要调整以适应你的环境

【讨论】:

  • 您好,谢谢,我们使用的是linux环境,我明天看看试试,谢谢!
  • 我在上面的代码中添加了 cmets,以便更清楚地了解我在做什么
  • 嗨 Ed,我已经使用了你的代码并添加了上面的 url,中间有一个空格,当我运行脚本时它只是挂在第一个 url 上,并且在睡眠时间之后永远不会继续.有任何想法吗?谢谢!!
  • 尝试通过注释掉 if 和 else 并用一个简单的 system("wget $url"); 替换 my $check 来测试它。看看 wget 是否在做它应该做的事情。从那里我们可以扩展它
猜你喜欢
  • 1970-01-01
  • 2018-11-02
  • 1970-01-01
  • 2016-05-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-07-21
  • 2020-11-06
相关资源
最近更新 更多