Running Commands on Remote Linux Server Using SSH

I am writing a Bash Script wherein I need to run some set of commands on a remote Linux server from my local computer using SSH. I want the results to be displayed on the terminal screen or dump the results in a file on my local system.

How can achieve this? Is the following syntax correct?

\#!/bin/bash
.
.
.
.

ssh <user>@<remote_host> 'COMMAND >> /path/to/file ; scp /path/to/file <user>@<local_host>:<location>; exit'
.
.

Thanks in advance.

Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

Solution 1

To have the results display on the terminal screen:

ssh <user>@<remote_host> COMMAND

To have the results saved to a file:

ssh <user>@<remote_host> COMMAND > FILE

To have the results both displayed on the terminal screen and saved to a file:

ssh <user>@<remote_host> COMMAND | tee FILE

Solution 2

If you do not intervene, stdout will normally appear on the local terminal. It can be saved to a local file as follow:

ssh <user>@<remote_host> COMMAND >my_local_file

Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply