How to use plink to run command from windows

Recently i had to run some commands on 250 linux servers in one of my project. So i decided to use plink.exe from windows machine. This section will help you how to use plink to run linux command from windows on multiple server

plink.exe without sudo privilege 

plink.exe -ssh -t -pw <password> -l <user>@<host>  -m <script> <IP Address of host>

syntax –
-m – create filename called “script.txt” or the name you want and place it under folder where plink.exe is located
-pw – password of remote host
-l – user id to login to remote host
ip address of host
-t – it will open pseudo shell

lets say script.txt include,
ls /tmp

Above command will show output on your local windows machines cmd.exe or powershell

if the host key was not cached in the registry yet, you would get an interactive prompt saying “Store key in cache? (y/n)” which would not be conducive to a batch script.
And once again, the way around this is to pipe a “y” to stdin, which makes the command:
cmd.exe /c echo y | plink.exe -ssh -t -pw myP4ss -l myuser@trusty1 -m script.txt <IP Address of host?

plink and sudo with password prompt

In the above example we dealt with simple commands that required no input and no privilege escalation with sudo (hostname, pwd).  But many times the commands we want to run in batch processes require sudo, which throws up an interactive prompt for a password.

Sudo password echoed and embedded inside plink script

Make sure you call plink with “-t” so that a tty is setup.  Then sudo to a shell and echo the password into stdin before running the command you want with sudo.

/bin/echo -e "myP4ss\n" | sudo -S /bin/bash
sudo apt-get update

Or you can echo the password directly to the command you want to run as sudo

/bin/echo -e "myP4ss\n" | sudo apt-get update

Run the command on number of hosts using powershell

First you need to create one text file with list of remote server IPS or FQDN (if DNS is configured properly) in the text file and place it under same folder where plink.exe is located

get-content .\linux_Server.txt | foreach {invoke-command -command {& echo y | .\plink.exe $_ -l <username> -pw <password> -m <file with list of command>; write-host -fore “$_ host finished”}}

This command will ssh in to each host under .\linux_Server.txt and execute set of commands defined in <file with list of command>

Hope this helps… feel free to comment with  suggestion,