AskOverflow.Dev

AskOverflow.Dev Logo AskOverflow.Dev Logo

AskOverflow.Dev Navigation

  • Início
  • system&network
  • Ubuntu
  • Unix
  • DBA
  • Computer
  • Coding
  • LangChain

Mobile menu

Close
  • Início
  • system&network
    • Recentes
    • Highest score
    • tags
  • Ubuntu
    • Recentes
    • Highest score
    • tags
  • Unix
    • Recentes
    • tags
  • DBA
    • Recentes
    • tags
  • Computer
    • Recentes
    • tags
  • Coding
    • Recentes
    • tags
Início / computer / Perguntas / 1833886
Accepted
Rootz
Rootz
Asked: 2024-03-06 01:25:56 +0800 CST2024-03-06 01:25:56 +0800 CST 2024-03-06 01:25:56 +0800 CST

O que há de errado com esse código de lote?

  • 772

Alguém pode ajudar como descobrir o que há de errado com esse código? Basicamente, é apenas uma parte do script que fiz para consertar algumas coisas e posso obter o resultado de "Status DCHP" que fornece um resultado em branco ou uma resposta inválida, como um display DHCP lan NO. Não consigo usar o PowerShell em algumas máquinas, então preciso usar lote.

basicamente, o código usa psexec para conectar um computador remoto na LAN e executar o script baseado em DHCP ou IP estático e consertar alguma coisa, então eu me conecto corretamente usando o sccm remoto.

@echo off
setlocal enabledelayedexpansion

:: Disabling UAC
echo Disabling UAC
reg add "HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System" /v "EnableLUA" /t REG_DWORD /d 0 /f >nul
reg add "HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System" /v "ConsentPromptBehaviorAdmin" /t REG_DWORD /d 0 /f >nul

:: Listing all network adapters
echo List all network adapters
netsh interface show interface
echo.

:: Getting the name of the network adapters
echo Enter the interface name you want to fix:
set /p adapterName=

:: Validating the user input
if not defined adapterName (
    echo You must enter a network adapter name!
    exit /b
)

:: Running ipconfig and storing the output in a temporary file
echo Run ipconfig and store the output in a temporary file
ipconfig > ipconfig.txt
REM ipconfig /all > dhcp.txt
netsh interface ip show addresses name="%adapterName%" > dhcp.txt

:: Parsing the IP address, subnet mask, and default gateway from the output
for /f "tokens=2 delims=:" %%A in ('findstr /i /c:"IPv4 Address" ipconfig.txt') do (
    set "ip=%%A"
    set "ip=!ip: =!"
)

for /f "tokens=2 delims=:" %%B in ('findstr /i /c:"Subnet Mask" ipconfig.txt') do (
    set "mask=%%B"
    set "mask=!mask: =!"
)

for /f "tokens=2 delims=:" %%C in ('findstr /i /c:"Default Gateway" ipconfig.txt') do (
    set "gateway=%%C"
    set "gateway=!gateway: =!"
)

for /f "tokens=2 delims=:" %%D in ('findstr /i /b /c:"DHCP Enabled" dhcp.txt') do (
    set "DHCP=%%D"
    set "DHCP=!DHCP: =!"
    if /i "!DHCP!"=="Yes" (
        set "DHCPStatus=Yes"
    ) else (
        set "DHCPStatus=No"
    )
)

if /i "%DHCPStatus%"=="Yes" (
    goto :dhcp
) else (
    goto :static
)

:dhcp
echo.
echo Actual network configuration of host
echo IP Address: !ip!
echo Subnet Mask: !mask!
echo Default Gateway: !gateway!
echo DHCP: !DHCPStatus!
echo.

:static
echo.
echo Actual network configuration of host
echo IP Address: !ip!
echo Subnet Mask: !mask!
echo Default Gateway: !gateway!
echo DHCP: !DHCPStatus!
echo.

erro

Código inteiro:

@echo off && setlocal enabledelayedexpansion

set "_xptoKey=HKLM\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters"
set "_ipv6Key=HKLM\SYSTEM\CurrentControlSet\Services\Tcpip6\Parameters"
set "_UACKey=HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System"

echo/Disabling UAC & for %%i in =;( EnableLUA,ConsentPromptBehaviorAdmin 
    );= do >nul reg add "!_UACKey!" /v "%%~i" /t REG_DWORD /d 0 /f

:: Listing all network adapters interfaces
echo/List all network adapters & netsh interface show interface

