我正在尝试编写一个脚本,它将ping超过600个位置的10.x.x.185,然后导出到文本文件。我知道>>可用于附加到文本文件。 IP范围如下:10.0.1.185,一直到10.50.2.185,每次递增1。我发现问题出现在10.0.255.185 ......
奖金,如果我可以在两个不同的文件中通过并失败。 有什么想法吗?
答案 0 :(得分:0)
循环可以通过两个for /L
循环完成,并且管道输出到两个单独的文件有点棘手,但仍然可能。
@echo off
:: Get the vast majority of the IP addresses
for /L %%A in (0,1,49) do (
for /L %%B in (0,1,255) do (
(ping 10.%%A.%%B.185>nul&&echo 10.%%A.%%B.185>>success.txt)||echo 10.%%A.%%B.185>>failure.txt
)
)
:: Get the 10.50.x.185 range separately since it only goes from 0 to 2
for /L %%A in (0,1,2) do (
(ping 10.50.%%A.185>nul&&echo 10.50.%%A.185>>success.txt)||echo 10.50.%%A.185>>failure.txt
)
&&
表示“如果先前命令成功,则仅执行此部分”,而||
表示“仅在先前命令失败时才执行此操作。”
答案 1 :(得分:0)
批处理文件中迭代连续数值列表的常用方法是使用for /l
命令。在您的情况下,由于您需要两个不同的系列,您将需要两个嵌套的for /l
循环,每个八位字节一个。
但是由于内循环的差异取决于外循环的值,我将使用环境变量来定义内循环应如何对每个外部值表现。
@echo off
setlocal enableextensions enabledelayedexpansion
rem Get a carriage return into a variable to later show progress in console
for /f %%a in ('copy "%~f0" nul /z') do set "CR=%%a"
rem Define the ranges that will be used for each of the network octets
rem Values are those in for /l command: start step end
set "octetA=0 1 50"
for /l %%a in (%octetA%) do set "octetB%%a=1 1 255"
set "octetB50=1 1 2"
rem Iterate over the addresses.
rem Two streams are used to send the sucess/failure addresses to
rem the correct log file. That way we avoid having to open/write/close
rem each file for each write operation.
7>"sucess.txt" 8>"failure.txt" (
for /l %%a in (%octetA%) do for /l %%b in (!octetB%%a!) do (
rem Show current ip being tested to console
<nul set /p"=Testing 10.%%a.%%b.185!CR!"
rem Execute ping command and send the address to the
rem adecuate output stream depending on sucess/failure
( ping -n 1 10.%%a.%%b.185 2>nul | find "TTL=" >nul
) && (>&7 echo 10.%%a.%%b.185)||(>&8 echo 10.%%a.%%b.185)
)
)
echo IP address testing finished