Python Automation สำหรับงาน IT คู่มือฉบับสมบูรณ์ 2026

Python Automation สำหรับงาน IT คู่มือฉบับสมบูรณ์ 2026
โดย อ.บอม | SiamCafe IT Blog | อัพเดต กุมภาพันธ์ 2026

Python เป็นภาษาโปรแกรมที่ IT Admin และ SysAdmin ควรเรียนรู้มากที่สุดในปี 2026 ด้วยไวยากรณ์ที่อ่านง่าย Library ที่ครบครัน และความสามารถในการทำงานอัตโนมัติทุกรูปแบบ Python ช่วยเปลี่ยนงาน IT ที่ซ้ำซากจากชั่วโมงเหลือวินาที ในคู่มือนี้เราจะแสดงตัวอย่างจริงที่ใช้ได้ทันทีในการจัดการ Server, Network และระบบ IT

ทำไม IT Admin ต้องเขียน Python

Python เป็นภาษาที่เหมาะกับงาน IT Automation มากที่สุดเพราะ:

ติดตั้ง Python สำหรับงาน IT

# Ubuntu/Debian (มี Python 3 อยู่แล้ว)
sudo apt install python3 python3-pip python3-venv

# สร้าง Virtual Environment
python3 -m venv ~/it-scripts
source ~/it-scripts/bin/activate

# ติดตั้ง Library ที่จำเป็น
pip install paramiko     # SSH Automation
pip install netmiko      # Network Device Automation
pip install requests     # HTTP/API
pip install psutil       # System Monitoring
pip install schedule     # Task Scheduling
pip install python-dotenv # Environment Variables
pip install jinja2       # Template Engine

จัดการไฟล์อัตโนมัติ

ลบ Log เก่าอัตโนมัติ

import os
import time
from pathlib import Path

def cleanup_old_logs(log_dir, days=30):
    """ลบไฟล์ Log ที่เก่ากว่า N วัน"""
    cutoff = time.time() - (days * 86400)
    deleted = 0
    freed = 0

    for log_file in Path(log_dir).rglob("*.log*"):
        if log_file.stat().st_mtime < cutoff:
            size = log_file.stat().st_size
            log_file.unlink()
            deleted += 1
            freed += size

    print(f"Deleted {deleted} files, freed {freed/1024/1024:.1f} MB")

cleanup_old_logs("/var/log", days=30)

Backup Config Files

import shutil
from datetime import datetime

def backup_configs(config_paths, backup_dir="/backup/configs"):
    """Backup Configuration Files พร้อม Timestamp"""
    timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
    dest = f"{backup_dir}/{timestamp}"
    os.makedirs(dest, exist_ok=True)

    for path in config_paths:
        if os.path.exists(path):
            shutil.copy2(path, dest)
            print(f"Backed up: {path}")

configs = [
    "/etc/nginx/nginx.conf",
    "/etc/ssh/sshd_config",
    "/etc/fail2ban/jail.local",
]
backup_configs(configs)

SSH Automation ด้วย Paramiko

import paramiko

def run_remote_command(host, user, key_path, command):
    """รันคำสั่งบน Remote Server ผ่าน SSH"""
    client = paramiko.SSHClient()
    client.set_missing_host_key_policy(paramiko.AutoAddPolicy())

    try:
        client.connect(host, username=user,
                      key_filename=key_path, port=22)
        stdin, stdout, stderr = client.exec_command(command)
        output = stdout.read().decode()
        errors = stderr.read().decode()

        if errors:
            print(f"[{host}] Error: {errors}")
        return output
    finally:
        client.close()

# ใช้งาน: ตรวจสอบ Disk ทุก Server
servers = ["192.168.1.10", "192.168.1.11", "192.168.1.12"]
for server in servers:
    result = run_remote_command(
        server, "admin", "/home/admin/.ssh/id_ed25519",
        "df -h / | tail -1"
    )
    print(f"{server}: {result.strip()}")
Tip: สำหรับการจัดการ Server หลายเครื่องพร้อมกัน ลองใช้ Ansible ซึ่งเขียนด้วย Python เช่นกัน แต่ไม่ต้องเขียนโค้ดเอง ใช้ YAML ในการกำหนด Task

Network Automation ด้วย Netmiko

from netmiko import ConnectHandler

def backup_switch_config(device_info):
    """Backup Config จาก Network Switch"""
    connection = ConnectHandler(**device_info)
    config = connection.send_command("show running-config")
    connection.disconnect()
    return config

# Cisco Switch
cisco_sw = {
    "device_type": "cisco_ios",
    "host": "192.168.1.1",
    "username": "admin",
    "password": "secret",
}

config = backup_switch_config(cisco_sw)
with open(f"switch_backup_{cisco_sw['host']}.txt", "w") as f:
    f.write(config)
print("Switch config backed up!")

Netmiko รองรับอุปกรณ์หลากหลาย ทั้ง Cisco, MikroTik, Juniper, HP และ Ubiquiti ศึกษาเพิ่มเติมเกี่ยวกับ การเลือก Managed Switch ที่เหมาะสม

Monitoring Script

import psutil
import requests
import socket

def check_system_health():
    """ตรวจสอบสุขภาพ Server"""
    cpu = psutil.cpu_percent(interval=1)
    ram = psutil.virtual_memory().percent
    disk = psutil.disk_usage('/').percent

    alerts = []
    if cpu > 80:
        alerts.append(f"CPU สูง: {cpu}%")
    if ram > 85:
        alerts.append(f"RAM สูง: {ram}%")
    if disk > 90:
        alerts.append(f"Disk เกือบเต็ม: {disk}%")

    return {
        "hostname": socket.gethostname(),
        "cpu": cpu, "ram": ram, "disk": disk,
        "alerts": alerts
    }

