Search code examples
batch-filesshputtyplink

How to execute multiple commands sequentially on device in Windows batch file using PuTTY/Plink?


I am trying to configure a device over SSH in a automated way using a .bat script. In the snippet below I am generating a file with the required commands in the correct order, afterwards I execute/read the file into the SSH connection using plink. This results in a error message the the commands are unknown, I think this is caused by the fact that the commands are not executed one by one but the entire file is inserted.

Does anyone have a idea how I can execute multiple commands sequentially?

I have tried to redirect the commands.txt file into plink without success. Also it is not possible to create a new SSH connection for each commands, because some commands turn the device into the configuration mode. Unfortunately the device that I am trying to configure is not Unix based, so chaining commands with && or ; is not possible, I am required to insert the command and then 'press enter' and continue.

config.bat

@echo off
SET /P IpAdres=IP: 
SET /p Username=Username:
SET /p Password=Password:
echo command 1 >> commands.txt
echo command 2 >> commands.txt
echo command 3 >> commands.txt
echo command 4 >> commands.txt
plink.exe -batch  %IpAdres% -l %Username% -pw %Password% -m commands.txt

Solution

  • It's indeed possible that the device interprets the commands as one. A command specified using Plink/PuTTY -m switch is executed using "exec" SSH channel, that's designed for a single command only. While some SSH servers (like OpenSSH) can handle even multiple commands this way (so your batch file would work there), it's no way a standard behaviour. Your device possibly uses some proprietary SSH server, not a common OpenSSH.


    If you want to simulate a user inputting the commands one-by-one, use input redirection instead (this way "shell" channel is used instead by Plink):

    (
        echo command 1
        echo command 2
        echo command 3
        echo command 4
    ) | plink.exe -batch %IpAdres% -l %Username% -pw %Password%