Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> สมาร์ทโฟน >> Linux

วิธีดาวน์โหลดไฟล์จาก Command Line ด้วย wget

คู่มือครบครันสำหรับ wget - Command Line Downloader ที่ทรงพลัง รองรับ Resume, Recursive, Mirror, Authentication, Bandwidth Control

ติดตั้ง wget


# Ubuntu/Debian
sudo apt install wget

# CentOS/RHEL/Fedora
sudo dnf install wget

# macOS
brew install wget

# Windows: Chocolatey/Scoop หรือ Binary จาก GNUWin32

คำสั่งพื้นฐาน


# ดาวน์โหลดไฟล์เดี่ยว
wget https://example.com/file.zip

# ระบุชื่อไฟล์เอาต์พุต
wget -O myfile.zip https://example.com/file.zip

# ดาวน์โหลดหลายไฟล์
wget -i urls.txt  # urls.txt มี URL ทีละบรรทัด

Resume Download (ต่อจากที่หยุด)


wget -c https://example.com/large-file.iso
# -c = continue (Resume)

Bandwidth Control


# จำกัดความเร็ว 1MB/s
wget --limit-rate=1m https://example.com/file.zip

# จำกัด 500KB/s
wget --limit-rate=500k https://example.com/file.zip

Recursive Download (Mirror Website)


# ดาวน์โหลดเว็บไซต์ (Depth 1)
wget -r -l 1 https://example.com/

# Mirror ทั้งไซต์ (สำหรับ Backup)
wget --mirror -p --convert-links -P ./backup https://example.com/

# เฉพาะไฟล์ .jpg
wget -r -l 1 -A.jpg https://example.com/

# ไม่ขึ้นไป Parent Directory
wget -r --no-parent https://example.com/dir/

Authentication


# Basic Auth
wget --user=username --password=pass https://example.com/protected/file

# หรือใน URL
wget https://user:pass@example.com/file

# Cookie (สำหรับ Site ต้อง Login)
wget --load-cookies cookies.txt https://example.com/

ตัวเลือกสำคัญอื่นๆ

อัตโนมัติ Backup Website ด้วย Cron


#!/bin/bash
# /usr/local/bin/website-backup.sh

DATE=$(date +"%Y-%m-%d")
BACKUP_DIR="/backup/website/$DATE"
mkdir -p "$BACKUP_DIR"
cd "$BACKUP_DIR"

wget --mirror -p --convert-links --wait=1 --random-wait \
     --user-agent="Mozilla/5.0 Backup Bot" \
     https://example.com/

# ลบ Backup เก่า > 30 วัน
find /backup/website -type d -mtime +30 -exec rm -rf {} \;

# Crontab (ทุกวัน 02:00)
0 2 * * * /usr/local/bin/website-backup.sh

ทางเลือกทันสมัย: curl / aria2

  • curl - มาตรฐาน, รองรับ Protocol มากกว่า, Library (libcurl)
  • aria2 - Multi-connection, Metalink, BitTorrent, RPC Interface

wget เป็นเครื่องมือ Download ที่น่าเชื่อถือ สคริปต์ได้ง่าย เหมาะสำหรับ Automation และ Server

Optionคำอธิบาย
-qQuiet (ไม่แสดง Progress)
-nvNon-verbose (แสดงแค่ Error)
-vVerbose (Debug)
--timeout=30Timeout วินาที
--tries=3Retry ครั้ง
--wait=1Wait ระหว่าง Request (Polite)
--random-waitWait Random 0.5-1.5x
--user-agent="..."Custom User Agent
--no-check-certificateSkip SSL Verify (ไม่แนะนำ)