L'objectiu d'aquest article és explicar com m'he fet un script que s'envia cada hora al meu correu amb la IP pública que tinc a ma casa.
Aquest és el resultat que necessitava, un correu cada hora que mostra la IP pública, de manera que si canvia ho sabré fàcilment:
Bàsicament, i anant directes al tema, el meu script l'he fet amb Python i el codi és el següent:
#!/usr/bin/env python3
import urllib.request
import datetime
import subprocess
#
SERVEIS = [
"https://api.ipify.org",
"https://ifconfig.me/ip",
"https://ipinfo.io/ip",
]
#
def enviar_correu(missatge):
proc = subprocess.Popen(
["msmtp", "__________________@gmail.com"],
stdin=subprocess.PIPE,
)
proc.communicate(missatge.encode("utf-8"))
#
def obtindre_ip_publica():
for url in SERVEIS:
try:
with urllib.request.urlopen(url, timeout=5) as resposta:
ip = resposta.read().decode("utf-8").strip()
if ip:
return ip
except Exception:
continue
return None
#
def main():
ara = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
ip = obtindre_ip_publica()
if ip:
print(f"{ara} IP pública: {ip}")
enviar_correu(f"Subject: IP publica\n\n{ara} IP publica: {ip}")
#
else:
print(f"{ara} No s'ha pogut obtindre la IP pública")
#
if __name__ == "__main__":
#
main()
Ara bé, per a que funcione necessitem un parell de requisits: necessitem instal·lar msmtp i configurar una contrasenya d'aplicació al nostre perfil de Google, perquè Google no permet les contrasenyes del correu quan fem una aplicació que fa servir l'SMTP per a enviaments de correu de manera externa.
Podem enviar correus de diferents maneres, jo en aquesta ocasió instal·laré msmtp per ser un programari que treballa molt bé i que és molt lleuger, suficient per a enviar correus automàticament sense necessitat de tenir massa processos oberts o un servidor de correus escoltant.
INSTAL·LACIÓ DE MSMTP
Aleshores, primer de tot instal·larem msmtp així:
doas pkg install msmtp
Ràpidament ho tindrem instal·lat:
~]$ doas pkg install msmtp
Updating FreeBSD repository catalogue...
FreeBSD repository is up to date.
All repositories are up to date.
The following 6 package(s) will be affected (of 0 checked):
.
New packages to be INSTALLED:
gmp: 6.3.0
gnutls: 3.8.10
libtasn1: 4.20.0_1
msmtp: 1.8.31
nettle: 3.10.2
p11-kit: 0.25.10
.
Number of packages to be installed: 6
.
The process will require 22 MiB more space.
5 MiB to be downloaded.
.
Proceed with this action? [y/N]: y
[1/6] Fetching nettle-3.10.2.pkg: 100% 2 MiB 1.6MB/s 00:01
[2/6] Fetching gmp-6.3.0.pkg: 100% 416 KiB 426.1kB/s 00:01
[3/6] Fetching libtasn1-4.20.0_1.pkg: 100% 157 KiB 160.9kB/s 00:01
[4/6] Fetching p11-kit-0.25.10.pkg: 100% 512 KiB 524.8kB/s 00:01
[5/6] Fetching gnutls-3.8.10.pkg: 100% 2 MiB 2.5MB/s 00:01
[6/6] Fetching msmtp-1.8.31.pkg: 100% 165 KiB 169.2kB/s 00:01
Checking integrity... done (0 conflicting)
[1/6] Installing gmp-6.3.0...
[1/6] Extracting gmp-6.3.0: 100%
[2/6] Installing libtasn1-4.20.0_1...
[2/6] Extracting libtasn1-4.20.0_1: 100%
[3/6] Installing nettle-3.10.2...
[3/6] Extracting nettle-3.10.2: 100%
[4/6] Installing p11-kit-0.25.10...
[4/6] Extracting p11-kit-0.25.10: 100%
[5/6] Installing gnutls-3.8.10...
[5/6] Extracting gnutls-3.8.10: 100%
[6/6] Installing msmtp-1.8.31...
[6/6] Extracting msmtp-1.8.31: 100%
Ara configurarem msmtp editant el fitxer ~/.msmtprc i afegirem la següent informació:
# Config global
defaults
authon
tlson
tls_trust_file /usr/local/share/certs/ca-root-nss.crt
logfile ~/.msmtp.log
#
# Perfil Gmail
account gmail
host smtp.gmail.com
port 587
from EL_TEU_CORREU@gmail.com
user EL_TEU_CORREU@gmail.com
password LA_TEUA_CONTRASENYA
#
# Comptes predeterminat
account default : gmail
A continuació li donarem permisos amb:
chmod 600 .msmtprc
INSTAL·LACIÓ DE CONTRASENYES D'APLICACIONS A GOOGLE
Entrarem a https://myaccount.google.com/security, i hem de tenir l'accès amb dos passos o doble factor. I fins afegirem "google authenticator".
En este cas, com que anem a fer servir Google Authenticator, necessitarem tenir aquesta App instal·lada en el nostre smartphone o dispositiu mòbil. Podem trobar-la en l'App Store de Google: Google Authenticator.
I bé, una vegada tenim Google Authenticator configurat també com a doble factor, ja podem configurar contrasenyes per a aplicacions. Anirem a https://myaccount.google.com/apppasswords i configurarem la nostra aplicació msmtp-coreu, i això em crearà una contrasenya de l'aplicació, tipo "abcd efgh ijkl mnop", la deixarem en el fitxer .msmtprc sense espais.
PROVANT A ENVIAR CORREUS AMB MSMTP
ara executarem:
$ echo "Funciona!" | msmtp -v __________________@gmail.com
I així, amb el paràmetre -v (verbose) veurem tot el procés que està passant, i en el meu cas veurem que envia el correu sense problemes:
$ echo "Funciona!" | msmtp -v ______________@gmail.com
ignoring system configuration file /usr/local/etc/msmtprc: No such file or directory
loaded user configuration file /home/joan/.msmtprc
falling back to default account
using account default from /home/joan/.msmtprc
host = smtp.gmail.com
port = 587
source ip = (not set)
proxy host = (not set)
proxy port = 0
socket = (not set)
timeout = off
protocol = smtp
domain = localhost
auth = choose
user = ______________@gmail.com
password = *
passwordeval = (not set)
ntlmdomain = (not set)
tls = on
tls_starttls = on
tls_trust_file = /usr/local/share/certs/ca-root-nss.crt
tls_crl_file = (not set)
tls_fingerprint = (not set)
tls_key_file = (not set)
tls_cert_file = (not set)
tls_certcheck = on
tls_min_dh_prime_bits = (not set)
tls_priorities = (not set)
tls_host_override = (not set)
auto_from = off
maildomain = (not set)
from = ______________@gmail.com
from_full_name = (not set)
allow_from_override = on
set_from_header = auto
set_date_header = auto
set_msgid_header = auto
set_to_header = off
remove_bcc_headers = on
dsn_notify = (not set)
dsn_return = (not set)
logfile = /home/joan/.msmtp.log
logfile_time_format = (not set)
syslog = (not set)
aliases = (not set)
reading recipients from the command line
<-- 220 smtp.gmail.com ESMTP 5b1f17b1804b1-477b1078a80sm98417215e9.14 - gsmtp
--> EHLO localhost
<-- 250-smtp.gmail.com at your service, [79.112.88.85]
<-- 250-SIZE 35882577
<-- 250-8BITMIME
<-- 250-STARTTLS
<-- 250-ENHANCEDSTATUSCODES
<-- 250-PIPELINING
<-- 250-CHUNKING
<-- 250 SMTPUTF8
--> STARTTLS
<-- 220 2.0.0 Ready to start TLS
TLS session parameters:
(TLS1.3)-(ECDHE-X25519)-(ECDSA-SECP256R1-SHA256)-(AES-256-GCM)
TLS certificate information:
Subject:
CN=smtp.gmail.com
Issuer:
C=US,O=Google Trust Services,CN=WR2
Validity:
Activation time: Mon Oct 27 09:34:55 2025
Expiration time: Mon Jan 19 09:34:54 2026
Fingerprints:
SHA256: 1A:DE:94:58:8C:94:39:84:28:FA:C1:40:CA:D8:16:77:3E:01:B5:F3:65:29:92:56:C1:1E:
34:03:8B:2C:50:C8
SHA1 (deprecated): F9:64:0A:27:5A:A4:24:86:D0:DA:93:49:8E:B2:E1:3B:43:1C:9E:43
--> EHLO localhost
<-- 250-smtp.gmail.com at your service, [79.112.88.85]
<-- 250-SIZE 35882577
<-- 250-8BITMIME
<-- 250-AUTH LOGIN PLAIN XOAUTH2 PLAIN-CLIENTTOKEN OAUTHBEARER XOAUTH
<-- 250-ENHANCEDSTATUSCODES
<-- 250-PIPELINING
<-- 250-CHUNKING
<-- 250 SMTPUTF8
--> AUTH PLAIN AGpvYW5jYXRhbGFwaW55b0BnbWFpbC5jb20Ad2d5ZW50cmJwYmNlc2pwbQ==
<-- 235 2.7.0 Accepted
--> MAIL FROM:<______________@gmail.com> SMTPUTF8
--> RCPT TO:<______________@gmail.com>
--> DATA
<-- 250 2.1.0 OK 5b1f17b1804b1-477b1078a80sm98417215e9.14 - gsmtp
<-- 250 2.1.5 OK 5b1f17b1804b1-477b1078a80sm98417215e9.14 - gsmtp
<-- 354 Go ahead 5b1f17b1804b1-477b1078a80sm98417215e9.14 - gsmtp
--> From: ______________@gmail.com
--> Date: Thu, 20 Nov 2025 11:14:07 +0100
--> Message-ID: <723be7fcd1f882b148c86d18d7369e96@gmail.com>
--> Funciona!
--> .
<-- 250 2.0.0 OK 1763633649 5b1f17b1804b1-477b1078a80sm98417215e9.14 - gsmtp
--> QUIT
<-- 221 2.0.0 closing connection 5b1f17b1804b1-477b1078a80sm98417215e9.14 - gsmtp
Aleshores ja funciona l'enviament de correus.
PROGRAMANT L'ENVIAMENT DE CORREUS DE MANERA AUTOMÀTICA
Doncs bé, ara que ja ens funciona l'enviament de correus, finalment, ho fiquem al Crontab per a que envie la IP pública cada hora amb la configuració 0 * * * * ORDRE, que quedarà de la següent manera:
$ crontab -l
0 * * * * python3.11 /home/joan/ip_publica.py >> /home/joan/ip_publica.log 2>&1
Ara cada hora rebrem un correu amb la IP pública. Em faré un filtre a Gmail per a que m'etiquete i m'arxive aquestos correus i no em molesten en la bústia principal.












