Cron 公用 IP 到日誌檔

Cron 公用 IP 到日誌檔

我想使用 cron 將我的公共 IP 記錄到文件中。像這樣的東西:

2021-05-17T01:11:46 99.99.99.99
2021-05-17T01:12:46 99.99.99.99
2021-05-17T01:13:46 99.99.99.99

這是我拼湊起來的:

* * * * * { date +%FT%T | tr "\n" " "; curl https://ipinfo.io/ip -s ; echo "" ; } >> /home/mario/logs/pubip.log

它在 sh 提示符號下工作*,但是一旦我將星號放在前面並將其放入 crontab -e 中,我會收到以下錯誤:

/bin/sh: 1: Syntax error: end of file unexpected (expecting "}")

作業系統:Ubuntu 20.04.2 LTS

*必須有一種更優雅的方式來處理格式。我覺得科學怪人很尷尬。

答案1

所以原來是‘%’符號。應該多閱讀文件:crontab(5)

The "sixth" field (the rest of the line) specifies the command to
       be run.  The entire command portion of the line, up to a newline
       or a "%" character, will be executed by /bin/sh or by the shell
       specified in the SHELL variable of the cronfile.  A "%" character
       in the command, unless escaped with a backslash (\), will be
       changed into newline characters, and all data after the first %
       will be sent to the command as standard input.

最終有效的正確 cron 行是

* * * * * { date +\%FT\%T | tr "\n" " "; curl https://ipinfo.io/ip -s ; echo "" ; } >> /home/mario/logs/pubip.log

也就是說,我將按照 @scimerman 的建議將其移至腳本中,以提高可讀性。

答案2

我無法重現你的。如果 cron 命令太龐大,更優雅的方法是將其包裝在單獨的 cron 腳本中並從 crontab 呼叫它:

$ cat ~/crontab.ip 
#!/bin/bash
{ date +%FT%T | tr "\n" " "; curl https://ipinfo.io/ip -s ; echo "" ; } >> ~/log.ip

我的 crontab 是:

$ crontab -l
* * * * * ~/crontab.ip

它應該有效。

答案3

將指令放入 cron 系統時,必須使用指令的完整路徑。

IE,
日期應該/bin/日期
t應該/usr/bin/tr
捲曲應該/usr/bin/curl
迴音應該/usr/bin/echo

相關內容