如何在 Windows 系统中自动化下载文件、验证校验和并保存到指定位置
以下是一个完整的指南,介绍如何使用 Ansible 的 win_get_url 模块在 Windows 系统中下载文件、验证校验和并保存到指定位置。
使用 Ansible 模块 win_get_url 下载文件
关于 win_get_url 模块
win_get_url 是 Ansible 的一个模块,全名为 ansible.windows.win_get_url,属于 Ansible 的 Windows 模块集合。它用于从 HTTP、HTTPS 或 FTP 下载文件到目标节点。对于 Linux 系统,应使用 ansible.builtin.get_url 模块。
主要参数
url(字符串,必需):指定要下载的文件的 URL。dest(字符串,必需):指定文件保存的目标路径。force(布尔值,默认为no):如果目标路径是文件,Ansible 每次都会下载文件。如果目标路径是目录,Ansible 默认不会替换已存在的文件,除非将force设置为yes。checksum_algorithm(字符串,默认为sha1):指定校验和算法。checksum(字符串):指定文件的校验和值。checksum_url(字符串):指定校验和文件的 URL。headers(字典):指定自定义 HTTP 头。http_agent(字符串,默认为ansible-httpget):指定 HTTP 请求的 User-Agent 字符串。proxy_url、proxy_username、proxy_password、proxy_use_default_credential:指定代理设置。
示例代码
以下是一个 Ansible Playbook,用于在 Windows 系统中下载文件并验证校验和。
文件名:win_get_url.yml
---
- name: win_get_url 模块示例
hosts: all
become: false
vars:
myurl: "https://example.com/path/to/file.zip" # 文件的 URL
mycrc: "https://example.com/path/to/file.zip.sha256" # 校验和文件的 URL
mycrc_algorithm: "sha256" # 校验和算法
mydest: 'C:\Users\vagrant\Desktop\file.zip' # 目标路径
tasks:
- name: 下载文件
ansible.windows.win_get_url:
url: "{{ myurl }}"
dest: "{{ mydest }}"
checksum_algorithm: "{{ mycrc_algorithm }}"
checksum_url: "{{ mycrc }}"
执行命令
$ ansible-playbook -i win/inventory download\ file/win_get_url.yml
执行结果
PLAY [win_get_url 模块示例] *******************************************************
TASK [Gathering Facts] ******************************************************
ok: [WindowsServer]
TASK [下载文件] ******************************************************
changed: [WindowsServer]
PLAY RECAP *******************************************************************
WindowsServer : ok=2 changed=1 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
验证文件是否下载成功
在 Windows 主机上检查文件是否已下载到指定路径:
$ ssh vagrant@WindowsServer
C:\Users\vagrant\Desktop>dir
Volume in drive C is Windows
Volume Serial Number is 1234-ABCD
Directory of C:\Users\vagrant\Desktop
01/01/2024 12:00 PM 1,024 file.zip
1 File(s) 1,024 bytes
0 Dir(s) 123,456,789,012 bytes free
通过以上步骤,您可以使用 Ansible 的 win_get_url 模块轻松在 Windows 系统中下载文件、验证校验和并保存到指定位置。