larry1chan@qq.com 5 hónapja
commit
e126e5fee3
12 módosított fájl, 390 hozzáadás és 0 törlés
  1. 1 0
      .config/last_ip.txt
  2. 1 0
      .gitignore
  3. 26 0
      Dockerfile
  4. 21 0
      config.ini
  5. 21 0
      config/config.ini
  6. 1 0
      config/last_ip.txt
  7. 8 0
      docker-compose.yml
  8. 100 0
      dynip.py
  9. 135 0
      ip_notifier.py
  10. 0 0
      last_ip.txt
  11. 74 0
      readme.md
  12. 2 0
      requirements.txt

+ 1 - 0
.config/last_ip.txt

@@ -0,0 +1 @@
+113.253.157.203

+ 1 - 0
.gitignore

@@ -0,0 +1 @@
+venv/

+ 26 - 0
Dockerfile

@@ -0,0 +1,26 @@
+# Use an official Python image as a base
+FROM python:3.9-slim
+
+# Set the working directory to /app
+WORKDIR /app
+
+# Copy the script into the container
+COPY ip_notifier.py requirements.txt /app/
+
+# Update pip to the latest version
+RUN pip install --upgrade pip
+
+# Install the required dependencies
+RUN pip install -r requirements.txt
+
+# Expose the port (not needed in this case, but good practice)
+EXPOSE 80
+
+# Create a volume for the config file
+VOLUME /app/config
+#      - /home/yazoo/appdev/dynip/config/config.ini:/app/config.ini
+#      - /home/yazoo/appdev/dynip/config/last_ip.txt:/app/last_ip.txt
+
+
+# Run the command when the container starts
+CMD ["python", "ip_notifier.py"]

+ 21 - 0
config.ini

@@ -0,0 +1,21 @@
+[General]
+check_interval = 600
+notify_methods = email,telegram  ; Comma-separated: email, telegram, nextcloud (or leave empty for default: email)
+last_ip_file = config/last_ip.txt
+
+[Email]
+from = larry1chan@qq.com
+to = larry1chan@gmail.com
+server = smtp.qq.com
+port = 465
+user = larry1chan@qq.com
+pass = xhybazbbucdyceed
+
+[Telegram]
+bot_token = 258792305:AAEF1WvtLOPj2DlXecT1fIBMKOm4OaXnMOU
+chat_id = 262500746
+
+[Nextcloud]
+url = https://1984.algometic.com
+token = your_nextcloud_token
+room = your_room_token

+ 21 - 0
config/config.ini

@@ -0,0 +1,21 @@
+[General]
+check_interval = 5 
+notify_methods = email,telegram  ; Comma-separated: email, telegram, nextcloud (or leave empty for default: email)
+last_ip_file = config/last_ip.txt
+
+[Email]
+from = larry1chan@qq.com
+to = larry1chan@gmail.com
+server = smtp.qq.com
+port = 465
+user = larry1chan@qq.com
+pass = xhybazbbucdyceed
+
+[Telegram]
+bot_token = 258792305:AAEF1WvtLOPj2DlXecT1fIBMKOm4OaXnMOU
+chat_id = 262500746
+
+[Nextcloud]
+url = https://1984.algometic.com
+token = your_nextcloud_token
+room = your_room_token

+ 1 - 0
config/last_ip.txt

@@ -0,0 +1 @@
+113.253.157.203

+ 8 - 0
docker-compose.yml

@@ -0,0 +1,8 @@
+services:
+  ip-notifier:
+    image: ip-notifier:latest
+
+    volumes:
+      - ./config:/app/config
+
+    restart: unless-stopped

+ 100 - 0
dynip.py

