0

I am trying to automate a SSH bash script to check whether my server is able to SSH the remote devices. I can not install any third party tool like sshpass, expact or Net:SSH as it is not allowed in my organization.

I have created an ip.txt file which contains the IP addresses. Script will pick the first IP and SSH the device. In next step I want to supply any command say date and last exit. Everything goes well until I supply exit command. "Exit" command terminates the whole script instead going to the next loop/IP.

Is there any way to continue the script even after supplying the exit command on the remote device prompt?

However, the below commands works: ssh username$IP "date && exit" but I have different commands to run on different servers.

Code it working fine but when exit command is supplied, shell script gets terminated.

#!/bin/bash
for IP  in `cat /home/ip.txt`
do
echo "Going to SSH first $IP"
ssh username@$IP
date >> log.txt
exit >> log.txt
echo "Completed first loop for $IP"
done

I want to enter the commands manually and want the script should not terminate when exit command is supplied.

1 Answers1

1

Just as @rolandweber has pointed out, the error occurs because you execute the exit command locally. It should look something like this:

#! /bin/bash
username=username
iplist=ip.txt
logfile=log.txt
while IFS= read -r ip; do
        echo "Testing $ip"
        echo -n "$ip: " >> $logfile
        serverdate="$(ssh $username@$ip <<-EOF
        date
EOF
)"
        error=$?
        echo "$serverdate ($error)" | tail -1 >> $logfile
done < $iplist

Note that you could indent the EOF, but the commands in the here-doc must be aligned with tabs.

Bayou
  • 3,293
  • 1
  • 9
  • 22
  • Thank you Roland and Bayou. – danish noman Jul 22 '19 at 10:08
  • But my requirement is little different. When I SSH the windows device it gives me another admin prompt to enter password even after the supplying the username and password. This admin prompt confirms me that I am able to SSH the device. So I want to pass a kill signal so that it can avoid admin prompt and go for the second loop. Also, is there any way to record the prompt in the log file like I am getting admin prompt here? – danish noman Jul 22 '19 at 10:23
  • I don't think that's possible to omit. For such problems you must use `expect` because it lets you interact with the shell (send passwords and stuff). Adding `exit` to the here-doc doesn't help you, because the password is required before `date` executes (I guess). However, if every server you're connecting to has a ssh key, you could make use of (timeout)[man7.org/linux/man-pages/man1/timeout.1.html]. And no, I don't know if there's a way to record the prompt in the log file; I don't use Windows at all :p – Bayou Jul 22 '19 at 11:19