Ping usando uma variável

0

Estou tentando criar um arquivo de lote que fará o ping de uma variável determinada pela entrada de usuários

por exemplo. "Digite o nome do PC:" nome do pc = 123

Em seguida, ele pula 123.domain.com

@echo off
set /p UserInputPath = Enter chosen PC: 

ping %UserInputPath%

ping MyServerName

PAUSE

Ping MyServerName funciona bem

Mas ping %UserInputPath% não e apenas exibe o menu "Ajuda" para Ping no CMD

Qualquer ajuda seria apreciada :::: EDITAR :::

ping %UserInputPath% -n 5

Retorna este erro: IP address must be specified.

Você não pode fazer ping em um nome de host? (Como é isso que estou tentando fazer)

EDIT 2 ::

Este é o meu mais recente:

@echo off
set /p UserInputPath = "Enter chosen PC: " 
PAUSE 

ping %UserInputPath%.store.domain.company.com

ping MyServerName

PAUSE
    
por Alex 24.05.2015 / 20:45

4 respostas

2
set /p UserInputPath = Enter chosen PC: 
                    ^ This space is included in the name of the variable

Então você termina com uma variável chamada %UserInputPath %

Melhor uso

set /p "UserInputPath=Enter Chosen PC: "
ping "%UserInputPath%.store.domain.company.com"
    
por 25.05.2015 / 08:30
1

Seguir os trabalhos de script, pelo menos para mim no Win7.

@echo off
set /p name="Enter name:"
ping %name%.google.com

Primeiro, pedimos que o usuário insira o nome e, em seguida, armazene-o na variável name e passe-o para ping (consulte %name% ) adicionando google.com (apenas como exemplo!).

    
por 24.05.2015 / 20:51
0

Aqui está um roteiro extravagante para você. Hackeado hoje cedo para a pergunta original antes de perceber que era para o Windows. Considerado convertendo-o em um arquivo de lote para você, mas parecia doloroso. Lembrou-me de escrever scripts de inicialização na faculdade.

Você precisa usar o Powershell ou criar um host * nix em algum lugar. O Powershell v3 é muito legal. Você pode converter isso em powershell facilmente, na verdade.

Haverá alguns votos a menos para isso, mas quem se importa. Alguém achará esse script útil. No mínimo, você pode roubar a lógica e a regex.

Testado no Debian.

#!/bin/bash
# ------------------------------------------------------------------
# superuserping.sh # Can be changed :P
# /usr/bin/superuserping.sh # Put it wherever you like...
# ------------------------------------------------------------------
# Usage:           ./superuserping.sh [fqdn|shortname|ip]
#                  If no argument is passed it will ask for one
# Author:          Alex Atkinson
# Author Date:     May 25, 2015

# ------------------------------------------------------------------
# VARIABLES
# ------------------------------------------------------------------
domain="domain.com"
rxshort='^[A-Za-z0-9]{1,63}$'
rxfqdn='^([A-Za-z0-9-]{1,63}\.)+[A-Za-z]{2,6}$'
rxip='^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$'

# ------------------------------------------------------------------
# Check for argument. Get one if none found.
# ------------------------------------------------------------------
if [ -z $1 ]; then
    echo -n "Enter the hostname or IP to ping and press [ENTER]: "
    read host
else
    host=$1
fi

# ------------------------------------------------------------------
# ARGUMENT VALIDATION
# ------------------------------------------------------------------
checkshort=$([[ $host =~ $rxshort ]])
checkshort=$?
checkfqdn=$([[ $host =~ $rxfqdn ]])
checkfqdn=$?
checkip=$([[ $host =~ $rxip ]])
checkip=$?

# ------------------------------------------------------------------
# FUNCTIONS
# ------------------------------------------------------------------
function check_userinput()
{
    # Validate userinput against shortname, fqdn, and IP regex. If shortname then add domain.
    if [[ $checkshort == '0' ]] || [[ $checkfqdn == "0" ]] || [[ $checkip == "0" ]] ; then
        if [[ $checkip == 1 ]]; then
            if [[ $host != *$domain ]]; then
                host=$host.$domain
            fi
        fi
    else
        echo -e "\e[00;31mERROR\e[00m: ERROR:" $host "does not appear to be a valid shortname, fqdn, or IP."
        exit 1
    fi
}

function resolve_host()
{
    # Check for DNS host resolution.
    dnscheck=$(host $host)
    if [[ $? -eq 0 ]]; then
        echo -e "\n"$dnscheck "\n"
    else
        echo -e "\n\e[00;31mERROR\e[00m: DNS was unable to resolve the provided hostname or IP:" $host".\n"
        echo -n "Press [ENTER] key to continue with ping, or [Q] to quit..."
        read -n 1 -s key
        if [[ $key = q ]] || [[ $key = Q ]]; then
            echo -e "\nExiting...\n"
            exit 1

        fi
    fi
}

# ------------------------------------------------------------------
# MAIN OPERATIONS
# ------------------------------------------------------------------
check_userinput
resolve_host
ping $host
    
por 25.05.2015 / 07:18
-1

Parece que você caiu na armadilha de expansão atrasada e seu snippet de código está entre ( e ) . Quando você usa uma variável alterada dentro de tal bloco, então você precisa ativar a expansão atrasada ...

@echo off
SETLOCAL enableextensions enabledelayedexpansion

set "UserInputPath=AnotherServer"

(
    set "UserInputPath=MyServerName"
    rem set /p "UserInputPath = Enter chosen PC: "

    echo 1st percent-expansion %UserInputPath%
    echo 1st delayedexpansion  !UserInputPath!
)
echo(
echo 2nd percent-expansion %UserInputPath%
echo 2nd delayedexpansion  !UserInputPath!

Saída:

1st percent-expansion AnotherServer
1st delayedexpansion  MyServerName

2nd percent-expansion MyServerName
2nd delayedexpansion  MyServerName
    
por 24.05.2015 / 21:43