Home > OS >  ssh to the machine and run the linux command using shell script and store it in the file
ssh to the machine and run the linux command using shell script and store it in the file

Time:09-29

I have machines stored in host.txt file. I need to read each line from file and do the ssh for it and run the linux command "cat /etc/redhat-release". Store the output along with machine name in the output file. Not sure if exit is also required after running ssh command.

script:

#!/bin/bash
while read line do
    sshpass -p 'abc123' ssh -o StrictHostKeyChecking=no ${line}
    echo `cat /etc/redhat-release` >> logfile.txt
done < host.txt 

Above one is not working. Please help. Thanks in advance.

CodePudding user response:

while IFS= read -r server; do
  sshpass -p 'abc123' ssh -o StrictHostKeyChecking=no "$server" cat /etc/redhat-release <&-
done <host.txt >logfile.txt

or with GNU xargs with -P option with 10 processes:

xargs -P10 -d '\n' -i{} sshpass -p 'abc123' ssh -o StrictHostKeyChecking=no {} cat /etc/redhat-release <host.txt >logfile.txt

Research: https://mywiki.wooledge.org/BashFAQ/001 While loop stops reading after the first line in Bash and ssh breaks out of while-loop in bash https://mywiki.wooledge.org/BashGuide/Practices#Quoting . Check your scripts with https://www.shellcheck.net/ .

  • Related