我想在R中创建一个ping给定网站的脚本.我没有找到任何有关此特定信息的信息.
首先,我需要的是有关网站是否响应ping的信息.
有没有人有关于现有脚本的信息或最适合使用的包?
Jor*_*eys 19
我们可以使用一个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
Run Code Online (Sandbox Code Playgroud)
如果要捕获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"
Run Code Online (Sandbox Code Playgroud)
使用该选项intern = TRUE
可以将输出保存在向量中.我把它留给读者作为练习来重新安排它以获得一些不错的输出.
小智 9
RCurl::url.exists
适用于localhost(ping并不总是)并且速度比RCurl::getURL
.
> library(RCurl)
> url.exists("google.com")
[1] TRUE
> url.exists("localhost:8888")
[1] TRUE
> url.exists("localhost:8012")
[1] FALSE
Run Code Online (Sandbox Code Playgroud)
请注意,可以设置超时(默认情况下相当长)
> url.exists("google.com", timeout = 5) # timeout in seconds
[1] TRUE
Run Code Online (Sandbox Code Playgroud)