windows bat series 12: get all devices on the host LAN

background

         Developers often need to use windows system to manage numerous Linux servers. As far as I am concerned, due to occasional change of office locations, the router assigns different IPs to Linux hosts each time. Therefore, it is necessary to detect all device IPs in the host LAN.

Code

COLOR 0A
CLS

@ECHO Off

Title 查询局域网内在线电脑IP
@ECHO off

setlocal enabledelayedexpansion

ECHO 正在获取本机的IP地址,请稍等...
for /f "delims=: tokens=2" %%i in ('ipconfig ^| find /i "IPv4"') do set ip=%%i
echo %ip%

for /f "delims=. tokens=1,2,3,4" %%i in ("%IP%") do set range=%%i.%%j.%%k

ECHO.&ECHO 正在获取本网段内的其它在线计算机名,请稍等...
ECHO 本网段【%range%.*】内的计算机有:

for /f "delims=" %%i in ('net view') do (
    set "var=%%i"
    ::查询在线计算机名称
    if "!var:~0,2!"=="\\" (
        set "var=!var:~2!"
        ECHO !var!
        ::发送一个ping报文
        ping -n 1 !var!>nul
    )
)

ECHO.
ECHO 正在获取本网段内的其它在线计算机IP,请稍等...
for /f "skip=3 tokens=1,* delims= " %%i in ('arp -a') do ECHO IP: %%i 正在使用

ECHO.
ECHO 查询完毕,按任意键退出...
pause>nul

Code explanation

  1. The color command sets the console foreground/background color : background black, foreground green;
  2. The title command sets the title of the console;
  3. setlocal enabledelayedexpansion enables variable delay binding ;
  4. The first for loop is used to obtain the local IPv4 address. Note that the pipe symbol used in the for loop needs to be escaped: ^| ;
  5. The second for loop is used to obtain the local network segment;
  6. The third for loop processes the result of the net view command and sends a ping message to all detected hosts to form an arp record ;
  7. View the arp address resolution table;

result

to sum up

  1. Get the result of the command through a for loop, and use single quotes to enclose the command ;
  2. To process strings through a for loop, you need to use double quotes .
  3. Use of net view command and arp command;
  4. BAT string processing-string interception, replacement, etc.;

Guess you like

Origin blog.csdn.net/zhaogang1993/article/details/89818453