0

I'm pretty new to coding and I needed a little automation batch file.

I usually just open Telnet from CMD and do this:

I type:o 192.168.1.248

And I get connected to the device I send my string WE1*1RTMP and the device responds with E1*1RTMP

This is correct and everything works.

But I would like to make this an automation without me requiring to type everything, just launch a .bat file.

  • I was able to do that both with Ncat, creating a bat file that says: echo WE1*1RTMP | ncat 192.1568.1.248 23and everything works.

  • I was also able to do it using Plink with a .bat file saying plink.exe -load RECtelnet < *path to a text file containing the WE1*1RTMP command. Now I need a way to check the response from the device.

When the command is received and executed correctly, the answer I get is E1*1RTMP, but I'd love to have something that check this. Like if the response I get is the same as this one, everything just disappear after running, but if the response is anything different, like the E10 error I get when I type a command that is not recognized from the device, instead of disappearing the cmd windows just says something like "Hey your command failed" or anything similar.

I could also send this command using SSH, I have another profile with Plink called "REC" that connects me thru SSH, if this is somehow easier to automate compared to telnet.

How can I archive this ? Thanks to everyone who will try to help.

Veehxia
  • 1
  • 2

2 Answers2

0

The simplest way for you to do what you want is likely to:

  1. Install python.

  2. Write this in a text file (e.g. with notepad), and save it as something ending in .py:

    import socket
    import traceback
    
    try:
        mysock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        mysock.connect(("192.168.1.248", 23))
        mysock.send(b"WE1*1RTMP\n")
        read_so_far = b""
    
        while b"E1*1RTMP".startswith(read_so_far):
            read_bit = sock.recv(1024)
            if read_bit == b"":
                print("Didn't get full message; had", repr(read_so_far))
                input("Press enter to continue... ")
                break
            read_so_far += read_bit
            if read_so_far.startswith(b"E1*1RTMP"):
                print("Got success message")
                break
        else:
            print("Got the wrong message: ", repr(read_so_far))
            input("Press enter to continue... ")
    except Exception as e:
        traceback.print_exc()
        input("Press enter to continue... ")
        raise
    

    NOTE: The way the lines are indented there is important.

  3. Double-clicking on that file should now do what you want. If something goes wrong, before asking for help here open up a command prompt, cd to the relevant directory and run it at the command line with python myfile.py (or whatever you named the file). People here will need that output.

  4. Sometime in the future, pick up a book on python or enroll in a python-focused course on coursera or elsewhere. I've heard good things about "Python for Everybody", but there's loads out there - well over 10% of your local big box book store's computer section these days is books trying to teach you python.

Daniel Martin
  • 23,083
  • 6
  • 50
  • 70
  • Thanks for you answer, I tryed doing as you said step-by-step, but that is what I get from the cmd: Traceback (most recent call last): File "C:\Users\Utente\Desktop\diretta.py", line 7, in mysock.send("WE1*1RTMP\n") TypeError: a bytes-like object is required, not 'str' Press enter to continue... In I press enter nothing seems to happen, I' ve checked on the device web page and the command has not been executed. – Veehxia Jul 30 '19 at 15:22
  • Ugh, sorry. The script is fixed now. – Daniel Martin Jul 30 '19 at 18:17
  • Thank you. I'm out of the workplace until friday so I cant try it right away, but I'll make sure to post updates once I do. Thanks again for your time and help. – Veehxia Jul 30 '19 at 21:24
0

I Modified the example Script to be much tighter and use yoru command and IP and do telnet instead of SSH etc.

REM Script Name:  TelnetToDevice.cmd
@(
  SETLOCAL EnableDelayedExpansion
  ECHO OFF
  REM SETUP Device Connection Details and commands
  SET "_PLink.Path=%~dp0plink.exe"
  SET "_PLink.Method=-telnet"
  REM SET "_PLink.Method=-ssh"
  SET "_Device.User=USERNAME"
  SET "_Device.PW=PASSWORD"
  SET "_Devices.List="192.1568.1.248""
  SET "_Devices.Cmd.List="WE1*1RTMP""
  SET /A "_Results.Count=0"
)


FOR %%A IN (%_Devices.List%) DO (
  FOR %%B IN (%_Devices.Cmd.List%) DO (
    FOR /F "Tokens=*" %%C IN ('
      ECHO.Y^|%_PLink.Path% %_PLink.Method% %_Device.User%@%%~A -pw %_Device.PW% "%%~B"
    ') DO (
      ECHO.Results is "%%C"
      SET /A "_Results.Count+=1"
      SET "_Result.!_Results.Count!=%%C"
    )
  )
)

ECHO.
ECHO.Listing all Variables generated:
ECHO.
SET "_Result."

PAUSE

(
  ENDLOCAL
  EXIT /B 0
)

