通过 ssh 使用 watch

Using watch with ssh

我有以下命令运行在本地机器上正常运行。

watch -t -n1 "echo `date '+%Y-%m-%d %H:%M:%S'` | tee -a Time.txt" &>/dev/null &

但是当我从远程机器 运行 它时,我不会创建预期的输出,即 Time.txt 不会被创建并且不会 运行ning 作为后台进程。

ssh ipaddress watch -t -n1 "echo `date '+%Y-%m-%d %H:%M:%S'` | tee -a Time.txt" &>/dev/null &

请帮我解决这个问题。我已经尝试了多个选项,例如将 ', " 用于 watch 命令,但它并没有帮助我。

您的 shell 语法不正确:explainshell

并在 运行 命令时抛出此错误:

Error opening terminal: unknown.

您应该使用选项 -t

-t      Force pseudo-tty allocation.  This can be used to execute arbitrary screen-based programs on a
        remote machine, which can be very useful, e.g. when implementing menu services.  Multiple -t
        options force tty allocation, even if ssh has no local tty.

并引用整个命令并将其传递给 ssh,并在必要时转义字符。附上explainshell

ssh -t ipaddress 'watch -t -n1 "echo `date +%Y-%m-%d\ %H:%M:%S` | tee -a Time.txt" \&\>/dev/null \&'
  • 无需使用echo输出子shell的结果。
  • 无需使用 tee 附加到文件。
  • 无需使用watch休眠一秒

试试这个。

ssh -t ipaddress 'while sleep 1; do date +%Y-%m-%d\ %H:%M:%S >> Time.txt; done &'