Öffentliche Cron-IP zur Protokolldatei

Öffentliche Cron-IP zur Protokolldatei

Ich möchte meine öffentliche IP-Adresse mit cron in einer Datei protokollieren. So etwas wie:

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

Folgendes habe ich zusammengeschustert:

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

Es funktioniert* in der sh-Eingabeaufforderung, aber sobald ich die Sternchen davor setze und es in crontab -e eingebe, erhalte ich die folgende Fehlermeldung:

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

Betriebssystem: Ubuntu 20.04.2 LTS

*Es muss einen eleganteren Weg geben, die Formatierung zu handhaben. Was ich frankensteinartig gemacht habe, fühlt sich ziemlich seltsam an.

Antwort1

Es stellte sich also heraus, dass es die '%'-Symbole waren. Hätte die Dokumentation genauer lesen sollen: 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.

Die richtige Cron-Zeile, die am Ende funktioniert hat, ist

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

Trotzdem werde ich dies der Lesbarkeit halber in ein Skript verschieben, wie @scimerman vorgeschlagen hat.

Antwort2

Ich konnte Ihr Problem nicht reproduzieren. Wenn der Befehl für Cron zu umfangreich ist, ist es eleganter, ihn in ein separates Cron-Skript einzubinden und dieses von Crontab aus aufzurufen:

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

und meine Crontab ist:

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

Es sollte funktionieren.

Antwort3

Wenn Sie Befehle in das Cron-System eingeben, müssen Sie den vollständigen Pfad für den Befehl verwenden.

Dh,
Datumsollte sein/bin/date
trsollte sein/usr/bin/tr
Lockesollte sein/usr/bin/curl.
Echosollte sein/usr/bin/echo

verwandte Informationen