Как извлечь IP-адрес из успешной команды ping?

942
Samuel Pauk

С большой помощью другого пользователя я смог вырезать символы из одного вывода из CMD. Затем я добавил свою следующую часть кода, где он оставил меня с переменной _3octet. Мой код сканирует все IP-адреса, связанные со шлюзом, к которому подключен компьютер, и фиксирует только те, которые имеют ответ. Оттуда я получаю список IP-адресов, которые ответили.

Reply from 192.168.1.67: bytes=32 time=288ms TTL=64  Reply from 192.168.1.72: bytes=32 time<1ms TTL=128  Reply from 192.168.1.73: bytes=32 time=16ms TTL=64  Reply from 192.168.1.75: bytes=32 time<1ms TTL=128  Reply from 192.168.1.76: bytes=32 time=155ms TTL=64  Reply from 192.168.1.88: bytes=32 time=1ms TTL=255 

Оттуда я хочу получить только IP-адреса, поэтому исключаю все, кроме «192.168.1. #», Для использования в будущей части программы. Аналогично начальной части кода с _3octetпеременной. Вот мой код

@echo off setlocal setlocal enabledelayedexpansion rem throw away everything except the IPv4 address line  for /f "usebackq tokens=*" %%a in (`ipconfig ^| findstr /i "ipv4"`) do ( rem we have for example "IPv4 Address. . . . . . . . . . . : 192.168.42.78" rem split on : and get 2nd token for /f delims^=^:^ tokens^=2 %%b in ('echo %%a') do ( rem we have " 192.168.42.78" rem split on . and get 4 tokens (octets) for /f "tokens=1-4 delims=." %%c in ("%%b") do ( set _o1=%%c set _o2=%%d set _o3=%%e set _o4=%%f rem strip leading space from first octet set _3octet=!_o1:~1!.!_o2!.!_o3!. echo !_3octet! ) ) ) cd C:\Windows for /l %%i IN (1,1,254) do ping -n 1 !_3octet!%%i | for /f delims^=^:^ tokens^=1 %%g in (find /i "bytes=32") do ( for /f "tokens=1-4 delims=." %%j in ("%%g") do ( set _o1=%%j set _o2=%%k set _o3=%%l set _o4=%%m set _4octet=!_o1:~11!.!_o2!.!_o3!.!_o4! echo !_4octet! ) ) endlocal 

Я получаю : was unexpected at this time.в качестве вывода несколько раз. Что говорит мне, что он пытается пинговать каждый адрес 1-254, а не те, которые приходят в ответ. Излишне говорить, что мой код не работает, как я надеялся.

Я планировал использовать этот окончательный список IP-адресов в этом коде: shutdown -r -m \\192.168.1.1 -t 10для выключения компьютеров, подключенных к шлюзу.

Если это вообще сбивает с толку, дайте мне знать. Спасибо.

2
`for / l %% i в (1,1254) do ping -n 1! _3octet! %% i do (для / f" delims =: tokens = 1 "%% g in (find / i" bytes = 32 " ) `Это выглядит как" Плохой параметр do. " Samuel Pauk 8 лет назад 0

1 ответ на вопрос

2
DavidPostill

I want to grab only the IP addresses from the successful pings

I'm not going to try and fix the 2nd part of your batch file, it is easier to write it from scratch.

Use the following batch file (test.cmd):

@echo off setlocal setlocal enabledelayedexpansion rem throw away everything except the IPv4 address line for /f "usebackq tokens=*" %%a in (`ipconfig ^| findstr /i "ipv4"`) do ( rem we have for example "IPv4 Address. . . . . . . . . . . : 192.168.42.78" rem split on : and get 2nd token for /f delims^=^:^ tokens^=2 %%b in ('echo %%a') do ( rem we have " 192.168.42.78" rem split on . and get 4 tokens (octets) for /f "tokens=1-4 delims=." %%c in ("%%b") do ( set _o1=%%c set _o2=%%d set _o3=%%e set _o4=%%f rem strip leading space from first octet set _3octet=!_o1:~1!.!_o2!.!_o3!. echo !_3octet! ) ) ) for /l %%i in (1,1,254) do ( rem do the ping and grab the 3rd token (ip address) if it succeeds (TTL= is found) for /f "usebackq tokens=3" %%j in (`ping -n 1 !_3octet!%%i ^| find "TTL="`) do ( rem we have ip address with a trailing : rem split on . and get the 4th token (last octet) rem we don't need the first 3 as they are already in !_3octet! for /f "tokens=4 delims=." %%k in ("%%j") do ( set _o4=%%k rem strip trailing : from last octet set _4octet=!_o4:~0,-1! echo !_4octet! ) ) ) endlocal 

Notes:

  • The value you want is saved in !_3octet!!_4octet! where

    • !_3octet! is the same as before

    • !_4octet! is the last octet (you don't need two extract the first 3 octets twice!)

  • You don't need cd C:\Windows

  • One of the IP addresses will be your gateway (router) address, you probably don't want to try and run shutdown on the gateway!


Further Reading

  • An A-Z Index of the Windows CMD command line - An excellent reference for all things Windows cmd line related.
  • enabledelayedexpansion - Delayed Expansion will cause variables to be expanded at execution time rather than at parse time.
  • for /f - Loop command against the results of another command.
  • ipconfig - Configure IP (Internet Protocol configuration)
  • set - Display, set, or remove CMD environment variables. Changes made with SET will remain only for the duration of the current CMD session.
  • setlocal - Set options to control the visibility of environment variables in a batch file.
  • variables - Extract part of a variable (substring).
Это имеет большой смысл! Большое спасибо! Samuel Pauk 8 лет назад 0
@SamuelPauk Я ухожу спать (сейчас час ночи). Если это не работает как есть (вполне возможно, так как это сложный анализ, и у меня нет сети, чтобы проверить это), пожалуйста, дайте мне знать, и я посмотрю на это завтра. DavidPostill 8 лет назад 0

Похожие вопросы