参考文档: http://blog.51cto.com/dyc2005/2064746

1. 环境说明:

  • windows server 2008+

  • centos7.3

2. 环境安装

2.1 centos环境

  1. #安装ansible
  2. yum install -y ansible
  3. # 安装pip
  4. wget https://bootstrap.pypa.io/get-pip.py
  5. python get-pip.py
  6. # 安装依赖
  7. pip install pywinrm paramiko PyYAML Jinja2 httplib2 six

2.2 windows 环境

PowerShell

  1. Set-ExecutionPolicy RemoteSigned # y 同意
  2. Get-ExecutionPolicy # RemoteSigned
  3. Get-Host # 查看powershell信息, 确保version是3.0以上

cmd

  1. winrm quickconfig # WinRM 服务. y 确认
  2. winrm e winrm/config/listener
  3. winrm set winrm/config/service/auth @{Basic="true"} # 配置auth 为true(默认为false)
  4. winrm set winrm/config/service @{AllowUnencrypted="true"} # 配置允许非加密方式

至此, 远程windows已配置完成.

下面,我们来通过 ansible 访问一下 windows

  1. [root@localhost ~]# vim /etc/ansible/hosts
  2. [winserver]
  3. 192.168.3.223 ansible_ssh_user="Administrator" ansible_ssh_pass="Fuljoy.com" ansible_ssh_port=5985 ansible_connection="winrm" ansible_winrm_server_cert_validation=ignore
  4. [root@localhost ~]# ansible winserver -m win_ping
  5. 192.168.3.223 | SUCCESS => {
  6. "changed": false,
  7. "ping": "pong"
  8. }

ansible 管理 windows

  1. # 1.查看连接状态
  2. ansible winserver -m win_ping
  3. # 2.获取Windows Facts
  4. ansible winserver -m setup
  5. # 3.远程执行命令
  6. ## 为了避免执行结束乱码,先执行如下命令。
  7. cp /usr/lib/python2.7/site-packages/winrm/protocol.py{,-}
  8. sed -i "s#tdout_buffer.append(stdout)#tdout_buffer.append(stdout.decode('gbk').encode('utf-8'))#g" /usr/lib/python2.7/site-packages/winrm/protocol.py
  9. sed -i "s#stderr_buffer.append(stderr)#stderr_buffer.append(stderr.decode('gbk').encode('utf-8'))#g" /usr/lib/python2.7/site-packages/winrm/protocol.py
  10. ## 3.1 获取ip 地址
  11. ansible winserver -m raw -a "ipconfig"
  12. ## 3.2 win_command模块远程获取身份
  13. ansible win7 -m win_command -a "whoami"
  14. ## 3.3 将windows主机上, C:\f1.txt 移到到 D:\
  15. ansible win7 -m raw -a "cmd /c 'move /y c:\f1.txt d:\'"
  16. ## 3.4 在windows主机上,创建目录
  17. ansible win7 -m raw -a "mkdir d:\\tmp"
  18. ## 3.5 将 /root/svn-test 目录 传送到 windows中的 d:/tmp 目录下
  19. ansible win7 -m win_copy -a "src=/root/svn-test dest=D:/tmp/"
  20. # 将远程目录的备份
  21. ansible win7 -m win_copy -a "src=d:/tmp/WindowsServices dest=d:/backup/ remote_src=yes "
  22. ## 3.6 删除windows中的 d:/tmp/svn-test
  23. ansible win7 -m win_file -a "path=d:/tmp/svn-test state=absent"
  24. ## 3.7 启动/停止 windows中的服务
  25. ansible win7 -m win_shell -a "net start jenkins"
  26. ansible win7 -m win_shell -a "net stop jenkins"
  27. ## 3.8 结束某程序
  28. ansible win7 -m raw -a "taskkill /F /IM QQ.exe /T"
  29. ## 3.9 重启windows服务器
  30. ansible win7 -m win_reboot
  31. ansible win7 -m win_shell -a 'shutdown -r -t 0'