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?
The append >> operator adds the output to the existing content instead of overwriting it. This allows you to redirect the output from multiple commands to a single file. For example, I could redirect the output of date by using the > operator and then redirect hostname and uname -r to the specifications.
The Solution: Pass The Script Over Standard Input The bash -s command means “execute the following commands in a new bash session.” The -s flag makes it read from standard input, and the < script.sh bit will read a local script file into standard input.
The regular output is sent to Standard Out (STDOUT) and the error messages are sent to Standard Error (STDERR). When you redirect console output using the > symbol, you are only redirecting STDOUT. In order to redirect STDERR, you have to specify 2> for the redirection symbol.
ssh [email protected] "ls -l" >output
You can even do things like:
ssh [email protected] "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 [email protected] ... etc
And it won't ask for a password either. (If your key pair is passwordless)..
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With