:: Getting the name of the network adapters and validating the user input
echo/ & set /p "_adapterName=Enter the interface name you want to fix: " || =;(
     echo You must enter a network adapter name! & exit /b );=

:: Parsing the IP address, subnet mask, and default gateway from the output
for /f "tokens=1-2 delims=:(" %%A in =;('
     ipconfig /all ^| findstr /ic:"IPv4"
    ');= do set "_ip=%%~B" && call set "_ip=%%_ip: =%%"

for /f "tokens=1-2 delims=:(" %%A in =;('
     ipconfig /all ^| findstr /ic:"Sub"
    ');= do set "_Sub=%%~B" && call set "_Sub=%%_Sub: =%%"
    
for /f "tokens=1-2 delims=:(" %%A in =;('
     ipconfig /all ^| findstr /ic:"Gate"
    ');= do set "_Gate=%%~B" && call set "_Gate=%%_Gate: =%%"

:: Showing the current settings obtained
echo/Actual Network Configuration of Host
echo/     IP Address: !_ip!
echo/    Subnet Mask: !_sub!
echo/Default Gateway: !_gate!
echo/           DHCP: !_dhcp! & echo/ 

:: Applying configurations and executing common commands
echo/Disabling & =;( 
     echo/Disabling network adapter... Please Wait... >con
     netsh interface set interface "Wi-Fi" disable 
     timeout /nobreak 6 | echo/ Enabling network adapter... Please wait... >con
     netsh interface set interface "Wi-Fi" enable
     timeout /nobreak 6 | echo/ >con 
    );= >nul 2>&1

:: Set the IP address, subnet mask, gateway, DNS servers if the current IP is not static
netsh interface ip show addresses name="!_adapterName!" | findstr "DHCP.*Yes" >nul || =;(
     echo/Configuring the network settings...
     netsh interface ipv4 set address name="!_adapterName!" source=static address="!_ip!" mask="!_sub!" gateway="!_gate!"
     netsh interface ipv4 set dns name="!_adapterName!" static 1.1.1.1 validate=no
     netsh interface ipv4 add dns name="!_adapterName!" 1.0.0.1 index=2 validate=no
     netsh interface ipv4 delete dnsservers name="!_adapterName!" 1.2.3.4 validate=no
    );=

echo/Adding DNS sufix: [xpto.pt + xpto2.pt] 
reg add "!_xptoKey!" /f /v SearchList /t REG_SZ /d "xpto.pt,xpto2.pt" >nul

echo/Disable TCP/IP v6 for the network adapter...
reg add "!_ipv6Key!" /v "DisabledComponents" /t REG_DWORD /d 0xffffffff /f >nul

for %%i in =;( "set global randomizeidentifier=disabled","isatap set state state=disabled",
     "6to4 set state state=disabled","set privacy state=disable","set teredo disable"
    );= do netsh interface IPV6 %%~i 

echo/Testing Network Connection (DHCP^)...
ping -n 4 10.0.25.80 | findstr "ms loss" | sort /Uniq

echo/Running Flushdns and Registerdns... & >nul =;( 
     ipconfig /flushdns & ipconfig /registerdns 
    );= 2>&1 | findstr "IP Cache" | Sort /Uniq

timeout /nobreak 5 | endlocal & goto :eof
batch
  • 3 3 respostas
  • 95 Views

3 respostas

  • Voted
  1. DavidPostill
    2024-03-06T02:52:53+08:002024-03-06T02:52:53+08:00

    "DCHP Status" fornece um resultado em branco

    findstr /i /b /c:"DHCP Enabled" dhcp.txtestá quebrado como está escrito.

    • /bPadrão de correspondência se estiver no início de uma linha.
    • /c:"string"Use string como uma string de pesquisa literal (pode incluir espaços).

    No entanto:

    Para corresponder uma frase/sentença inteira ou para usar expressões regulares, use as opções /C e /R .

    (ênfase minha)

    Então você precisa remover /b ou adicionar /r.

    Remover /bfunciona para mim:

    F:\test>type dhcp.txt
    
    Configuration for interface "Wireless Network Connection"
        DHCP enabled:                         Yes
        IP Address:                           192.168.188.250
        Subnet Prefix:                        192.168.188.0/24 (mask 255.255.255.0)
        Default Gateway:                      192.168.188.251
        Gateway Metric:                       0
        InterfaceMetric:                      25
    
    
    F:\test>findstr /i /c:"DHCP Enabled" dhcp.txt
        DHCP enabled:                         Yes
    
    F:\test>
    

    Você também precisa alterar seu forloop da seguinte maneira:

    F:\test>type test.cmd
    @echo off
    setlocal enabledelayedexpansion
    for /f "tokens=3" %%D in ('findstr /i /c:"DHCP Enabled" dhcp.txt') do (
        if /i "%%D"=="Yes" (
            set "DHCPStatus=Yes"
        ) else (
            set "DHCPStatus=No"
        )
        echo !DHCPStatus!
      )
    endlocal
    
    F:\test>test
    Yes
    
    F:\test>
    

    Leitura adicional

    • Um índice AZ da linha de comando do Windows CMD | SS64.com
    • Comandos CMD do Windows (categorizados) - Windows CMD - SS64.com
    • Findstr - Pesquisa de strings - Windows CMD - SS64.com
    • 1
  2. Danijel
    2024-03-06T02:44:30+08:002024-03-06T02:44:30+08:00

    Seu problema é como você usa delims, ou seja, você pode ver isso;

    /B         Matches pattern if at the beginning of a line.
    

    mas então você teria que "respeitar" sua própria produção e realmente seguir em frente;

    for /f "tokens=2 delims=:" %%D in ('findstr /i /b /c:"    DHCP enabled" dhcp.txt') do (
    

    PS: isso funcionará perfeitamente;

    for /f "tokens=2 delims=:" %%D in ('findstr /i /b /c:"    DHCP enabled" dhcp.txt') do (
        set "DHCPStatus=%%D"
    )
    
    • 0
  3. Best Answer
    Io-oI
    2024-03-07T05:51:46+08:002024-03-07T05:51:46+08:00

    Você não precisa criar arquivos temporários e ter que excluí-los após manipulá-los para obter o resultado desejado, você pode usar um forloop doble para obter suas strings diretamente da saída do comando, e também observando que o :staticrótulo reproduz basicamente o mesmo que a :DHCPetiqueta, para que você possa usar echo variablessem :specificetiqueta para :each...


    @echo off && setlocal enabledelayedexpansion
    
    set "_xptoKey=HKLM\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters"
    set "_UACKey=HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System"
    
    echo/Disabling UAC & for %%i in =;( EnableLUA,ConsentPromptBehaviorAdmin 
        );= do >nul reg add "!_UACKey!" /v "%%~i" /t REG_DWORD /d 0 /f
        
    echo/List all network adapters & netsh interface show interface & echo/
    
    :: Getting the name of the network adapters and validating the user input
    echo/ & set /p "_adapterName=Enter the interface name you want to fix: " || =;(
         echo You must enter a network adapter name! & exit /b );=
    
    :: Parsing the IP address, subnet mask, and default gateway from the output    
    for %%G in =;( IPv4,Sub,Gate );= do for /f "tokens=1-2 delims=:(" %%A in =;('
         ipconfig /all ^| Find "%%~G" ');= do set "_%%~G=%%~B" && call set "_%%~G=%%_%%~G: =%%"
    
    :: Showing the current settings obtained
    echo/ & echo/Actual network configuration of host
    echo/     IP Address: !_IPv4! &  echo/    Subnet Mask: !_Sub!
    echo/Default Gateway: !_Gate! &  echo/           DHCP: !_DHCP! & echo/ 
    
    :: Applying configurations and executing common commands
    echo/Disabling & =;( 
         echo/Disabling network adapter... Please Wait... >con
         netsh interface set interface "Wi-Fi" disable 
         timeout /nobreak 6 | echo/ Enabling network adapter... Please wait... >con
         netsh interface set interface "Wi-Fi" enable
         timeout /nobreak 6 | echo/ >con 
        );= >nul 2>&1
    
    :: Set the IP address, subnet mask, gateway, DNS servers if the current IP is not static
    netsh interface ip show addresses name="!_adapterName!" | findstr "DHCP.*Yes" >nul || =;(
         echo/Configuring the network settings...
         netsh interface ipv4 set address name="!_adapterName!" source=static address="!_ip!" mask="!_sub!" gateway="!_gate!"
         netsh interface ipv4 set dns name="!_adapterName!" static 1.1.1.1 validate=no
         netsh interface ipv4 add dns name="!_adapterName!" 1.0.0.1 index=2 validate=no
         netsh interface ipv4 delete dnsservers name="!_adapterName!" 1.2.3.4 validate=no
        );=
    
    >nul =;(
         echo/Adding DNS sufix: [xpto.pt + xpto2.pt] >con:
         echo/reg add "!_xptoKey!" /f /v SearchList /t REG_SZ /d "xpto.pt,xpto2.pt" 
        
         echo/Disable TCP/IP v6 for the network adapter... >con:
         echo/reg add "!_xptoKey:p\=p6\!" /v "DisabledComponents" /t REG_DWORD /d 0xffffffff /f 
        );= 2>&1
    
    for %%i in =;( "set global randomizeidentifier=disabled","isatap set state state=disabled",
         "6to4 set state state=disabled","set privacy state=disable","set teredo disable"
        );= do netsh interface IPV6 %%~i 
    
    echo/Testing Network Connection (DHCP^)...
    ping -n 4 10.0.25.80 | findstr "ms loss" | sort /Uniq
    
    echo/Running /Flushdns and /RegisterDNS... & >nul =;( 
         ipconfig /flushdns & ipconfig /registerdns 
        );= 2>&1 | findstr "IP Cache" | Sort /Uniq
    
    timeout /nobreak 5 | endlocal & goto :eof
    

    • Ou alternativa mais próxima do seu código original ...

    
    @echo off && setlocal enabledelayedexpansion
    
    echo/Disabling UAC & for %%i in =;( EnableLUA,ConsentPromptBehaviorAdmin 
        );= do >nul reg add "HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System" /v "%%~i" /t REG_DWORD /d 0 /f
    
    :: Listing all network adapters
    echo/List all network adapters & netsh interface show interface
    
    :: Getting the name of the network adapters and validating the user input
    echo/ & set /p "_adapterName=Enter the interface name you want to fix: " || =;(
         echo You must enter a network adapter name! & exit /b );=
    
    :: Parsing the IP address, subnet mask, and default gateway from the output
    for /f "tokens=1-2 delims=:(" %%A in =;('
         ipconfig /all ^| findstr /ic:"IPv4"
        ');= do set "_ip=%%~B" && call set "_ip=%%_ip: =%%"
    
    for /f "tokens=1-2 delims=:(" %%A in =;('
         ipconfig /all ^| findstr /ic:"Sub"
        ');= do set "_Sub=%%~B" && call set "_Sub=%%_Sub: =%%"
        
    for /f "tokens=1-2 delims=:(" %%A in =;('
         ipconfig /all ^| findstr /ic:"Gate"
        ');= do set "_Gate=%%~B" && call set "_Gate=%%_Gate: =%%"
    
    netsh interface ip show addresses name="%_adapterName%" | findstr "DHCP.*Yes" >nul && =;(
        set "_dhcp=Yes" && goto :dhcp );= || set "_dhcp=No" && goto :static
    
    :dhcp
    echo/
    echo/Actual network configuration of host
    echo/     IP Address: !_ip!
    echo/    Subnet Mask: !_sub!
    echo/Default Gateway: !_gate!
    echo/           DHCP: !_dhcp! & echo/ 
    endlocal & goto :eof
    
    :static
    echo/
    echo/Actual network configuration of host
    echo/     IP Address: !_ip!
    echo/    Subnet Mask: !_sub!
    echo/Default Gateway: !_gate!
    echo/           DHCP: !_dhcp!
    echo/           DHCP: !_dhcp! & echo/ 
    endlocal & goto :eof
    

    Observe que você está atualmente executando um comando redirecionando a saída e submetendo esta saída para um arquivo para manipulação em um loop e verificando se tem sim/não na linha para definir esta variável e trazer a execução para um controle de fluxo ( goto :DHCPou goto :staticrótulo) , mas uma linha faz isso sem a necessidade de toda a etapa acima.

    Veja um uso de findstrpara uma condição com uma multiplicidade de strings a ser pesquisada em uma linha/saída ( findstr String1.*String2) do seu comando e redirecionada para um operador que definirá diretamente sua variável dependendo se ela resulta em verdadeiro/sucesso ( &&) ou falso /falha ( ||):

    Se a string DHCP+ um ou mais caracteres ( .*) + Yesfor encontrada na mesma linha retorna true, a execução seguinte será a que vem depois && (executes these commands), mas se a execução retornar false, as múltiplas strings não são encontradas na mesma linha, o operador || (execute this block):

    netsh interface ip show addresses name="%_adapterName%" | findstr "DHCP.*Yes" >nul && =;(
        set "_dhcp=Yes" && goto :dhcp );= || set "_dhcp=No" && goto :static

    Por fim, considere sempre adicionar um Endlocalao usar Setlocal, especialmente se houver múltiplas execuções do mesmo bat sem fechar a sessão atual.


    PS. : Considere a resposta de DavidPostill♦ , o núcleo de sua variável indefinida foi o uso de /Bem seu findstrcomando ....


    Recursos adicionais:

    • Goto :lable /?
    • Findstr /?
    • For /?
    • For /F /?
      • For /F commands
    • Execução Condicional
      • ||e&&
    • Redirecionamento de Comandos
      • |, <, >, 2>, etc
    • Para onde GOTO :EOFretorna?
    • Set variable=variable:substrings| DOS - Manipulação de Strings
    • Como o interpretador de comandos do Windows [ cmd.exe] analisa scripts
    • -1

relate perguntas

  • Contar arquivos em uma pasta e subpastas com extensão específica (.mp4) na linha de comando

  • Arquivo de lote do Windows para minimizar todas as janelas abertas

  • Lote do Windows para alterar o tempo limite de todos os pools de aplicativos do IIS

  • Linha de comando: comando geral para renomear arquivo

  • Qual seria o equivalente em lote do argumento "pass" do Python?

Sidebar

Stats

  • Perguntas 205573
  • respostas 270741
  • best respostas 135370
  • utilizador 68524
  • Highest score
  • respostas
  • Marko Smith

    Como posso reduzir o consumo do processo `vmmem`?

    • 11 respostas
  • Marko Smith

    Baixar vídeo do Microsoft Stream

    • 4 respostas
  • Marko Smith

    O Google Chrome DevTools falhou ao analisar o SourceMap: chrome-extension

    • 6 respostas
  • Marko Smith

    O visualizador de fotos do Windows não pode ser executado porque não há memória suficiente?

    • 5 respostas
  • Marko Smith

    Como faço para ativar o WindowsXP agora que o suporte acabou?

    • 6 respostas
  • Marko Smith

    Área de trabalho remota congelando intermitentemente

    • 7 respostas
  • Marko Smith

    O que significa ter uma máscara de sub-rede /32?

    • 6 respostas
  • Marko Smith

    Ponteiro do mouse movendo-se nas teclas de seta pressionadas no Windows?

    • 1 respostas
  • Marko Smith

    O VirtualBox falha ao iniciar com VERR_NEM_VM_CREATE_FAILED

    • 8 respostas
  • Marko Smith

    Os aplicativos não aparecem nas configurações de privacidade da câmera e do microfone no MacBook

    • 5 respostas
  • Martin Hope
    Vickel O Firefox não permite mais colar no WhatsApp web? 2023-08-18 05:04:35 +0800 CST
  • Martin Hope
    Saaru Lindestøkke Por que os arquivos tar.xz são 15x menores ao usar a biblioteca tar do Python em comparação com o tar do macOS? 2021-03-14 09:37:48 +0800 CST
  • Martin Hope
    CiaranWelsh Como posso reduzir o consumo do processo `vmmem`? 2020-06-10 02:06:58 +0800 CST
  • Martin Hope
    Jim Pesquisa do Windows 10 não está carregando, mostrando janela em branco 2020-02-06 03:28:26 +0800 CST
  • Martin Hope
    andre_ss6 Área de trabalho remota congelando intermitentemente 2019-09-11 12:56:40 +0800 CST
  • Martin Hope
    Riley Carney Por que colocar um ponto após o URL remove as informações de login? 2019-08-06 10:59:24 +0800 CST
  • Martin Hope
    zdimension Ponteiro do mouse movendo-se nas teclas de seta pressionadas no Windows? 2019-08-04 06:39:57 +0800 CST
  • Martin Hope
    jonsca Todos os meus complementos do Firefox foram desativados repentinamente, como posso reativá-los? 2019-05-04 17:58:52 +0800 CST
  • Martin Hope
    MCK É possível criar um código QR usando texto? 2019-04-02 06:32:14 +0800 CST
  • Martin Hope
    SoniEx2 Altere o nome da ramificação padrão do git init 2019-04-01 06:16:56 +0800 CST

Hot tag

windows-10 linux windows microsoft-excel networking ubuntu worksheet-function bash command-line hard-drive

Explore

  • Início
  • Perguntas
    • Recentes
    • Highest score
  • tag
  • help

Footer

AskOverflow.Dev

About Us

  • About Us
  • Contact Us

Legal Stuff

  • Privacy Policy

Language

  • Pt
  • Server
  • Unix

© 2023 AskOverflow.DEV All Rights Reserve