5

I am trying to run a script remotely (from a bash script), but am having trouble getting the output to redirect locally, for analysis. Running the script is no problem with:

ssh -n -l "$user" "$host" '/home/user/script.sh $params'

However I am unable to capture the output of that script. I have tried the following:

results=$(ssh -n -l "$user" "$host" '/home/user/script.sh $params')
results=`ssh -n -l "$user" "$host" '/home/user/script.sh $params'`
ssh -n -l "$user" "$host" '/home/user/script.sh $params' | grep "what I'm looking for"
ssh -n -l "$user" "$host" '/home/user/script.sh $params' > results_file

Any ideas?

zvxr
  • 187
  • 1
  • 5
  • 12

5 Answers5

4
ssh user@host.com "ls -l" >output

You can even do things like:

ssh user@host.com "cat foo.tar" | tar xvf --

To make things simple, generate a pub/private key pair using ssh-keygen. Copy the *.pub key to the remote host into ~/.ssh/authorized_keys, make sure it's chmod'd 600

Then you can do

ssh -i ~/.ssh/yourkey user@host.com ... etc

And it won't ask for a password either. (If your key pair is passwordless)..

synthesizerpatel
  • 27,321
  • 5
  • 74
  • 91
1

Realized

ssh -n -l "$user" "$host" '/home/user/script.sh $params' > results_file

was working, as expected. It only appeared to lock up as the output was being redirected (and the script would take 5-6 minutes to build), and therefore was not being displayed. Thanks all.

zvxr
  • 187
  • 1
  • 5
  • 12
0

You are surely doing something wrong. I just tested it and it works fine.

shadyabhi@archlinux /tmp $ cat echo.sh 
#!/bin/bash
echo "Hello WOrld"$1
shadyabhi@archlinux /tmp $ ssh -n -l shadyabhi 127.0.0.1 '/tmp/echo.sh' foo
Hello WOrldfoo
shadyabhi@archlinux /tmp $ ssh -n -l shadyabhi 127.0.0.1 '/tmp/echo.sh' foo > out
shadyabhi@archlinux /tmp $ cat out
Hello WOrldfoo
shadyabhi
  • 16,675
  • 26
  • 80
  • 131
0

Well, in order for ssh -n to work at all, you need to have things set up so that you can log in without needing a password or passphrase (so you need a local private key either available with ssh-agent, or without a passphrase, and that public key needs to be in the appropriate authorized_keys file on the remote machine). But if that is the case, what you have should work fine (it has worked fine for me on many machines).

One other odd possibility is if your remote script.sh tries to write to stdin or /dev/tty instead of stdout/stderr. In which case it won't work with ssh -n

Chris Dodd
  • 119,907
  • 13
  • 134
  • 226
0

Your script does not get any of the parameters and is probably taking too long to run because of that. Also, whatever comes out (on stdout) can be piped to a next command or redirected to a file like any other local command. Consider the following:

$ cat ~/bin/ascript.sh 
echo one:$1 two:$2 three:$3

$ params="squid whale shark"
$ ssh localhost  'ascript.sh $params'
one: two: three:

$ ssh localhost  "ascript.sh $params"
one:squid two:whale three:shark