Date created: Tuesday, June 20, 2017 12:11:22 PM. Last modified: Tuesday, April 9, 2024 4:45:02 PM

Running Parallel Commands via SSH




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:

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

# Alternatively
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:

set -u

export SSHPASS="mypass"
CMD="show ver | i uptime"

while read -r HOST || [[ -n "$HOST" ]]
    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