Remote execution of a local script on multiple servers

So I have a scriptlet called solaris_command:

for i in \
server1 server2 server3
do 
echo $i
ssh $i $1
echo ""
done

I then use that as a command in multiple scripts to allow for data gathering for all virtual hosts in the environment thusly:

solaris_command "cat /etc/hosts">>hosts.txt

this works for most instances but I am trying to do something a little more advanced and I can't seem to bend it to my will.

what I would like to do is something like:

 sed -e 's/^/$HOSTNAME /' /etc/vfstab|egrep -v -e $HOSTNAME' #'|expand|egrep -e '(svr|ldm|zone)'|cut -d ' ' -f 1-2,4|sed -e 's/ /,/'

basically reading in /etc/vfstab|manipulating it a couple times with sed, grep and cut to get the data I want in the format I want and then save it to a .txt file on the server I ran the command from.

however with respect to

$HOSTNAME

it outputs the hostname of the server the command was run on, not the name of the remote server. I'm stumped. I've tried it with

\$HOSTNAME

,

$HOSTNAME

,

`echo $HOSTNAME`

.

`hostname`

, and even

`echo /etc/nodename`

to no avail.

There were a few similar posts in forum
Shell Programming and Scripting - The UNIX and Linux Forums
I propose two separate scripts, this avoids the quoting chaos with remote execution.
Just make a simple "remote_script", that will run on the remote host:

#!/bin/bash
sed -e 's/^/$HOSTNAME /' /etc/vfstab|egrep -v -e $HOSTNAME' #'|expand|egrep -e '(svr|ldm|zone)'|cut -d ' ' -f 1-2,4|sed -e 's/ /,/'

Then you pass it by this modified "solaris_command" script:

for i in \
server1 server2 server3
do 
 echo $i
 ssh -x $i /bin/bash < remote_script
 echo ""
done

For efficiency I added -x

This is exactly what I am attempting to do, the problem is when I use

$hostname

the variable is populated with the hostname of the server running the script not the remote system.

You had one script,
and passed the second script as an argument to ssh - problem.

While I suggest two separate scripts.
ssh directly reads the "remote_script" via stdin - the current shell does not see it and cannot do substitutions.
So the /bin/bash on the remote system first sees and substitutes variables in the "remote_script".