HackersInside
HackersInside

Reputation: 307

Capturing SSH Output in a variable in a bash script

I'm trying to SSH into another machine and caputre it's ip address and hostname into a variable.

However, the varaible seems to be empty when i echo it.

I have tried out answers from other posts, but it didnt solve my problem. I'm not able to figure out as what the problem is.

#!/bin/bash

FILE=/home/admin/Vishal/output.txt
input=host.txt

while IFS= read -r line
do 
echo "$line"
if [ $line = $HOSTNAME ]
then

ip=`hostname -i`
domain=`hostname -A`
host=`hostname`
sudo echo $ip $domain $line localhost >> $FILE

else
output=$(ssh -i -t admin@$line  << "ENDSSH"

ip2=`hostname -i`
domain2=`hostname -A`
host2=`hostname`
ENDSSH
)
echo $output
fi

done <"$input"

The input file contains a list of hostnames

The variable FILE contains the path of the file where the results are to be stored.

The varaible output is the one in which i want to store the results.

Note: The script works for first part of the if where ssh isnt required.

Upvotes: 0

Views: 1440

Answers (1)

jeb
jeb

Reputation: 82418

Ony this command is relevant for your quesion:

output=$(ssh -i -t admin@$line  << "ENDSSH"

ip2=`hostname -i`
domain2=`hostname -A`
host2=`hostname`
ENDSSH
)

The command sets some variables, but doesn't produce any output, so it's expected that output does't contain your values.

If you really want three lines with hostname related values, then something simple like this should work

output=$(ssh admin@$line "hostname -i; hostname -A; hostname")

Upvotes: 1

Related Questions