Skip to main content

Tự động phát hiện IP công cộng và cập nhật vào Google Cloud / AWS

Project description

IP Updater v2.0 - Tự Động Cập Nhật IP Công Cộng

Python 3.7+ License: MIT

IP Updater là script tự động phát hiện thay đổi IP công cộng và cập nhật vào:

  • Google Cloud Platform: Firewall Rules, Cloud SQL Authorized Networks
  • Amazon Web Services: Security Groups (SSH, MySQL, custom ports)

🚀 Tính Năng Mới v2.0

  • Kiến trúc OOP: Tách lớp rõ ràng, dễ mở rộng
  • CLI Arguments: Hỗ trợ --dry-run, --force, --verbose
  • Xử lý lỗi chi tiết
  • Logging nâng cao: Console & file, nhiều cấp độ
  • Không lặp code: Tuân thủ nguyên tắc DRY
  • Test coverage >85%
  • Cài đặt phụ thuộc linh hoạt: Chỉ cần SDK bạn sử dụng

📋 Yêu Cầu

  • Python 3.7+
  • Phụ thuộc (tùy provider):
    • GCP: google-cloud-compute, google-api-python-client
    • AWS: boto3
    • Chung: requests

⚡ Cài Đặt Nhanh

1. Clone & Cài Dependencies

git clone https://github.com/lequyettien/ip-updater.git
cd ip-updater
python3 -m pip install -r requirements.txt

2. Tạo & Chỉnh Sửa File Cấu Hình

cp config.json.example config.json
# Sửa config.json theo thông tin của bạn

3. Cấu Hình Credentials

Google Cloud Platform

# Cách 1: Biến môi trường (khuyến nghị)
export GOOGLE_APPLICATION_CREDENTIALS="$PWD/gcp-credentials.json"

# Cách 2: Gcloud ADC
gcloud auth application-default login

Amazon Web Services

# Cách 1: AWS CLI
aws configure

# Cách 2: Biến môi trường
export AWS_ACCESS_KEY_ID="your-key"
export AWS_SECRET_ACCESS_KEY="your-secret"

4. Chạy Script

python3 auto_update_ip.py                # Chạy bình thường
python3 auto_update_ip.py --dry-run      # Chạy thử, không thay đổi thật
python3 auto_update_ip.py --force        # Buộc cập nhật kể cả IP không đổi
python3 auto_update_ip.py --verbose      # Hiển thị log chi tiết

🛠️ Sử Dụng

CLI Options

usage: auto_update_ip.py [-h] [-c CONFIG] [--dry-run] [--force] [-v] [--version]

options:
  -h, --help            Hiển thị help
  -c, --config CONFIG   Đường dẫn file cấu hình (default: config.json)
  --dry-run             Chạy thử, không thực hiện thay đổi thực tế
  --force               Buộc cập nhật kể cả khi IP không thay đổi
  -v, --verbose         Hiển thị log chi tiết (DEBUG level)
  --version             Hiển thị version

Ví dụ:

python3 auto_update_ip.py                          # Chạy với config mặc định
python3 auto_update_ip.py --config prod.json       # Dùng config file khác
python3 auto_update_ip.py --dry-run                # Chạy thử
python3 auto_update_ip.py --force                  # Buộc cập nhật
python3 auto_update_ip.py --verbose                # Log chi tiết

Cấu Trúc config.json

{
  "gcp": {
    "project_id": "your-gcp-project",
    "credentials_file": "gcp-credentials.json",
    "firewall_rules": ["allow-office-ssh", "allow-office-https"],
    "sql_instances": ["production-mysql", "staging-postgres"]
  },
  "aws": {
    "region": "ap-southeast-1",
    "security_groups_ssh": [
      {
        "group_id": "sg-xxxxxxxxx",
        "description": "Office SSH Access"
      }
    ],
    "security_groups_mysql": [
      {
        "group_id": "sg-yyyyyyyyy",
        "description": "Office MySQL Access"
      }
    ],
    "ports_ssh": [
      {"protocol": "tcp", "port": 22, "description": "SSH"}
    ],
    "ports_mysql": [
      {"protocol": "tcp", "port": 3306, "description": "MySQL"}
    ]
  },
  "ip_cache_file": "last_known_ip.txt"
}

⏰ Chạy Định Kỳ

Cron

Chạy mỗi 5 phút:

*/5 * * * * cd /path/to/ip-updater && /usr/bin/python3 auto_update_ip.py >> /var/log/ip_update.log 2>&1

Chạy mỗi giờ:

0 * * * * cd /path/to/ip-updater && /usr/bin/python3 auto_update_ip.py

Systemd Timer (Linux)

Tạo service file /etc/systemd/system/ip-updater.service:

[Unit]
Description=IP Updater Service
After=network-online.target

[Service]
Type=oneshot
WorkingDirectory=/path/to/ip-updater
ExecStart=/usr/bin/python3 /path/to/ip-updater/auto_update_ip.py
User=your-user
Environment="GOOGLE_APPLICATION_CREDENTIALS=/path/to/gcp-credentials.json"

[Install]
WantedBy=multi-user.target

Tạo timer file /etc/systemd/system/ip-updater.timer:

[Unit]
Description=IP Updater Timer
Requires=ip-updater.service

[Timer]
OnBootSec=5min
OnUnitActiveSec=5min

[Install]
WantedBy=timers.target

Kích hoạt timer:

sudo systemctl daemon-reload
sudo systemctl enable ip-updater.timer
sudo systemctl start ip-updater.timer
sudo systemctl status ip-updater.timer

