Ping usando uma variável

Ping usando uma variável

Estou tentando criar um arquivo em lote que fará ping em uma variável determinada pela entrada do usuário

por exemplo, "Insira o nome do PC:" nome do PC = 123

Em seguida, ele faz ping em 123.domain.com

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

ping %UserInputPath%

ping MyServerName

PAUSE

Ping MyServerNamefunciona bem

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

Qualquer ajuda seria apreciada ::::EDIT:::

ping %UserInputPath% -n 5

Retorna este erro:IP address must be specified.

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

EDITAR 2::

Este é o meu mais recente:

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

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

ping MyServerName

PAUSE

Responder1

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"

Responder2

O script a seguir funciona, pelo menos para mim no Win7.

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

Primeiro pedimos ao usuário para inserir o nome, depois o armazenamos em nameuma variável e o passamos para ping(veja %name%) adicionar google.com(apenas como exemplo!).

Responder3

Aqui está um script bash sofisticado para você. Hackeei hoje cedo para a pergunta original antes de perceber que era para Windows. Considerei convertê-lo em um arquivo em lote para você, mas parecia doloroso. Me lembrou de escrever scripts de startups na faculdade.

Você precisa usar o Powershell ou ativar um host *nix em algum lugar. Powershell v3 é muito bom. Você poderia converter isso em PowerShell com bastante facilidade, na verdade.

Haverá alguns votos negativos para isso, mas quem se importa. Alguém achará este script útil. No mínimo você pode saquear a lógica e o 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

Responder4

Parece que você caiu noarmadilha de expansão atrasadae seu trecho de código está entre (e ). Quando você usa uma variável alterada dentro de tal bloco, você precisaativar 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

informação relacionada