@@ -0,0 +1,100 @@
+import time
+import requests
+import smtplib
+from email.mime.text import MIMEText
+
+# --- CONFIGURATION ---
+CHECK_INTERVAL = 300  # seconds
+NOTIFY_METHOD = "email"  # "email", "telegram", or "nextcloud"
+LAST_IP_FILE = "last_ip.txt"
+
+# Email settings
+EMAIL_FROM = "larry1chan@qq.com"
+EMAIL_TO = "larry1chan@gmail.com"
+SMTP_SERVER = "smtp.qq.com"
+SMTP_PORT = 465
+SMTP_USER = "larry1chan@qq.com"
+SMTP_PASS = "xhybazbbucdyceed"
+
+# Telegram settings
+TELEGRAM_BOT_TOKEN = "258792305:AAEF1WvtLOPj2DlXecT1fIBMKOm4OaXnMOU"
+TELEGRAM_CHAT_ID = "262500746"
+
+# Nextcloud Talk settings
+NEXTCLOUD_URL = "https://1984.algometic.com"
+NEXTCLOUD_TOKEN = "your_nextcloud_token"
+NEXTCLOUD_ROOM = "your_room_token"
+
+def get_public_ip():
+    try:
+        return requests.get("https://api.ipify.org").text.strip()
+    except Exception as e:
+        print(f"Error getting public IP: {e}")
+        return None
+
+def send_email(subject, body):
+    try:
+        msg = MIMEText(body)
+        msg["Subject"] = subject
+        msg["From"] = EMAIL_FROM
+        msg["To"] = EMAIL_TO
+        with smtplib.SMTP_SSL(SMTP_SERVER, SMTP_PORT) as server:
+            server.set_debuglevel(1)
+            #server.starttls()
+            server.login(SMTP_USER, SMTP_PASS)
+            server.sendmail(EMAIL_FROM, EMAIL_TO, msg.as_string())
+    except Exception as e:
+        print(f"Error sending email: {e}")
+    return False
+
+
+        
+
+def send_telegram(message):
+    url = f"https://api.telegram.org/bot{TELEGRAM_BOT_TOKEN}/sendMessage"
+    data = {"chat_id": TELEGRAM_CHAT_ID, "text": message}
+    requests.post(url, data=data)
+
+def send_nextcloud_talk(message):
+    url = f"{NEXTCLOUD_URL}/ocs/v2.php/apps/spreed/api/v1/chat/{NEXTCLOUD_ROOM}"
+    headers = {
+        "OCS-APIRequest": "true",
+        "Authorization": f"Bearer {NEXTCLOUD_TOKEN}"
+    }
+    data = {"message": message}
+    requests.post(url, headers=headers, data=data)
+
+def notify(ip):
+    message = f"Public IP changed to: {ip}"
+    if NOTIFY_METHOD == "email":
+        send_email("IP Address Changed", message)
+    elif NOTIFY_METHOD == "telegram":
+        send_telegram(message)
+    elif NOTIFY_METHOD == "nextcloud":
+        send_nextcloud_talk(message)
+    else:
+        print("Unknown notification method.")
+
+def load_last_ip():
+    try:
+        with open(LAST_IP_FILE, "r") as f:
+            return f.read().strip()
+    except FileNotFoundError:
+        return None
+
+def save_last_ip(ip):
+    with open(LAST_IP_FILE, "w") as f:
+        f.write(ip)
+
+def main():
+    last_ip = load_last_ip()
+    while True:
+        ip = get_public_ip()
+        if ip and ip != last_ip:
+            notify(ip)
+            save_last_ip(ip)
+            last_ip = ip
+        time.sleep(CHECK_INTERVAL)
+
+if __name__ == "__main__":
+    main()

+ 135 - 0
ip_notifier.py

@@ -0,0 +1,135 @@
+import time
+import requests
+import smtplib
+from email.mime.text import MIMEText
+import configparser
+
+# Load configuration from config.ini
+config = configparser.ConfigParser()
+config.read('config/config.ini')
+
+if not config.sections():
+    raise ValueError("Config file 'config.ini' not found or empty. Please create it with the required settings.")
+
+# General settings
+CHECK_INTERVAL = config.getint('General', 'check_interval', fallback=300)  # Unused in one-shot mode, but kept for reference
+NOTIFY_METHODS_STR = config.get('General', 'notify_methods', fallback='email')  # Comma-separated string, default to 'email'
+LAST_IP_FILE = config.get('General', 'last_ip_file', fallback='last_ip.txt')
+
+# Parse notify_methods into a list (strip whitespace, lowercase, remove duplicates)
+NOTIFY_METHODS = list(set(m.strip().lower() for m in NOTIFY_METHODS_STR.split(',') if m.strip()))
+if not NOTIFY_METHODS:
+    NOTIFY_METHODS = ['email']  # Default to email if empty or invalid
+
+# Email settings
+EMAIL_FROM = config.get('Email', 'from', fallback='')
+EMAIL_TO = config.get('Email', 'to', fallback='')
+SMTP_SERVER = config.get('Email', 'server', fallback='')
+SMTP_PORT = config.getint('Email', 'port', fallback=465)
+SMTP_USER = config.get('Email', 'user', fallback='')
+SMTP_PASS = config.get('Email', 'pass', fallback='')
+
+# Telegram settings
+TELEGRAM_BOT_TOKEN = config.get('Telegram', 'bot_token', fallback='')
+TELEGRAM_CHAT_ID = config.get('Telegram', 'chat_id', fallback='')
+
+# Nextcloud Talk settings
+NEXTCLOUD_URL = config.get('Nextcloud', 'url', fallback='')
+NEXTCLOUD_TOKEN = config.get('Nextcloud', 'token', fallback='')
+NEXTCLOUD_ROOM = config.get('Nextcloud', 'room', fallback='')
+
+def get_public_ip():
+    try:
+        return requests.get("https://api.ipify.org").text.strip()
+    except Exception as e:
+        print(f"Error getting public IP: {e}")
+        return None
+
+def send_email(subject, body):
+    if not all([EMAIL_FROM, EMAIL_TO, SMTP_SERVER, SMTP_USER, SMTP_PASS]):
+        print("Email settings incomplete in config.")
+        return False
+    try:
+        msg = MIMEText(body)
+        msg["Subject"] = subject
+        msg["From"] = EMAIL_FROM
+        msg["To"] = EMAIL_TO
+        with smtplib.SMTP_SSL(SMTP_SERVER, SMTP_PORT) as server:
+            server.set_debuglevel(1)
+            # server.starttls()  # Commented as in original; using SSL
+            server.login(SMTP_USER, SMTP_PASS)
+            server.sendmail(EMAIL_FROM, EMAIL_TO, msg.as_string())
+        return True
+    except Exception as e:
+        print(f"Error sending email: {e}")
+        return False
+
+def send_telegram(message):
+    if not all([TELEGRAM_BOT_TOKEN, TELEGRAM_CHAT_ID]):
+        print("Telegram settings incomplete in config.")
+        return False
+    try:
+        url = f"https://api.telegram.org/bot{TELEGRAM_BOT_TOKEN}/sendMessage"
+        data = {"chat_id": TELEGRAM_CHAT_ID, "text": message}
+        response = requests.post(url, data=data)
+        return response.status_code == 200
+    except Exception as e:
+        print(f"Error sending Telegram message: {e}")
+        return False
+
+def send_nextcloud_talk(message):
+    if not all([NEXTCLOUD_URL, NEXTCLOUD_TOKEN, NEXTCLOUD_ROOM]):
+        print("Nextcloud settings incomplete in config.")
+        return False
+    try:
+        url = f"{NEXTCLOUD_URL}/ocs/v2.php/apps/spreed/api/v1/chat/{NEXTCLOUD_ROOM}"
+        headers = {
+            "OCS-APIRequest": "true",
+            "Authorization": f"Bearer {NEXTCLOUD_TOKEN}"
+        }
+        data = {"message": message}
+        response = requests.post(url, headers=headers, data=data)
+        return response.status_code == 200
+    except Exception as e:
+        print(f"Error sending Nextcloud message: {e}")
+        return False
+
+def notify(ip):
+    message = f"Public IP changed to: {ip}"
+    for method in NOTIFY_METHODS:
+        if method == "email":
+            success = send_email("IP Address Changed", message)
+            print(f"Email notification {'sent' if success else 'failed'}.")
+        elif method == "telegram":
+            success = send_telegram(message)
+            print(f"Telegram notification {'sent' if success else 'failed'}.")
+        elif method == "nextcloud":
+            success = send_nextcloud_talk(message)
+            print(f"Nextcloud notification {'sent' if success else 'failed'}.")
+        else:
+            print(f"Unknown notification method: {method}. Skipping.")
+
+def load_last_ip():
+    try:
+        with open(LAST_IP_FILE, "r") as f:
+            return f.read().strip()
+    except FileNotFoundError:
+        return None
+
+def save_last_ip(ip):
+    with open(LAST_IP_FILE, "w") as f:
+        f.write(ip)
+
+def main():
+    last_ip = load_last_ip()
+    while True:
+        print("Checking for public IP...")
+        ip = get_public_ip()
+        if ip and ip != last_ip:
+            notify(ip)
+            save_last_ip(ip)
+            last_ip = ip
+        time.sleep(CHECK_INTERVAL)
+
+if __name__ == "__main__":
+    main()

