Search code examples
windowsbatch-fileconnectivity

Batch file to check the availability of a specific port of a remote server


Hi I am trying to make a bat file to check the availability from different servers to a specific one, in order to check if there are some firewalls between them,or something that blocks the conecction. The thing is I can't use third parties software like portqry, nmap ... So iam stuck here, every tip will be helpfull.

Thanks in advance XD,


Solution

  • manually you can use telnet

    echo.|telnet google.com 80
    

    But telnet output cannot be handles so it's not useful for scripting.

    Here's one solution which is more or less cheating (as it creates an .exe file) , but is not downloades. As it contains binary data into hex string it's a little bit long ,so I'd had to use pastebin.com

    Another way.Using jscript.net/batch hybrid (should be saved as bat) which also creates a small exe file. But setting socket connection timeout is not so trivial task so if the port is not availble it will be waiting a little bit too long:

    @if (@X)==(@Y) @end /****** silent line that start jscript comment ******
    
    @echo off
    ::::::::::::::::::::::::::::::::::::
    :::       compile the script    ::::
    ::::::::::::::::::::::::::::::::::::
    setlocal
    ::if exist portchk.exe goto :skip_compilation
    
    set "frm=%SystemRoot%\Microsoft.NET\Framework\"
    :: searching the latest installed .net framework
    for /f "tokens=* delims=" %%v in ('dir /b /s /a:d /o:-n "%SystemRoot%\Microsoft.NET\Framework\v*"') do (
        if exist "%%v\jsc.exe" (
            rem :: the javascript.net compiler
            set "jsc=%%~dpsnfxv\jsc.exe"
            goto :break_loop
        )
    )
    echo jsc.exe not found && exit /b 0
    :break_loop
    
    
    %jsc% /nologo /out:"portchk.exe" "%~dpsfnx0"
    ::::::::::::::::::::::::::::::::::::
    :::       end of compilation    ::::
    ::::::::::::::::::::::::::::::::::::
    :skip_compilation
    
    :: download the file
    
    
     ::::just change the link and the file::::
     portchk.exe google.com 80
     portchk.exe google.com 666
    
    
    exit /b 0
    
    
    ****** end of jscript comment ******/
    
    import System;
    import System.Net.Sockets;
    import System.Timers;
    
    var arguments:String[] = Environment.GetCommandLineArgs();
    
    
    
    var remote_host=arguments[1];
    var remote_port=arguments[2];
    
    //var ipa= (IPAddress) Dns.GetHostAddresses(remote_host)[0];
    
    var sock=new System.Net.Sockets.Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
    
    try {
        sock.Connect(remote_host, remote_port);
        //sock.ConnectAsync(remote_host, remote_port);
        timer_connection = new Timer();
    
        Console.WriteLine("connected to something");
    
    }catch (e) {
    
        Console.WriteLine("Port is probably not available");
    }