Okay if you just need to collect the output from that command, maybe launch another command in response then it's fairly easy to do in CMD using PLINK, and NCAT should work the same.

(I use Plink to connect to our Cisco Devices from CMD to collect Data, and run some simple commands if I get certain responses)

This is done by catching the output from the command by parsing the results in a FOR /F loop.

At the CLI Directly:

NCAT

FOR /F "Tokens=*" %A IN ('
  ECHO.WE1*1RTMP^| ncat 192.1568.1.248 23
') DO (
  ECHO.%%A
  SET "_Result=%%A"
)

PLINK

FOR /F "Tokens=*" %A IN ('
  plink.exe -load RECtelnet ^< "C:\path\to\file containing WE1*1RTMP command.txt"
') DO (
  ECHO.%%A
  SET "_Result=%%A"
)

Note, I assume you know that in the above commands you will need to provide the Username password etc in these cases, as you say these are working commands as stand.

I happen to have a Script that I use to connect to multiple devices and run commands, its over-kill for your needs, and I will write a trimmed down version, but it seemed worthwhile to include it as the example of running in a CMD script:

Here is the shell of the actual CMD Script I use to check and fix our Fibre switches:

@(
    SETLOCAL ENABLEDELAYEDEXPANSION
    ECHO OFF
    REM SETUP Device Connection Details and commands
    SET "_PLink.Path=%~dp0plink.exe"
    SET "_Device.User=USERNAME"
    SET "_Device.PW=PASSWORD"
    SET "_Devices.List="IP/Hostname1" "IP/Hostname_2" "IP/Hostname_3" "IP/HostnameN""
    SET "_Devices.Cmd.List="show feature ^| inc http" "show system internal flash ^| include Mount" "show system internal flash ^| include tmp" "dir ^| include free" "show system internal dir /var/tmp ^| Inc 'log.+[0-9][0-9][0-9][0-9][0-9][0-9]'" "show environment fan ^| ex ---- ^| ex Filter" "show environment temperature ^| ex ---- ^| ex '('""

    REM Setup Log files and Email
    CALL :GetDateTime
    SET "_Log.Folder=%~dp0Log"
    SET "_eMail.Folder=%~d0\Temp"
    IF NOT EXIST "!_Log.Folder!" ( MD "!_Log.Folder!" )
    IF NOT EXIST "!_eMail.Folder!" ( MD "!_eMail.Folder!" )
    SET "_Log.File=!_Log.Folder!\%~n0_Log_!IsoDate!_!IsoTime!.log"
    SET "_eMail.File=!_eMail.Folder!\%~n0_eml.tmp"
    SET "_eMail.Subject=%~n0 - Log"
    ECHO.>"!_eMail.File!"
    SET "_SMTPServer=SMTPServerIP"
    SET "_RcptTo=Yourname@YourDomain.com"
    SETLOCAL DISABLEDELAYEDEXPANSION
)
CALL :Main


(
    ENDLOCAL
    Exit /b %eLvl%
)


:Main
    FOR %%A IN (%_Devices.List%) DO (
        CALL :OutEcho
        CALL :DateEcho %%~A:
        FOR %%B IN (%_Devices.Cmd.List%) DO (
            FOR /F "Tokens=*" %%C IN ('
                ECHO.Y^|%_PLink.Path% -ssh %_Device.User%@%%~A -pw %_Device.PW% "%%~B"
            ') DO (
                CALL :OutEcho %%~A: %%~C
                (
                    ECHO.%%~C | FIND /I "log" >NUL
                ) && (
                    FOR /F "Tokens=1" %%D IN ("%%~C") DO (
                        CALL :OutEcho %%~A: Deleting:  %%~D
                        FOR %%b IN (
                            %_Devices.Cmd.DeleteFoundFile%
                        ) DO (
                            FOR /F "Tokens=*" %%c IN ('
                                %_PLink.Path% -ssh %_Device.User%@%%~A -pw %_Device.PW% "%%~b%%~D"
                            ') DO (
                                CALL :OutEcho %%~A: %%~c
                            )
                            CALL :OutEcho %%~A: Deleted:  %%~D
                        )
                    )
                )
            )
        )

    )
    CALL :SendMail "%_eMail.File%" "%_eMail.Subject%"
GOTO :EOF


:SendMail
    ECHO.Sending Email for "%~2"
    CALL ECHO CALL "%~dp0mailsend.exe" -domain reval.com -smtp %_SMTPServer% -f %Computername%@reval.com -t %_RcptTo% -sub "%~2" -attach "%~1",text,i
    CALL "%~dp0mailsend.exe" -domain reval.com -smtp %_SMTPServer% -f %Computername%@reval.com -t %_RcptTo% -sub "%~2" -attach "%~1",text,i
GOTO :EOF


