Run awk command inside ssh

I am trying to run an awk command inside of ssh and it is not working. These are AIX servers.

for i in `cat servers`; do ssh $i "/bin/hostname; df -g | awk '/dev/ && $4+0 > 70'"; done
server1
server2
server3
server4

I also tried these two methods and they did not work. It just seemed to hang like this.

for i in `cat servers`; do ssh $i '/bin/hostname; df -g | awk '/dev/ && $4+0 > 80''; done
for i in `cat servers`; do ssh $i '/bin/hostname; df -g | awk "/dev/ && $4+0 > 80"'; done

Here documents work for this situation, example with ssh keys set up :

ssh somewhere << EOF
  ls some_folder; 
  cd ./some_folder
  ./do_some_action.sh  'some params'
  pwd
  ./do_ some_other_action  'other params'
 exit


EOF

Try escaping awk 's $ sign.

1 Like

Some advanced comments (this is the Advanced forum)
If you have a string in ' ' and want to have embedded ' ' (for the remote host) then use '\'' for each embedded '

for i in `cat servers`; do ssh $i 'hostname; df -g | awk '\''/dev/ && $4+0 > 80'\'''; done

(In this example you could omit the last '' of course.)

A here document like

ssh remotehost << 'EOF'
remote commands...
EOF

(quote the first EOF!) will solve most such head aches.

The clean solution is: two scripts!
A remotescript and
the ssh script like

ssh remotehost bash < remotescript.sh

Without any local evaluation the remotescript is sent to the remote host.

Quoting is a pain in the ass if you try to do it in combination with ssh commands.

Some hints:

  • Perform the actual textprocessing locally if possible, like this: ssh remoteserver command | grep ... | cut ... | awk ...
  • Put all what you want to do into a script, copy the script to remote and run it. I wrote a small script myself, which does that for me on a list of servers:
    [list]
  • check connectivity to server
  • copy script package to server
  • extract script package on server
  • run script on server
  • delete script package
    [/list]
  • If you have a list of servers you have to manage regularly, dive into some management or admin tool that allows the tasks for multiple servers(pssh, ansible, puppet, chef, saltstack, ...)

I just checked google. Seems that AIX has some support on the primary linux targeted config management tools above:
AIX configuration management with ... Something

With my proposal the remote shell (e.g. bash) runs the input stream - no need to copy/delete any files.
You can even use parameters:

ssh remotehost /bin/bash -s arg1 arg2 < remotescript.sh

arg1 and arg2 are passed to $1 and $2, respectively.