yacine R
yacine R

Reputation: 39

How to use the "watch" command with SSH

I have a script that monitors a specific server, giving me the disk usage, CPU usage, etc. I am using 2 Ubuntu VMs: I run the script on the server using SSH (ssh user@ip < script.sh from the first VM), and I want to make it show values in real time, so I tried 2 approaches I found on here:

1. while loop with clear

The first approach is using a while loop with "clear" to make the script run multiple times, giving new values every time and clearing the previous output like so:

while true
do
      clear; 
      # bunch of code
done

The problem here is that it doesn't clear the terminal, it just keeps printing the new results one after another.

2. watch

The second approach uses watch:

watch -n 1 Script.sh

This works fine on the local machine (to monitor the current machine where the script is), but I can't find a way to make it run via SSH. Something like

ssh user@ip < 'watch -n 1 script.sh'

works in principle, but requires that the script be present on the server, which I want to avoid. Is there any way to run watch for the remote execution (via SSH) of a script that is present on the local machine?

Upvotes: 1

Views: 1305

Answers (1)

morrisunix
morrisunix

Reputation: 31

For your second approach (using watch), what you can do instead is to run watch locally (from within the first VM) with an SSH command and piped-in script like this:

watch -n 1 'ssh user@ip < script.sh'

The drawback of this is that it will reconnect in each watch iteration (i.e., once a second), which some server configurations might not allow. See here for how to let SSH re-use the same connection for serial ssh runs.

But if what you want to do is to monitor servers, what I really recommend is to use a monitoring system like 'telegraf'.

Upvotes: 2

Related Questions