Login to remote host and execute commands

Hi,
i want to write script where it will login into 50 hosts and if login is successful it print message "login to host1 is
successful" if not it should print message "Not able to login to host1". once connection to the host is succesful it should fire df command to check filesystem if df is stuck somewhere
then it should print message "DF got stuck otherwise print message "DF is successful"
Please advice how should i achive this

i used below approach

#!/usr/bin/ksh
for i in `cat host.txt`
do
        ssh $i
if [[ $? -eq 0 ]] then
echo "Login to $i is succesful"
        df
                if [[ $? -eq 0 ]] then
                echo "Df is successful"
                else
                echo "DF got stucked"
                fi
else
echo "Not able to Login to $i"

fi
done

Thanks

Ok. Assuming that ssh is listening on port 22 in each of those hosts, and that the file hosts.txt contains a list of IP addresses or hostnames this is what I'd do:

#!/usr/bin/ksh
while read line
do
ssh $line <<EOF # Use a 'here document' to pass a sequence of commands to the ssh connection
if [[ $? -eq 0 ]] then
	echo "Login to $line was succesful"
	df
		if [[ $? -eq 0 ]] then
			echo "df is successful"
		else
			echo "DF got stucked"
		fi
else
	echo "Not able to Login to $i"
fi
exit
EOF
done < hosts.txt

Let me know if this works for you. Good luck.

1 Like

Hi,

Thanks for your help.

But i m getting below error and systems hangs for 2-5 seconds and then it runs the commands successfully.

Pseudo-terminal will not be allocated because stdin is not a terminal.

Also i would like to send the echo statments output to some txt file and then email should be send to user like below.

example

"Login to $line is successfult"
"DF is executed successfulyy at $line"

can u please help.

Thanks

Please use code tags as required by forum rules!

Read man ssh . Done that, you may want to use the -T option to ssh. The "few-second-hang" is not a hang but the duration of the remote login process.

Use output redirection immediately after input redirection to create the log file. Then, mail the log file to your address list.

1 Like