:DateEcho
    (
        SETLOCAL
        CALL :GetDateTime
    )
    CALL :OutEcho %TDate% - %*
    ENDLOCAL
GOTO :EOF


:OutEcho
    ECHO.%*
    ECHO.%*>>"%_Log.File%"
    ECHO.%*>>"%_eMail.File%"
GOTO :EOF


:GetDateTime
    FOR /F "Tokens=1-7 delims=MTWFSmtwfsouehrandit:-\/. " %%A IN ("%DATE% %TIME: =0%") DO (
        FOR /F "Tokens=2-4 Skip=1 Delims=(-)" %%a IN ('ECHO.^| DATE') DO (
            SET "%%~a=%%~A"
            SET "%%~b=%%~B"
            SET "%%~c=%%~C"
            SET /a "#%%~a=1%%~A - (2%%~A-1%%~A)"
            SET /a "#%%~b=1%%~B - (2%%~B-1%%~B)"
            SET /a "#%%~c=1%%~C - (2%%~C-1%%~C)"
            SET "HH=%%~D"
            SET "Mn=%%~E"
            SET "SS=%%~F"
            SET "Ms=%%~G"
            SET /a "#HH=1%%~D - (2%%~D-1%%~D)"
            SET /a "#Mn=1%%~E - (2%%~E-1%%~E)"
            SET /a "#SS=1%%~F - (2%%~F-1%%~F)"
            SET /a "#Ms=1%%~G - (2%%~G-1%%~G)"
            SET /a "#TMinutes=((1%%~D - (2%%~D-1%%~D))*60)+(1%%~E - (2%%~E-1%%~E))"
            SET /a "#TSeconds=((((1%%~D - (2%%~D-1%%~D))*60)+(1%%~E - (2%%~E-1%%~E)))*60)+(1%%~F - (2%%~F-1%%~F))"
        )
    )
    SET "TTime=%HH%.%Mn%.%SS%"
    SET "IsoTime=%HH%.%Mn%.%SS%.%Ms%"
    SET "TDate=%yy%-%mm%-%dd%"
    SET "IsoDate=%yy%-%mm%-%dd%"
GOTO :EOF

Below is a MUCH tighter script that uses your provided info directly.

REM Script Name:  TelnetToDevice.cmd
@(
  SETLOCAL EnableDelayedExpansion
  ECHO OFF
  REM SETUP Device Connection Details and commands
  SET "_PLink.Path=%~dp0plink.exe"
  SET "_PLink.Method=-telnet"
  REM SET "_PLink.Method=-ssh"
  SET "_Device.User=USERNAME"
  SET "_Device.PW=PASSWORD"
  SET "_Devices.List="192.1568.1.248""
  SET "_Devices.Cmd.List="WE1*1RTMP""
  SET /A "_Results.Count=0"
)


FOR %%A IN (%_Devices.List%) DO (
  FOR %%B IN (%_Devices.Cmd.List%) DO (
    FOR /F "Tokens=*" %%C IN ('
      ECHO.Y^|%_PLink.Path% %_PLink.Method% %_Device.User%@%%~A -pw %_Device.PW% "%%~B"
    ') DO (
      ECHO.Results is "%%C"
      SET /A "_Results.Count+=1"
      SET "_Result.!_Results.Count!=%%C"
    )
  )
)

ECHO.
ECHO.Listing all Variables generated:
ECHO.
SET "_Result."

PAUSE

(
  ENDLOCAL
  EXIT /B 0
)
Ben Personick
  • 3,074
  • 1
  • 22
  • 29
  • Thanks for the answers, unfortunately both of those didnt work. I have a web page where I can check if the command has been run properly and they dont run at all. – Veehxia Jul 30 '19 at 15:20
  • @Veehxia I also included an example of the full script I use, Normally for PLINK I will actually pass the lines as an argument directly. Since this is a script doing a specific and different task I left the actual command in place so you can see hwo they are escaped in this scenario. I'll also post a much shorter version which I think does just your piece. – Ben Personick Jul 30 '19 at 15:39
  • @Veehxia Also normally with PLINk I have to specify the Username and password I assumed you simply omitted that from your command because you knew you would need to ad it back in, is this correct? – Ben Personick Jul 30 '19 at 15:39
  • @Veehxia I posted the version which uses the info you provided and greatly reduces the total script at the top of the answer for you, give that one a shot as well. – Ben Personick Jul 30 '19 at 15:57
  • Thank you very much, I'll try it on friday when I'm back. Sadly I'm pretty new to all of this so, is there anything I should change to make it run on my machine? – Veehxia Jul 30 '19 at 17:58
  • Also I forgot to mention that the device doesnt require a log in. Its a simple video streamer / recorder, the command I'm sending just make it start streaming – Veehxia Jul 30 '19 at 18:04