Reputation: 53
I have a large number of devices around 300 I have different creds to them SSH CREDS, API CREDS So as I cannot manually SSH to all those devices and check the creds are working or not I am thinking of writing a script and pass the device IP's to the script and which gives me as yes as a result if the SSH creds are working and NO if not working. I am new to all this stuff! details will be appreciated! I will run this script on a server from where I can ssh to all the devices.
Upvotes: 0
Views: 2341
Reputation: 11861
Your question isn't clear as to what sort of credentials you use for connecting to each host: do all hosts have the same connection method, for instance?
Let's assume that you use ssh's authorised keys method to log in to each host (i.e. you have a public key on each host within the ~/.ssh/authorized_keys
file). You can run ssh with a do nothing command against each host and look at the exit code to see if the connection was successful.
HOST=1.2.3.4
ssh -i /path/to/my/private.key user@${HOST} true > /dev/null 2>&1
if [ $? -ne 0]; then echo "Error, could not connect to ${HOST}"; fi
Now it's just a case of wrapping this in some form of loop where you cycle through each host (and choose the right key for each host, perhaps you could name each private key after the name or IP address of the target host). The script will go out all those hosts for which a connection was not possible. Note that this script assumes that true
is available on the target host, otherwise you could use ls
or similar. We pipe all output to /dev/null/
as we're only interested in the ability to connect.
EDIT IN RESPONSE TO OP CLARIFICATION:
I'd strongly recommend not using username/password for login, as the username and password will likely be held in your script somewhere, or even in your shell history, if you run the command from the command line. If you must do this, then you could use expect
or sshpass
, as detailed here: https://srvfail.com/how-to-provide-ssh-password-inside-a-script-or-oneliner/
The ssh command shown does not spawn a shell, it literally logs in to the remote server, executes the command true
(or ls
, etc), then exits. You can use the return code ($?
in bash) to check whether the command executed correctly. My example shows it printing out an error message for non-zero return codes, but to print out YES
on successful connection, you could do this:
if [ $? -eq 0]; then echo "${HOST}: YES"; fi
Upvotes: 1