I am trying below code programatically to login to ssh ip from a csv file.
the below code logging into all servers and executing some command line syntax. But what I need is for example if i have 5 IP's ,if first one connects successfully and executes the commands then i want program to exit if not it has to login into 2nd IP check whether it will be able to access it and issue comands and get me output...like this...
and also the IP have .pem key authetication...so how would i modify below program to allow ssh with pem key
#!/bin/bash
USERNAME=someUser
HOSTS="host1 host2 host3"
SCRIPT="pwd; ls"
for HOSTNAME in ${HOSTS} ; do
ssh -l ${USERNAME} ${HOSTNAME} "${SCRIPT}"
done
#!/bin/bash
USERNAME=someUser
HOSTS="host1 host2 host3"
SCRIPT="pwd; ls"
for HOSTNAME in ${HOSTS} ; do
ssh -l ${USERNAME} ${HOSTNAME} "${SCRIPT}" && break
done
&& break causes the shell when the prior command is successful to skip the rest of the loop immediately. Since you do not have any commands after the loop the program is ending then.
Notes
${VAR} is no obligation here. $VAR will do too(The first one is 100% syntactically correct too; There are some cases however, when you have to use ${VAR}, e. g. when the following characters would extend the variable name like ${VAR}NAME. Without the braces, this would resolve another - possibly unset - variable named VARNAME)
I would avoid overwriting well defined variable Names like HOSTNAME. This variable is reserved for the real hostname of the system. Take any other variable name like "hostname"(lowercase) or "myhost"