def send_line_notify(token, message):
    """ส่ง Alert ผ่าน LINE Notify"""
    requests.post(
        "https://notify-api.line.me/api/notify",
        headers={"Authorization": f"Bearer {token}"},
        data={"message": message}
    )

# ใช้งาน
health = check_system_health()
if health["alerts"]:
    msg = f"\n[{health['hostname']}]\n" + "\n".join(health["alerts"])
    send_line_notify("YOUR_LINE_TOKEN", msg)

Backup Automation

import subprocess
from datetime import datetime

def backup_mysql(db_name, user, password, backup_dir):
    """Backup MySQL Database"""
    timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
    filename = f"{backup_dir}/{db_name}_{timestamp}.sql.gz"

    cmd = f"mysqldump -u {user} -p{password} {db_name} | gzip > {filename}"
    result = subprocess.run(cmd, shell=True, capture_output=True)

    if result.returncode == 0:
        size = os.path.getsize(filename)
        print(f"Backup OK: {filename} ({size/1024/1024:.1f} MB)")
        return filename
    else:
        print(f"Backup FAILED: {result.stderr.decode()}")
        return None

# Backup ทุก Database
databases = ["wordpress", "nextcloud", "gitea"]
for db in databases:
    backup_mysql(db, "backup_user", "secret", "/backup/mysql")

เรียก API อัตโนมัติ

import requests

def check_ssl_expiry(domain):
    """ตรวจสอบวันหมดอายุ SSL Certificate"""
    import ssl, socket
    from datetime import datetime

    context = ssl.create_default_context()
    with socket.create_connection((domain, 443)) as sock:
        with context.wrap_socket(sock, server_hostname=domain) as ssock:
            cert = ssock.getpeercert()
            expiry = datetime.strptime(
                cert['notAfter'], '%b %d %H:%M:%S %Y %Z'
            )
            days_left = (expiry - datetime.now()).days
            return days_left

# ตรวจสอบ SSL ทุกเว็บ
websites = [
    "icafeforex.com",
    "siamlancard.com",
    "siam2r.com",
    "siamcafe.net"
]
for site in websites:
    days = check_ssl_expiry(site)
    status = "OK" if days > 30 else "WARNING"
    print(f"{site}: SSL expires in {days} days [{status}]")

ตั้งเวลารัน Script

ใช้ Crontab (Linux)

# แก้ไข Crontab
crontab -e

# รัน Backup ทุกวัน ตี 2
0 2 * * * /home/admin/it-scripts/bin/python /home/admin/scripts/backup.py

# รัน Health Check ทุก 5 นาที
*/5 * * * * /home/admin/it-scripts/bin/python /home/admin/scripts/health_check.py

# ลบ Log เก่าทุกวันอาทิตย์
0 3 * * 0 /home/admin/it-scripts/bin/python /home/admin/scripts/cleanup_logs.py

Best Practices

สำหรับผู้ที่สนใจใช้ Python สร้าง Trading Bot หรือ EA สำหรับ Forex สามารถศึกษาเพิ่มเติมได้ที่ iCafeForex สอนเทรด Forex

คำถามที่พบบ่อย

ไม่เคยเขียนโค้ดมาก่อน เริ่มได้ไหม?

ได้เลย Python ออกแบบมาให้ง่าย เริ่มจากการเขียน Script เล็กทีละอัน เช่น ลบ Log เก่า หรือ Ping Server แล้วค่อยเพิ่มความซับซ้อน ไม่ต้องเป็น Developer ก็เขียน Python สำหรับงาน IT ได้

Python 2 หรือ Python 3?

Python 3 เท่านั้น Python 2 หมดอายุการสนับสนุนตั้งแต่ปี 2020 ในปี 2026 ไม่มีเหตุผลที่จะใช้ Python 2 อีกต่อไป

Bash Script กับ Python ต่างกันอย่างไร?

Bash เหมาะสำหรับงานง่ายที่เรียกคำสั่ง Linux ต่อกัน Python เหมาะสำหรับงานที่ซับซ้อนกว่า เช่น Parse JSON, เรียก API, จัดการ Database หรืองานที่ต้องใช้ Logic มาก ทั้งสองใช้ร่วมกันได้ดี

สรุป

Python Automation เป็นทักษะที่จะเปลี่ยนชีวิตการทำงาน IT ของคุณ งานที่เคยใช้เวลาหลายชั่วโมงจะเหลือเพียงไม่กี่วินาที เริ่มต้นจากงานง่ายที่ทำซ้ำทุกวัน แล้วค่อยขยายไปยังงานที่ซับซ้อนขึ้น ไม่นานคุณจะมี Script Collection ที่ช่วยให้ทำงานได้อย่างมีประสิทธิภาพกว่าเดิมหลายเท่า

📖 บทความที่เกี่ยวข้อง

Python Automation สำหรับงาน IT คู่มือฉบับสมบูรณ์ 2026อ่านบทความ → Python Alembic Automation Script — คู่มือฉบับสมบูรณ์ 2026อ่านบทความ → Python Alembic Career Development IT — คู่มือฉบับสมบูรณ์ 2026อ่านบทความ → Python Alembic CI CD Automation Pipeline — คู่มือฉบับสมบูรณ์ 2026อ่านบทความ → Python Alembic Compliance Automation — คู่มือฉบับสมบูรณ์ 2026อ่านบทความ →

📚 ดูบทความทั้งหมด →