🧪 Testing

Chạy tests

python3 -m pip install pytest pytest-cov
pytest -v
pytest --cov=auto_update_ip --cov-report=html

Coverage hiện tại: >85%

  • IP detection & caching
  • Load & validate config
  • Update GCP Firewall & Cloud SQL
  • Update AWS Security Groups
  • Error handling
  • Dry-run mode

📂 Cấu Trúc Thư Mục

ip-updater/
├── auto_update_ip.py          # Main script (v2.0)
├── config.json                # Config cá nhân (gitignored)
├── config.json.example        # Mẫu config
├── gcp-credentials.json       # GCP credentials (gitignored)
├── requirements.txt           # Python dependencies
├── pytest.ini                 # Pytest config
├── .gitignore                 # Git ignore rules
├── README.md                  # Tài liệu này
├── CHANGELOG.md               # Lịch sử phiên bản
├── LICENSE                    # MIT License
├── tests/
│   ├── conftest.py
│   └── test_auto_update_ip.py
└── ip_update.log              # Log file (tự động tạo)

🔐 Security Best Practices

Credentials

  • Không commit credentials vào git
  • Dùng .gitignore để loại trừ file nhạy cảm
  • Sử dụng environment variables khi có thể
  • Set quyền file: chmod 600 gcp-credentials.json

IAM Permissions

GCP

  • Roles: roles/compute.securityAdmin, roles/cloudsql.admin
  • Hoặc custom role:
compute.firewalls.get
compute.firewalls.update
cloudsql.instances.get
cloudsql.instances.update

AWS

IAM policy tối thiểu:

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Action": [
        "ec2:AuthorizeSecurityGroupIngress",
        "ec2:RevokeSecurityGroupIngress",
        "ec2:DescribeSecurityGroups"
      ],
      "Resource": "*"
    }
  ]
}

Network Security

  • Chỉ mở port cần thiết
  • Sử dụng CIDR /32 cho IP đơn
  • Kiểm tra log thường xuyên
  • Thiết lập cảnh báo khi có thay đổi

🐛 Troubleshooting

Lỗi cấu hình

cp config.json.example config.json
# Sửa lại config.json

Lỗi GCP credentials

ls -la gcp-credentials.json
export GOOGLE_APPLICATION_CREDENTIALS="$PWD/gcp-credentials.json"
gcloud auth application-default login

Lỗi AWS credentials

aws configure
cat ~/.aws/credentials
aws sts get-caller-identity

Không phát hiện thay đổi IP

rm last_known_ip.txt
python3 auto_update_ip.py --force --verbose

Test dry-run

python3 auto_update_ip.py --dry-run --verbose

Kiểm tra logs

tail -f ip_update.log
tail -f ip_update.log | grep "ERROR\|WARNING"

📝 Changelog

v2.0.0 (2025-10-08)

  • Refactor OOP
  • Thêm CLI arguments
  • Logging & error handling nâng cao
  • Loại bỏ lặp code
  • Optional dependencies
  • Test suite đầy đủ
  • Cập nhật tài liệu

v1.0.0

  • Ra mắt ban đầu
  • Update IP cho GCP Firewall, Cloud SQL, AWS Security Groups

🤝 Đóng Góp

Chào mừng mọi đóng góp!

  1. Fork repo
  2. Tạo branch mới (git checkout -b feature/AmazingFeature)
  3. Commit thay đổi (git commit -m 'Add AmazingFeature')
  4. Push lên branch (git push origin feature/AmazingFeature)
  5. Mở Pull Request

📄 License

Dự án theo MIT License - xem LICENSE để biết chi tiết.


👥 Tác Giả

  • Le Quyet Tien

🙏 Cảm Ơn

  • Google Cloud Python SDK
  • AWS Boto3
  • Python Requests library
  • Các contributor

📞 Hỗ Trợ


Made with ❤️ by Le Quyet Tien

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

ez_ip_updater-2.0.0.tar.gz (24.5 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

ez_ip_updater-2.0.0-py3-none-any.whl (12.3 kB view details)

Uploaded Python 3

File details

Details for the file ez_ip_updater-2.0.0.tar.gz.

File metadata

  • Download URL: ez_ip_updater-2.0.0.tar.gz
  • Upload date:
  • Size: 24.5 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.13.7

File hashes

Hashes for ez_ip_updater-2.0.0.tar.gz
Algorithm Hash digest
SHA256 ff01cefc7243908cddff20cc2ef1f5ff6a6f02bb42b942a04814d0e3357361f6
MD5 0f5f6bf4580a592c3eb170dccda2a4e2
BLAKE2b-256 f489759134ab1532795804d96d2aa933656f8b2d838866c8c9fc067a6edf2c42

See more details on using hashes here.

File details

Details for the file ez_ip_updater-2.0.0-py3-none-any.whl.

File metadata

  • Download URL: ez_ip_updater-2.0.0-py3-none-any.whl
  • Upload date:
  • Size: 12.3 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.13.7

File hashes

Hashes for ez_ip_updater-2.0.0-py3-none-any.whl
Algorithm Hash digest
SHA256 5f1cdc58ec594f82b71ac7131b3c14a4a4e1fecce4575f4d3aa993106b006cdc
MD5 c0b4956195adac745443a9a321158584
BLAKE2b-256 da24e4e01fb4e68aaaaf4dd5ca012954dc5220ff57dd3dedacd2c76de6840a79

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page