我怎样才能让这个在线网站检查器工作?
How can I make this online site checker work?
我正在 Windows 上使用 CURL 创建一个在线站点检查器(告诉您它是打开还是关闭),但它似乎不起作用。
我试过在 Windows 上创建一个简单的脚本。首先,我在 statusgoogle.txt 文件中使用 curl 和输出重定向检查 Google。然后,我让 findstr 找到句子 "Connection established"。这意味着该网站是UP。 findstr 的错误代码 0 表示它找到了它要查找的内容。所以,如果它找到了它要找的东西,我会收到一条消息 "site is up"。如果没有找到,我会得到一个不同的错误代码,因此消息应该是 "site down".
问题是: 我收到两条消息。我已经尝试使用 if %errorlevel%,但它也不起作用。
此外,我想要一个包含多个网站的代码,因为我正在创建一个实际上一次检查大约 9 或 10 个网站的 bat 脚本。
curl -i http://www.google.com/ 1> statusgoogle.txt
findstr /c:"Connection established" statusgoogle.txt
if errorlevel 0 (GOTO :upwarning) else (GOTO :downwarning)
:upwarning
echo site up
:downwarning
echo site down
如果 findstr 找到字符串 "Connection established",那么我应该会收到带有 "site up" 的消息。它实际发生的是:它同时显示 "site up" 和 "site down".
消息问题在于,在您跳转到 "upwarning" 之后,您的其余代码仍将被执行。您必须在 "echo site up":
之后终止脚本curl -i http://www.google.com/ 1> statusgoogle.txt
findstr /c:"Connection established" statusgoogle.txt
if errorlevel 0 (GOTO :upwarning) else (GOTO :downwarning)
:upwarning
echo site up
goto :EOF
:downwarning
echo site down
:EOF
表示 "End Of File"。 "exit /b" 也可以。
经典if errorlevel 0
命令的误区之一,
翻译成(如果是,请参阅帮助)
if errorlevel is 0 or greater
这对于正错误级别总是正确的。
或者
- 检查
if errorlevel 1
并反转逻辑
if errorlevel 1 (GOTO :downwarning) else (GOTO :upwarning)
- 检查
%errorlevel%
的当前值if %errorlevel%==0 (GOTO :upwarning) else (GOTO :downwarning)
- 在 success/fail
&&/||
上使用条件执行
curl -i http://www.google.com/ 1> statusgoogle.txt
findstr /c:"Connection established" statusgoogle.txt &&(GOTO :upwarning)||(GOTO :downwarning)
:upwarning
echo site up
goto :eof
:downwarning
echo site down
如果您会使用 PowerShell,那将非常简单。
try {
Invoke-WebRequest "http://www.hp.com" | Out-Null
"Web site is up"
} catch {
"Web site is not up"
}