+ 0 - 0
last_ip.txt


+ 74 - 0
readme.md

@@ -0,0 +1,74 @@
+# IP Address Change Notifier
+
+==========================
+
+This script is designed to monitor and notify when the public IP address of a device changes. It uses various notification methods, including email, Telegram, and Nextcloud Talk.
+
+## Configuration
+
+---
+
+The script relies on a configuration file named `config.ini` to store settings. The file should be in the same directory as the script.
+
+### General Settings
+
+* `check_interval`: The interval in seconds between IP checks (default: 300)
+* `notify_methods`: A comma-separated list of notification methods (default: email)
+* `last_ip_file`: The file to store the last known IP address (default: last_ip.txt)
+
+### Email Settings
+
+* `from`: The sender's email address
+* `to`: The recipient's email address
+* `server`: The SMTP server address
+* `port`: The SMTP server port (default: 465)
+* `user`: The SMTP username
+* `pass`: The SMTP password
+
+### Telegram Settings
+
+* `bot_token`: The Telegram bot token
+* `chat_id`: The Telegram chat ID
+
+### Nextcloud Talk Settings
+
+* `url`: The Nextcloud URL
+* `token`: The Nextcloud token
+* `room`: The Nextcloud room ID
+
+## How it Works
+
+---
+
+1. The script loads the configuration from `config.ini`.
+2. It checks the public IP address using the `get_public_ip` function.
+3. If the IP address has changed, it sends a notification using the specified methods.
+4. The last known IP address is stored in the `last_ip_file`.
+
+## Notification Methods
+
+---
+
+The script supports the following notification methods:
+
+* Email: Sends an email using the specified SMTP server and credentials.
+* Telegram: Sends a message using the Telegram bot token and chat ID.
+* Nextcloud Talk: Sends a message using the Nextcloud URL, token, and room ID.
+
+## Running the Script
+
+---
+
+To run the script, simply execute it using Python:
+
+```bash
+python ip_notifier.py
+```
+
+Note: Make sure to replace `ip_notifier.py` with the actual script name.
+
+## Troubleshooting
+
+---
+
+If you encounter any issues, check the script's output for error messages. Ensure that the configuration file is correct and that the notification methods are properly set up.

+ 2 - 0
requirements.txt

@@ -0,0 +1,2 @@
+requests
+configparser