简体   繁体   English

如何在 SSH 中使用“watch”命令

[英]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:我有一个监视特定服务器的脚本,为我提供磁盘使用情况、CPU 使用情况等。我正在使用 2 个 Ubuntu 虚拟机:我使用 SSH 在服务器上运行脚本( ssh user@ip < script.sh来自第一个脚本。 ),我想让它实时显示值,所以我尝试了在这里找到的 2 种方法:

1. while loop with clear 1. while循环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:第一种方法是使用带有“clear”的while循环使脚本多次运行,每次都给出新值并清除以前的output,如下所示:

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 2. watch

The second approach uses watch :第二种方法使用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.这在本地机器上工作正常(监视脚本所在的当前机器),但我找不到让它通过 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?有没有办法运行watch本地计算机上存在的脚本的远程执行(通过 SSH)?

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 ),您可以做的是使用 SSH 命令和管道输入脚本在本地(从第一个 VM 中)运行watch ,如下所示:

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

The drawback of this is that it will reconnect in each watch iteration (ie, once a second), which some server configurations might not allow.这样做的缺点是它会在每次watch迭代中重新连接(即每秒一次),某些服务器配置可能不允许这样做。 See here for how to let SSH re-use the same connection for serial ssh runs.有关如何让 SSH 重新使用串行ssh运行的相同连接,请参见此处

But if what you want to do is to monitor servers, what I really recommend is to use a monitoring system like 'telegraf'.但是如果你想做的是监控服务器,我真正推荐的是使用像'telegraf'这样的监控系统。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM