我想使用R语言创建一个脚本,用于ping指定的网站。我没有找到R语言中关于此特定问题的任何信息。
首先,我只需要得到该网站是否响应ping请求的信息。
请问是否有现成的脚本或最适合入手的软件包?
我们可以使用 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
可以将输出保存在向量中。我把如何重新排列以获得一些合理的输出留给读者作为一个练习。
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
> library(RCurl);
> getURL("http://www.google.com")
[1] "<!doctype html><ht....
library(httr)
b <- GET("http://www.google.com")
b$status_code
[1] 200
这个问题有一个解决方案... {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)