在R中对网站进行Ping测试

18

我想使用R语言创建一个脚本,用于ping指定的网站。我没有找到R语言中关于此特定问题的任何信息。

首先,我只需要得到该网站是否响应ping请求的信息。

请问是否有现成的脚本或最适合入手的软件包?


2
关于术语的注释:ping是针对主机而不是网站的。如果有必要,您可能需要了解服务器、主机、IP、域和网站之间的区别。但对于大多数目的来说,这并不是什么大问题。 - Iterator
请注意,有些人将“ping一个网站”解释为“发送GET查询并确保返回响应代码200”。我同意这不是常见的术语,但确实存在。 - patrickmdnet
5个回答

23

我们可以使用 system2 调用来在 shell 中获取 ping 命令的返回状态。在 Windows(和可能的 Linux)上,以下命令将起作用:

ping <- function(x, stderr = FALSE, stdout = FALSE, ...){
    pingvec <- system2("ping", x,
                       stderr = FALSE,
                       stdout = FALSE,...)
    if (pingvec == 0) TRUE else FALSE
}

# example
> ping("google.com")
[1] FALSE
> ping("ugent.be")
[1] TRUE

如果您想捕获ping命令的输出,您可以将stdout = ""设置为空字符串,或者使用系统调用:

> X <- system("ping ugent.be", intern = TRUE)
> X
 [1] ""                                                         "Pinging ugent.be [157.193.43.50] with 32 bytes of data:" 
 [3] "Reply from 157.193.43.50: bytes=32 time<1ms TTL=62"       "Reply from 157.193.43.50: bytes=32 time<1ms TTL=62"      
 [5] "Reply from 157.193.43.50: bytes=32 time<1ms TTL=62"       "Reply from 157.193.43.50: bytes=32 time<1ms TTL=62"      
 [7] ""                                                         "Ping statistics for 157.193.43.50:"                      
 [9] "    Packets: Sent = 4, Received = 4, Lost = 0 (0% loss)," "Approximate round trip times in milli-seconds:"          
[11] "    Minimum = 0ms, Maximum = 0ms, Average = 0ms"         

使用选项intern = TRUE可以将输出保存在向量中。我把如何重新排列以获得一些合理的输出留给读者作为一个练习。


2
谢谢(已点赞),但它是循环的。在您的代码中,我们必须使用ping -c1(或有限次数)。 system2("ping", paste0("-c1 ",x)。链接:Ping 4次 - phili_b
它也适用于Mac。只是当ping很好(主机可用)时,该函数不会立即返回“TRUE”布尔值。但是,当ping很差(主机不可用)时,该函数会立即返回“FALSE”布尔值。 - Abel Callejo
phili_b 的建议解决了我在 该问题 中提到的关于函数未立即返回值 TRUE 的问题。 - Abel Callejo

11

RCurl :: url.exists 适用于本地主机(其中ping不总是适用),并且比 RCurl :: getURL 更快。

> library(RCurl)
> url.exists("google.com")
[1] TRUE
> url.exists("localhost:8888")
[1] TRUE
> url.exists("localhost:8012")
[1] FALSE

请注意,可以设置超时时间(默认情况下较长)。

> url.exists("google.com", timeout = 5) # timeout in seconds
[1] TRUE

2
如果您想查看一个网站是否响应HTTP请求,您可以使用RCurl库在R中测试一个URL,它是curl HTTP客户端库的R接口。
示例:
> library(RCurl);
> getURL("http://www.google.com")
[1] "<!doctype html><ht....

如果您想检查响应代码(如200、404等),则需要编写一个自定义函数作为getURL()的“header”选项传递。

2
获取状态码
library(httr)

b <- GET("http://www.google.com")

b$status_code

[1] 200 

2

这个问题有一个解决方案... {pingr} 前往CRAN链接.

library(pingr)

# check if domain can be reached via port 80
is_up(destination = "example.com")

## [1] TRUE


# check how domain name is resolved to ip adress
nsl("example.com")

## $answer
##          name class type   ttl          data
## 1 example.com     1    1 85619 93.184.216.34
## 
## $flags
## aa tc rd ra ad cd 
## NA NA NA NA NA NA 


# check HTTP port
pingr::ping_port("example.com", 80)


# check HTTPS port
pingr::ping_port("example.com", 443)



网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接