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

SiamCafe.net Since 1997 | 19/02/2026

สารบัญ

ทำไม Python ถึงเป็นภาษาอันดับ 1 สำหรับ Automation

Python เป็นภาษาที่ SysAdmin และ DevOps Engineer ทั่วโลกเลือกใช้สำหรับ Automation เพราะหลายเหตุผล: syntax อ่านง่ายเหมือนภาษาอังกฤษ มี library สำเร็จรูปเป็นพันๆ ตัว ทำงานได้ทั้ง Linux, Windows, macOS และมี community ที่ใหญ่มาก

ผมทำงาน IT มากว่า 20 ปี เริ่มจากเขียน Bash script แล้วย้ายมา Python ตั้งแต่ปี 2010 ตอนนี้ Python ช่วยประหยัดเวลาผมอย่างน้อย 10 ชั่วโมง/สัปดาห์ จากงานที่เคยทำมือ เช่น backup, monitoring, log analysis, report generation

เปรียบเทียบกับ Bash:

เกณฑ์BashPython
ความง่ายง่ายสำหรับคำสั่งสั้นๆง่ายสำหรับทุกขนาด
Error Handlingจำกัดครบถ้วน (try/except)
Cross-platformLinux/macOS เท่านั้นทุก OS
Libraryจำกัดเป็นพันๆ ตัว
Testingยากง่าย (pytest, unittest)

เริ่มต้น Python สำหรับ SysAdmin

ติดตั้ง Python:

# Ubuntu/Debian
sudo apt install python3 python3-pip python3-venv

# CentOS/RHEL
sudo yum install python3 python3-pip

# ตรวจสอบ version
python3 --version

สร้าง Virtual Environment:

python3 -m venv ~/automation-env
source ~/automation-env/bin/activate
pip install paramiko requests psutil schedule

โครงสร้างโปรเจกต์:

automation/
├── scripts/
│   ├── backup.py
│   ├── monitor.py
│   ├── log_analyzer.py
│   └── network_check.py
├── config/
│   └── settings.yaml
├── logs/
├── requirements.txt
└── README.md

Automation ที่ 1: จัดการ File และ Directory

งานที่ SysAdmin ทำบ่อยที่สุดคือจัดการไฟล์:

import os
import shutil
from pathlib import Path
from datetime import datetime, timedelta

def cleanup_old_files(directory, days=30):
    # ลบไฟล์ที่เก่ากว่า N วัน
    cutoff = datetime.now() - timedelta(days=days)
    deleted = 0
    for path in Path(directory).rglob("*"):
        if path.is_file():
            mtime = datetime.fromtimestamp(path.stat().st_mtime)
            if mtime < cutoff:
                path.unlink()
                deleted += 1
    return deleted

def organize_by_extension(directory):
    # จัดไฟล์ตาม extension
    for path in Path(directory).iterdir():
        if path.is_file():
            ext = path.suffix.lower() or "no_extension"
            dest = Path(directory) / ext.lstrip(".")
            dest.mkdir(exist_ok=True)
            shutil.move(str(path), str(dest / path.name))

# ใช้งาน
deleted = cleanup_old_files("/var/log/old", days=30)
print(f"Deleted {deleted} old files")

Automation ที่ 2: Monitor Server

ตรวจสอบสถานะ server อัตโนมัติ:

import psutil
import smtplib
from email.mime.text import MIMEText

def check_server():
    alerts = []
    
    # CPU
    cpu = psutil.cpu_percent(interval=5)
    if cpu > 80:
        alerts.append(f"CPU สูง: {cpu}%")
    
    # RAM
    ram = psutil.virtual_memory()
    if ram.percent > 85:
        alerts.append(f"RAM สูง: {ram.percent}%")
    
    # Disk
    disk = psutil.disk_usage("/")
    if disk.percent > 90:
        alerts.append(f"Disk เต็ม: {disk.percent}%")
    
    if alerts:
        send_alert("\n".join(alerts))
    
    return alerts

def send_alert(message):
    msg = MIMEText(message)
    msg["Subject"] = "Server Alert"
    msg["From"] = "admin@example.com"
    msg["To"] = "team@example.com"
    
    with smtplib.SMTP("smtp.gmail.com", 587) as s:
        s.starttls()
        s.login("admin@example.com", "app_password")
        s.send_message(msg)

Automation ที่ 3: Backup อัตโนมัติ

import subprocess
import tarfile
from datetime import datetime

def backup_database(db_name, output_dir="/backup"):
    timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
    filename = f"{output_dir}/{db_name}_{timestamp}.sql.gz"
    
    cmd = f"mysqldump -u root {db_name} | gzip > {filename}"
    result = subprocess.run(cmd, shell=True, capture_output=True)
    
    if result.returncode == 0:
        print(f"Backup OK: {filename}")
        cleanup_old_backups(output_dir, keep=7)
    else:
        print(f"Backup FAILED: {result.stderr}")

def backup_files(source, output_dir="/backup"):
    timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
    filename = f"{output_dir}/files_{timestamp}.tar.gz"
    
    with tarfile.open(filename, "w:gz") as tar:
        tar.add(source, arcname=os.path.basename(source))
    
    print(f"Backup OK: {filename}")

def cleanup_old_backups(directory, keep=7):
    files = sorted(Path(directory).glob("*.gz"), 
                   key=lambda x: x.stat().st_mtime)
    for f in files[:-keep]:
        f.unlink()
        print(f"Deleted old backup: {f.name}")

Automation ที่ 4: จัดการ Log Files

import re
from collections import Counter

