批量管理Windows机器
实现如下功能: 0. 在目标机器上打开winrm
- 推送文件到目标机器
- 从git上更新代码部署到目标机器
- 在目标机器上运行特定程序
- 杀掉目标机器上的进程
开启winrm
- 启用 WinRM 远程服务
winrm quickconfig
- 查看 WinRM 服务监听状态:
C:\Windows\system32>winrm e winrm/config/listener
Listener [Source="GPO"]
Address = *
Transport = HTTP
Port = 5985
Hostname
Enabled = true
URLPrefix = wsman
CertificateThumbprint
ListeningOn = 127.0.0.1, 169.254.52.7, xx.xx.xx.xx, ::1, fe80::3989:dd91:e6b3:6f41%15, fe80::fd01:a9fd:c410:3407%12
- 允许使用 Basic 认证方式:
winrm set winrm/config/service/auth ‘@{Basic="true"}’
Auth
Basic = true [Source="GPO"]
Kerberos = true
Negotiate = true
Certificate = false
CredSSP = false
CbtHardeningLevel = Relaxed
- 允许 WinRM 使用非加密的连接
winrm set winrm/config/service '@{AllowUnencrypted="true"}'
定义hosts
hosts文件中定义了所需管理的主机的信息及变量。
# hosts
[windows]
192.168.0.105
192.168.0.106
[windows:vars]
ansible_connection=winrm
ansible_user=administrator
ansible_password=XXXXXXXXXX
ansible_winrm_server_cert_validation=ignore
sgcc_workspace=C:\Users\Administrator\goods_screen
sgcc_pstools=C:\Users\Administrator\goods_screen\pstools
git_project_url=http://office.pingansec.com:30080/huililong/e_goods_screen
git_token=vFzejvzVoo-zxYJ1AXxb
注意:ansible_connection=winrm 指定使用winrm连接windows机器,默认使用SSH。
安装pstools
执行程序,及kill程序是通过psexec及pskill实现。所以需要在所有机器上安装这两个工具。此过程只需做一次
# install_psexec.yml
- hosts: windows
tasks:
- name: Copy pskill
win_copy:
src: pstools/pskill.exe
dest: '{{sgcc_pstools}}\'
- name: Copy psexec
win_copy:
src: pstools/psexec.exe
dest: '{{sgcc_pstools}}\'
执行命令:
ansible-playbook -i hosts install_psexec.yml
更新代码
# sgcc_deploy_source.yml
- hosts: windows
tasks:
- name: Download source from git
win_get_url:
url: '{{git_project_url}}/repository/archive.zip?ref={{commit}}&private_token={{git_token}}'
dest: '{{sgcc_workspace}}\archive.zip'
- name: Unzip archive.zip
win_unzip:
src: '{{sgcc_workspace}}\archive.zip'
dest: '{{sgcc_workspace}}'
- name: Remove Old version
win_file:
path: '{{sgcc_workspace}}\e_goods_screen\'
state: absent
- name: Rename
win_copy:
src: '{{sgcc_workspace}}\e_goods_screen-{{commit}}-{{commit}}\'
dest: '{{sgcc_workspace}}\e_goods_screen\'
remote_src: yes
backup: yes
- name: Remove temp
win_file:
path: '{{sgcc_workspace}}\e_goods_screen-{{commit}}-{{commit}}\'
state: absent
git_token要从gitlab账号中获取。用于免登录下载项目代码 根据指定的提交号更新代码
ansible-playbook -i hosts sgcc_deploy_source.yml --extra-vars "commit=c7466a437afb6aaa3826729770167ea9a7de5659"
运行程序
使用psexec在目标机器上执行相应代码 以下为执行 test.py 这个脚本的配置。实际使用请根据具体要运行的python脚本修改command
session:2 指的是远程桌面的会话,在目标机器上使用query session查看
注意:通过winrm远程使用psexec时,尽管winrm建立连接时已经登录认证过了,依旧需要指定username与password
# sgcc_run_job.yml
- hosts: windows
tasks:
- name: 运行测试例子程序
win_psexec:
executable: '{{sgcc_pstools}}\psexec.exe'
command: 'python {{sgcc_workspace}}\test.py'
session: 2
interactive: yes
wait: no
username: administrator
password: XXXXXXXX
ansible-playbook -i hosts sgcc_run_job.yml
杀进程
以下例子为杀掉 python 进程
- hosts: windows
tasks:
- name:
win_command: '{{sgcc_pstools}}\pskill.exe python'