参考文档: http://blog.51cto.com/dyc2005/2064746
1. 环境说明:
windows server 2008+
centos7.3
2. 环境安装
2.1 centos环境
#安装ansible
yum install -y ansible
# 安装pip
wget https://bootstrap.pypa.io/get-pip.py
python get-pip.py
# 安装依赖
pip install pywinrm paramiko PyYAML Jinja2 httplib2 six
2.2 windows 环境
PowerShell
Set-ExecutionPolicy RemoteSigned # y 同意
Get-ExecutionPolicy # RemoteSigned
Get-Host # 查看powershell信息, 确保version是3.0以上
cmd
winrm quickconfig # WinRM 服务. y 确认
winrm e winrm/config/listener
winrm set winrm/config/service/auth @{Basic="true"} # 配置auth 为true(默认为false)
winrm set winrm/config/service @{AllowUnencrypted="true"} # 配置允许非加密方式
至此, 远程windows已配置完成.
下面,我们来通过 ansible 访问一下 windows
[root@localhost ~]# vim /etc/ansible/hosts
[winserver]
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
[root@localhost ~]# ansible winserver -m win_ping
192.168.3.223 | SUCCESS => {
"changed": false,
"ping": "pong"
}
ansible 管理 windows
# 1.查看连接状态
ansible winserver -m win_ping
# 2.获取Windows Facts
ansible winserver -m setup
# 3.远程执行命令
## 为了避免执行结束乱码,先执行如下命令。
cp /usr/lib/python2.7/site-packages/winrm/protocol.py{,-}
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
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
## 3.1 获取ip 地址
ansible winserver -m raw -a "ipconfig"
## 3.2 win_command模块远程获取身份
ansible win7 -m win_command -a "whoami"
## 3.3 将windows主机上, C:\f1.txt 移到到 D:\
ansible win7 -m raw -a "cmd /c 'move /y c:\f1.txt d:\'"
## 3.4 在windows主机上,创建目录
ansible win7 -m raw -a "mkdir d:\\tmp"
## 3.5 将 /root/svn-test 目录 传送到 windows中的 d:/tmp 目录下
ansible win7 -m win_copy -a "src=/root/svn-test dest=D:/tmp/"
# 将远程目录的备份
ansible win7 -m win_copy -a "src=d:/tmp/WindowsServices dest=d:/backup/ remote_src=yes "
## 3.6 删除windows中的 d:/tmp/svn-test
ansible win7 -m win_file -a "path=d:/tmp/svn-test state=absent"
## 3.7 启动/停止 windows中的服务
ansible win7 -m win_shell -a "net start jenkins"
ansible win7 -m win_shell -a "net stop jenkins"
## 3.8 结束某程序
ansible win7 -m raw -a "taskkill /F /IM QQ.exe /T"
## 3.9 重启windows服务器
ansible win7 -m win_reboot
ansible win7 -m win_shell -a 'shutdown -r -t 0'