简体   繁体   English

如何使用批处理命令将主机名替换为网络驱动器路径中的IP地址

[英]How to replace hostname with IP address in a network drive path using batch command

set SourceDir=\\my_server\path    

if "%SourceDir:~0,2%"=="\\" (
  set sourceHost= REM not sure what to do. here I need to isolate hostname
  for /f "tokens=2" %%b in ('nslookup %SourceDir%^|find /i "Address"') do set ser_ip=%%b
  REM here I need to replace my_server with %ser_ip%     
)

In this code I'm trying to replace the host-name with IP address in a network path. 在这段代码中,我试图用网络路径中的IP地址替换主机名。

  1. in the set sourceHost= REM not sure what to do. here I need to isolate hostname set sourceHost= REM not sure what to do. here I need to isolate hostname set sourceHost= REM not sure what to do. here I need to isolate hostname Line I need to isolate the hostname from the path set sourceHost= REM not sure what to do. here I need to isolate hostname行,我需要从路径隔离主机名
  2. in the REM here I need to replace my_server with %ser_ip% line need to replace host name with retrieved ip address REM here I need to replace my_server with %ser_ip%行,并用检索到的IP地址替换主机名

if the nslookup ip adress is 10.12.13.14 last result should be \\\\10.12.13.14\\path Please help me for these two lines. 如果nslookup ip地址为10.12.13.14最后一个结果应为\\\\10.12.13.14\\path请为这两行提供帮助。 Thank you! 谢谢!

I'd go with ping instead of nslookup. 我会使用ping而不是nslookup。 If there are IPv6 addresses they are more difficult to parse and ping has a -4 option. 如果有IPv6地址,则更难解析,而ping具有-4选项。
The ip is easy to extract as it is enclosed in square brackets.: ip易于提取,因为它放在方括号中。

@Echo off&SetLocal EnableExtensions EnableDelayedExpansion
set "SourceDir=\\my_server\path"
if "%SourceDir:~0,2%"=="\\" (
  for /f "delims=\" %%H in ( "%SourceDir%"
  ) Do for /f "tokens=2delims=[]" %%b in ('ping -n 1 -4 %%H^|find "["'
  ) do Set "SourceDir=!SourceDir:%%H=%%b!"
)
Echo %SourceDir%

What about this (assuming you want to stick to nslookup ): 怎么样(假设您想坚持使用nslookup ):

set "SourceDir=\\my_server\path"

if "%SourceDir:~0,2%"=="\\" (
  rem // Extract server name and splif off remaining path:
  for /F "tokens=1* delims=\" %%a in ("%SourceDir%") do set "sourceHost=%%a" & set "sourceShare=%%b"
  for /F "tokens=2" %%b in ('nslookup %SourceDir%^|find /I "Address"') do set "ser_ip=%%b"
  rem // Assemble new path by IP and former remaining path:
  echo "\\%ser_ip%\%sourceShare%"
)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM