wget 命令 #
1. 基本介绍 #
wget 是一个功能强大的命令行工具,用于从网络上下载文件。它支持 HTTP、HTTPS、FTP 等多种协议,具有递归下载、断点续传、后台下载等功能,是开发人员和系统管理员常用的网络工具之一。
2. 基本语法 #
bash
wget [选项] [URL]
3. 常用选项 #
| 选项 | 描述 |
|---|---|
-O, --output-document <file> |
将输出保存到指定文件 |
-P, --directory-prefix <prefix> |
将文件保存到指定目录 |
-c, --continue |
断点续传下载 |
-r, --recursive |
递归下载整个网站 |
-l, --level <depth> |
限制递归深度 |
-np, --no-parent |
不追溯到父目录 |
-nc, --no-clobber |
不覆盖已存在的文件 |
-nd, --no-directories |
不创建目录结构 |
-nH, --no-host-directories |
不创建主机目录 |
-t, --tries <number> |
设置重试次数 |
-T, --timeout <seconds> |
设置超时时间 |
-w, --wait <seconds> |
设置下载间隔时间 |
-i, --input-file <file> |
从文件中读取URL列表 |
-b, --background |
在后台运行 |
-q, --quiet |
静默模式,不显示输出 |
-v, --verbose |
显示详细信息 |
-U, --user-agent <agent> |
设置用户代理字符串 |
-H, --span-hosts |
递归下载时跨越主机 |
-A, --accept <patterns> |
接受指定模式的文件 |
-R, --reject <patterns> |
拒绝指定模式的文件 |
--limit-rate <rate> |
限制下载速度 |
--no-check-certificate |
不检查SSL证书 |
-u, --user <user:password> |
设置认证信息 |
4. 常见用法示例 #
4.1 基本下载 #
bash
# 下载单个文件
wget https://example.com/file.txt
# 将文件保存为指定名称
wget -O newname.txt https://example.com/file.txt
# 将文件保存到指定目录
wget -P downloads/ https://example.com/file.txt
4.2 断点续传 #
bash
# 断点续传下载
wget -c https://example.com/large_file.zip
4.3 批量下载 #
bash
# 从文件中读取URL列表下载
wget -i urls.txt
# 下载多个URL
wget https://example.com/file1.txt https://example.com/file2.txt
4.4 递归下载 #
bash
# 递归下载整个网站,深度为2
wget -r -l 2 https://example.com
# 递归下载但不追溯到父目录
wget -r -np https://example.com/docs/
# 递归下载时不创建目录结构
wget -r -nd https://example.com/files/
# 递归下载时不创建主机目录
wget -r -nH https://example.com/
4.5 过滤下载 #
bash
# 只下载.jpg和.png文件
wget -r -A jpg,png https://example.com/images/
# 下载时排除.gif文件
wget -r -R gif https://example.com/images/
4.6 后台下载 #
bash
# 在后台运行下载
wget -b https://example.com/large_file.zip
# 查看后台下载进度
cat wget-log
4.7 限速下载 #
bash
# 限制下载速度为100KB/s
wget --limit-rate=100k https://example.com/large_file.zip
4.8 其他常用功能 #
bash
# 静默模式下载
wget -q https://example.com/file.txt
# 显示详细下载信息
wget -v https://example.com/file.txt
# 设置用户代理
wget -U "Mozilla/5.0" https://example.com
# 跳过SSL证书检查
wget --no-check-certificate https://example.com
# 设置下载重试次数为5次
wget -t 5 https://example.com/file.txt
# 设置超时时间为30秒
wget -T 30 https://example.com/file.txt
5. 高级用法 #
5.1 镜像网站 #
bash
# 镜像整个网站
wget --mirror -p --convert-links -P ./mirror https://example.com
参数说明:
--mirror: 等同于-r -N -l inf -np,创建网站镜像-p: 下载显示页面所需的所有文件(图片、CSS等)--convert-links: 将链接转换为本地链接-P ./mirror: 将文件保存到mirror目录
5.2 带认证的下载 #
bash
# 基本认证下载
wget --user=username --password=password https://example.com/secure/file.txt
# 从.netrc文件读取认证信息
wget -nH --user-agent=Mozilla/5.0 --netrc-file=~/.netrc https://example.com/
5.3 自定义HTTP头部 #
bash
# 设置自定义HTTP头部
wget --header="Accept-Language: zh-CN" --header="Referer: https://example.com" https://example.com/file.txt
6. 总结 #
wget 是一个功能强大且灵活的命令行下载工具,支持多种协议和丰富的选项。通过掌握其常用功能,如基本下载、断点续传、递归下载、批量下载等,可以大大提高网络文件下载的效率。无论是单个文件下载还是整个网站镜像,wget 都是一个可靠的选择。
最后更新:2026-02-07