def analyze_nginx_log(logfile):
    ip_counter = Counter()
    status_counter = Counter()
    error_urls = []
    
    pattern = r'(\d+\.\d+\.\d+\.\d+).*?"\w+ (.+?) HTTP.*?" (\d+)'
    
    with open(logfile) as f:
        for line in f:
            match = re.search(pattern, line)
            if match:
                ip, url, status = match.groups()
                ip_counter[ip] += 1
                status_counter[status] += 1
                if status.startswith("5"):
                    error_urls.append(url)
    
    print("Top 10 IPs:")
    for ip, count in ip_counter.most_common(10):
        print(f"  {ip}: {count} requests")
    
    print("\nStatus codes:")
    for status, count in status_counter.most_common():
        print(f"  {status}: {count}")
    
    if error_urls:
        print(f"\n5xx errors: {len(error_urls)}")
        for url in set(error_urls)[:10]:
            print(f"  {url}")

Automation ที่ 5: Network Monitoring

import socket
import requests
import time

def check_services(services):
    results = []
    for name, url in services.items():
        try:
            start = time.time()
            resp = requests.get(url, timeout=10)
            elapsed = time.time() - start
            results.append({
                "name": name,
                "status": "UP" if resp.status_code == 200 else "DOWN",
                "code": resp.status_code,
                "time": f"{elapsed:.2f}s"
            })
        except Exception as e:
            results.append({
                "name": name,
                "status": "DOWN",
                "code": 0,
                "time": str(e)[:50]
            })
    return results

services = {
    "Website": "https://siamcafe.net",
    "API": "https://api.example.com/health",
    "Blog": "https://siamcafe.net/blog/",
}

for r in check_services(services):
    print(f"{r['name']}: {r['status']} ({r['code']}) {r['time']}")

Automation ที่ 6: API Integration

เชื่อมต่อกับ API ภายนอก เช่น Slack, LINE, Telegram:

import requests

def send_line_notify(token, message):
    url = "https://notify-api.line.me/api/notify"
    headers = {"Authorization": f"Bearer {token}"}
    data = {"message": message}
    requests.post(url, headers=headers, data=data)

def send_telegram(bot_token, chat_id, message):
    url = f"https://api.telegram.org/bot{bot_token}/sendMessage"
    data = {"chat_id": chat_id, "text": message}
    requests.post(url, json=data)

def send_slack_webhook(webhook_url, message):
    requests.post(webhook_url, json={"text": message})

อ่านเพิ่มเติม: API คืออะไร REST API เบื้องต้น | AI Tools สำหรับคน IT | สร้าง EA ด้วย ChatGPT | Passive Income จาก AI

เครื่องมือและ Library ที่ต้องรู้

Libraryใช้ทำอะไรติดตั้ง
paramikoSSH connectionpip install paramiko
psutilSystem monitoringpip install psutil
requestsHTTP/API callspip install requests
scheduleTask schedulingpip install schedule
pyyamlConfig filespip install pyyaml
jinja2Template/Reportpip install jinja2
fabricRemote executionpip install fabric
ansibleConfiguration mgmtpip install ansible

Best Practices

1. ใช้ Virtual Environment: แยก dependencies ของแต่ละโปรเจกต์ ป้องกัน version conflict

2. ใช้ Config File: อย่า hardcode ค่าต่างๆ ในโค้ด ใช้ YAML หรือ .env file

3. Logging: ใช้ module logging แทน print() เพื่อให้ debug ง่ายขึ้น

4. Error Handling: ใช้ try/except ทุกที่ที่อาจเกิด error โดยเฉพาะ network operations

5. Testing: เขียน unit test ด้วย pytest ก่อน deploy

6. Version Control: ใช้ Git เก็บ script ทุกตัว

สรุป

Python เป็นเครื่องมือที่ทรงพลังสำหรับ IT Automation ตั้งแต่งานง่ายๆ อย่าง file management จนถึงงานซับซ้อนอย่าง server monitoring และ API integration เริ่มต้นจากงานที่ทำซ้ำบ่อยที่สุด เขียน script อัตโนมัติ แล้วค่อยๆ ขยายไปงานอื่น

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

Q: ต้องเรียน Python นานแค่ไหนถึงจะเขียน automation ได้?

A: ถ้ามีพื้นฐาน IT อยู่แล้ว เรียน Python พื้นฐาน 2-4 สัปดาห์ก็เริ่มเขียน automation ง่ายๆ ได้ เช่น file management, backup script สำหรับงานซับซ้อนอาจต้อง 2-3 เดือน

Q: Python กับ Bash เลือกอะไรดี?

A: ถ้าเป็นคำสั่งสั้นๆ 1-5 บรรทัด ใช้ Bash ถ้ายาวกว่านั้นหรือต้องการ error handling ดี ใช้ Python กฎง่ายๆ: ถ้า script ยาวกว่า 20 บรรทัด ให้ใช้ Python

Q: Python 2 กับ Python 3 ใช้ตัวไหน?

A: Python 3 เท่านั้น Python 2 หมด support ตั้งแต่ปี 2020 ถ้ามี script เก่าที่เป็น Python 2 ควร migrate มา Python 3

Q: ต้องติดตั้ง library อะไรบ้าง?

A: เริ่มจาก 4 ตัวหลัก: requests (HTTP), paramiko (SSH), psutil (monitoring), schedule (scheduling) แล้วค่อยเพิ่มตามต้องการ

Q: Python automation ปลอดภัยไหม?

A: ปลอดภัยถ้าเขียนถูกต้อง อย่า hardcode password ในโค้ด ใช้ environment variables หรือ secret manager ตั้ง permission ของ script ให้เหมาะสม