关于批量管理windows,踩了不少坑,后来随着研究不断深入。梳理下来,其实不算复杂。
目的及思路:管理机(Linux)使用Ansible管理windows, 尤其是远程执行bat脚本
环境
管理机Python版本要求:≥3.6
1. 管理机Linux操作
安装Python3,略
ansible必须使用pip来安装,否则会报如下错误
“msg”: “winrm or requests is not installed: No module named winrm”
安装pip命令
| 1 | 从官网下载pip包到本地,官网链接:https://pypi.org/project/pip/#files | 
| 1 | 安装pywinrm | 
| 1 | 创建ansible工作目录 | 
2. Win Server 2016操作
注:以下操作需要PowerShell以管理员身份运行
| 1 | ::确认powershell版本 | 
更改powerShell的策略为remotesigned,否则运行不了powerShell脚本文件
| 1 | get-executionpolicy | 
配置Winrm
| 1 | ::配置并启动winrm | 
3. Ansible管理机-使用示例
| 1 | cd /etc/ansible | 
cat hosts
| 1 | [windows] | 
执行脚本测试
| 1 | ansible -i /etc/ansible/hosts windows -m win_ping | 
远程执行cmd命令或bat脚本
| 1 | ansible -i /etc/ansible/hosts all -m win_shell -a 'D:\scripts\test.bat' | 
4. 其他常用命令
| 1 | 文件批量分发---通过ansible批量(若目标存在同名文件,则自动覆盖)发送到所有主机 | 
5. 错误解决
- 错误1:”msg”: “winrm or requests is not installed: No module named winrm” - 1 
 2
 3- 原因:用yum安装ansible无法调用pip安装的pywinrm插件 
 --#解决方案:卸载yum安装的ansible,使用pip安装ansible
- 错误2:plaintext: the specified credentials were rejected by the server - 1 - 检查windows账号密码是否正确,我这里是因为密码错误导致的 
- 错误3:bat脚本在服务器上直接运行正常,但从ansible运行bat报错:Access is denied(访问拒绝) - 1 
 2
 3
 4- 并非某个命令没有执行权限,而是因为脚本中,存在变量取值异常导致命令执行错误的问题。 
 需要在脚本中打断点(echo变量,逐一确认是否正常)验证。
 有个案例是:时间取值windows执行正常,ansible执行出错而导致此错误。解决方法是重新配置时间变量。
- 本文作者: GaryWu
- 本文链接: https://garywu520.github.io/2020/09/17/Ansible自动化管理win-2016/
- 版权声明: 本博客所有文章除特别声明外,均采用 MIT 许可协议。转载请注明出处!
 
		