Date created: Tuesday, June 20, 2017 12:11:22 PM. Last modified: Sunday, April 30, 2023 4:47:35 PM

Running Parallel Commands via SSH

References

https://dataplumber.wordpress.com/2016/10/26/issuing-junos-commands-using-ansible-raw-module/

 

Examples

Running a single command on multiple remote devices using Ansible:

ansible all -i hosts -m raw -c paramiko -a "wr mem"

 

Using parallel SSH (pssh):

pssh -h hosts.txt -l username --askpass -o /output_dir/ "wr mem"

 

Ciscocmd expect script:

./ciscocmd -u username -p password -T hosts.txt -r commands.txt -l log-file-prefix- -Y

 

When using SSH on Linux the -T option tells SSH not to allocate a PTY so that when run from a cron job the tasks can accept stdin/out from the session (e.g. log to a file). The -q option will suppress any devices banners. Specifying /dev/zero as an input will hold the SSH command running incase there is a delay in stdout opening. Having "-oStrictHostKeyChecking=no -oUserKnownHostsFile=/dev/null" is potentially insecure and may not be suitable for a production network.

RAW_OUTPUT=$(timeout $TIMEOUT sshpass -e ssh -T -q -oStrictHostKeyChecking=no -oUserKnownHostsFile=/dev/null $USER@$HOST "$CMD" </dev/zero 2>/dev/null)

 

BASH space seperated values:

ips="10.254.255.16 10.254.255.2 10.254.254.50 10.254.248.2"
for ip in $ips; do echo "$ip:"; ssh -q -T $username@$ip "show vpdn group"; echo ""; done

# Alternatively
ips="10.254.255.16 10.254.255.2 10.254.254.50 10.254.248.2"
export SSHPASS="mypass"
for ip in $ips; do echo "$ip:"; sshpass -e ssh -q -T $username@$ip "show vpdn group"; echo ""; done

BASH script using a for loop over a hosts file:

#!/bin/bash
set -u

USER="myuser"
export SSHPASS="mypass"
TIMEOUT=10s
CMD="show ver | i uptime"

while read -r HOST || [[ -n "$HOST" ]]
do
    timeout $TIMEOUT sshpass -e ssh -n -q -oStrictHostKeyChecking=no -oUserKnownHostsFile=/dev/null -oBatchMode=no $USER@$HOST "$CMD" 2>/dev/null &
    # Not all SSH versions support the -q and -o options used here ^
done < hosts.txt