【运维心得】playbook远程清理windows亲测步骤
目录
安装 Ansible 和 WinRM 支持
配置 Windows 终端的 WinRM 服务
创建 Ansible 清单文件
测试 Ansible 连接
编写删除临时文件的 Playbook
执行 Playbook 删除文件
验证临时文件是否删除
高级配置(可选)
SecureCRT的坑
常见问题排查
由于最近清理离职电脑较多,一个一个的清理比较费力,所以就想到了运维自动化工具ansible,本文就以清理windows临时文件为例,详细说明如何安装并使用playbook远程操控windows终端。
安装 Ansible 和 WinRM 支持
在 Ubuntu 系统上安装 Ansible 和配置 WinRM 支持是远程控制 Windows 终端的第一步。确保系统已更新至最新版本,使用以下命令安装 Ansible:
sudo apt update
sudo apt install software-properties-common
sudo add-apt-repository ppa:ansible/ansible
sudo apt install ansible -y
安装完成后,验证 Ansible 版本:
ansible --version
我安装的是:ansible [core 2.18.9]
为支持 Windows 远程管理,需安装 pywinrm
库,这里有个坑被我碰到了,一开始始终无法安装成功pywinrm,后来经常查证,发现要首先安装python3-pip才可以!这个坑可能是我安装ubuntu的时候采用了最小化安装(因为是虚拟机安装)引起的:
sudo apt install python3 python3-pip
pip install pywinrm
配置 Windows 终端的 WinRM 服务
在 Windows 终端上启用 WinRM 服务是必要的。以管理员身份打开 PowerShell,执行以下命令快速配置 WinRM:
winrm quickconfig -q //全部yes即可winrm set winrm/config/service '@{AllowUnencrypted="true"}'
winrm set winrm/config/service/auth '@{Basic="true"}'
允许防火墙通过 WinRM 通信,这里也碰到一个坑,就是安装了某卫士,结果后面测试的时候,每次都被阻断,即使添加了信任也没用,所以比较好的选择是:关闭卫士1小时就可以了!:
netsh advfirewall firewall add rule name="WinRM-HTTP" dir=in localport=5985 protocol=TCP action=allow
可以使用下面的命令查看被控机winrm的参数:
winrm get winrm/config
正常情况下,列出的参数应该与刚才设置的参数一致,否则就要查是否执行过程中有权限报错。
创建 Ansible 清单文件
在 Ubuntu 上创建 Ansible 清单文件(/etc/ansible/hosts
),定义 Windows 主机信息。以下示例配置了单个 Windows 主机:
[windows]
192.168.1.100[windows:vars]
ansible_user=Administrator
ansible_password=your_password
ansible_connection=winrm
ansible_winrm_transport=basic
ansible_winrm_server_cert_validation=ignore
上面的参数除了IP地址、用户名、密码需要修改,其他的都不要修改,否则可能会执行不成功,尤其是拼写错误!
测试 Ansible 连接
使用 ansible
命令测试与 Windows 主机的连接:
ansible windows -m win_ping
若返回 pong
,表示连接成功。
编写删除临时文件的 Playbook
创建一个名为 delete_temp_files.yml
的 Playbook,内容如下:
- name: Clean Windows temporary fileshosts: windowsgather_facts: yesvars:temp_paths:- "{{ ansible_env.TEMP }}"- "C:\\Temp"- "{{ ansible_env.USERPROFILE }}"- "{{ ansible_env.USERPROFILE }}\\AppData\\Local\\Temp"retention_days: 7tasks:- name: Check temporary directories existwin_stat:path: "{{ item }}"loop: "{{ temp_paths }}"register: temp_dirsignore_errors: yes- name: Find old temporary fileswin_find:paths: "{{ item.item }}"age: "{{ retention_days }}d"file_type: filerecurse: yespatterns: ['*.tmp', '*.log', '*.cache', '*.bak']loop: "{{ temp_dirs.results | selectattr('stat.exists', 'defined') }}"register: found_files- name: Delete old temporary fileswin_file:path: "{{ item.path }}"state: absentloop: "{{ found_files.results | selectattr('files', 'defined') | map(attribute='files') | flatten }}"when: found_files.results | length > 0- name: Show cleanup summarydebug:msg: "Cleaned {{ found_files.results | map(attribute='files') | map('length') | sum }} files from {{ temp_paths | join(',') }}"when: found_files.results | length > 0
这里也有坑:yml的格式非常严格,比如冒号后面必须要有空格,否则执行就不成功!包括删除文件的方式,也有好几种,我采取的是最保险的一种。
执行 Playbook 删除文件
运行 Playbook 以删除临时文件和清空回收站:
ansible-playbook delete_temp_files.yml
//或者加个参数查看详细执行过程
ansible-playbook delete_temp_files.yml -vvv
验证临时文件是否删除
通过以下命令检查 Windows 终端上的临时文件是否已删除:
ansible windows -m win_shell -a "dir $env:TEMP"
若返回结果为空或仅显示少量系统文件,表示操作成功。
高级配置(可选)
为提高安全性,建议使用 HTTPS 和证书认证替代基础认证。在 Windows 终端上生成自签名证书并重新配置 WinRM:
$cert = New-SelfSignedCertificate -DnsName $env:COMPUTERNAME -CertStoreLocation Cert:\LocalMachine\My
winrm create winrm/config/Listener?Address=*+Transport=HTTPS "@{Hostname=`"$env:COMPUTERNAME`"; CertificateThumbprint=`"$($cert.Thumbprint)`"}"
更新 Ansible 清单文件以使用 HTTPS:
ansible_connection=winrm
ansible_winrm_transport=ntlm
ansible_winrm_port=5986
ansible_winrm_scheme=https
SecureCRT的坑
另外在过程中,本人还碰到了SecureCRT连接新安装的ubuntu24.04时提示No compatible hostkey!
经常查证,需要加入下面的协议才可以,猜测可能也是在安装ubuntu的时候,选择了最小化安装导致的问题:
vim /etc/ssh/sshd_config
//在 /etc/ssh/sshd_config 文件中追加以下两行文本
HostKeyAlgorithms ssh-dss,ssh-ed25519,ssh-rsa,rsa-sha2-256,rsa-sha2-512
KexAlgorithms curve25519-sha256@libssh.org,ecdh-sha2-nistp256,ecdh-sha2-nistp384,ecdh-sha2-nistp521,diffie-hellman-group-exchange-sha256,diffie-hellman-group14-sha1,diffie-hellman-group-exchange-sha1,diffie-hellman-group1-sha1
常见问题排查
若连接失败,检查以下方面:
- Windows 防火墙是否允许 WinRM 端口(5985/5986)通信。
- 用户名和密码是否正确。
- WinRM 服务是否正在运行(
Get-Service WinRM
)。 - Ubuntu 和 Windows 网络是否互通。
通过以上步骤,可以高效地使用 Ansible 和 WinRM 远程管理 Windows 终端并清理临时文件。