溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

ansible自動(dòng)化管理windows系統(tǒng)實(shí)戰(zhàn)

發(fā)布時(shí)間:2020-05-20 00:43:40 來源:網(wǎng)絡(luò) 閱讀:110566 作者:dyc2005 欄目:系統(tǒng)運(yùn)維

一、簡述

1、說明
日常系統(tǒng)自動(dòng)化運(yùn)維過程中難免會(huì)有windows系列服務(wù)器,就開源軟件來說目前大多的對(duì)windows批量管理兼容性不太好;不像Linux系統(tǒng)便捷,但現(xiàn)實(shí)中確實(shí)有些業(yè)務(wù)需要跑在windows上;搜索查找折騰一番后,發(fā)現(xiàn)python開發(fā)的ansible(已經(jīng)被redhat收購)有比較好的解決方案,通過一番折騰,整理出來,以備忘交流;

2、實(shí)驗(yàn)環(huán)境
服務(wù)器端:
CentOS7.4_x64 自帶python 2.7.5 ip:172.16.3.167
源碼安裝ansible

被管理windows端:
win7sp1_x32 需要powershell 3.0+ ip:172.16.3.188 并開啟winrm服務(wù) 開啟防火墻規(guī)則

3、實(shí)驗(yàn)?zāi)繕?biāo)
能通過ansible 的各模塊對(duì)windows進(jìn)行傳輸文件,管理賬號(hào),執(zhí)行腳本等批量自動(dòng)化管理工作;

二、ansible配置

1、簡介
Ansible 從1.7+版本開始支持Windows,但管理機(jī)必須為Linux系統(tǒng),遠(yuǎn)程主機(jī)的通信方式也由Linux下的SSH變?yōu)镻owerShell,管理機(jī)需要安裝Python的pywinrm模塊,但PowerShell需3.0+版本且Management Framework 3.0+版本,實(shí)測Windows 7 SP1和Windows Server 2008 R2及以上版本系統(tǒng)經(jīng)簡單配置可正常與Ansible通信。
2、環(huán)境準(zhǔn)備
以下配置在CentOS7.4_x64下
安裝pip及相關(guān)依賴

下載pip
#wget https://bootstrap.pypa.io/get-pip.py
#python get-pip.py
安裝依賴
#pip install pywinrm paramiko PyYAML Jinja2 httplib2 six

3、源碼安裝ansible

# git clone git://github.com/ansible/ansible.git --recursive
#cd ./ansible
#source ./hacking/env-setup

運(yùn)行了env-setup腳本,就意味著Ansible基于源碼運(yùn)行起來了.默認(rèn)的inventory文件是 /etc/ansible/hosts
cat /etc/ansible/hosts
注:可以把這步添加到開機(jī)自啟中;

[win7]
172.16.3.188 ansible_ssh_user="virtual" ansible_ssh_pass="myself." ansible_ssh_port=5985 ansible_connection="winrm" ansible_winrm_server_cert_validation=ignore

注意上信息在一行;以空格隔開,[win7] 是這臺(tái)主機(jī)的標(biāo)題;下面的是ip和連接信息等;
以上ansible管理端已經(jīng)配置好,被管理端win7還沒有配置,相對(duì)來說稍稍麻煩點(diǎn)

三、被管理端win7配置

1、環(huán)境簡介
和Linux稍有區(qū)別,被管理端系統(tǒng)如果是Windows系列時(shí);需預(yù)先有以下配置:
安裝Framework 3.0+ (有可能需要下載)
配置powershell策略為remotesigned (需要修改)
升級(jí)PowerShell至3.0+(win7默認(rèn)是2.0)
設(shè)置Windows遠(yuǎn)端管理,英文全稱WS-Management(WinRM)

2、環(huán)境配置
a、升級(jí)或安裝Framework 4.5
如果Framework版不滿足請至微軟官方下載
b、修改powershell策略為remotesigned
如圖:
ansible自動(dòng)化管理windows系統(tǒng)實(shí)戰(zhàn)

c、升級(jí)PowerShell至3.0
保存以下腳本為upgrade_to_ps3.ps1

# Powershell script to upgrade a PowerShell 2.0 system to PowerShell 3.0 
# based on http://occasionalutility.blogspot.com/2013/11/everyday-powershell-part-7-powershell.html 
# some Ansible modules that may use Powershell 3 features, so systems may need 
# to be upgraded.  This may be used by a sample playbook.  Refer to the windows 
# documentation on docs.ansible.com for details. 
# - hosts: windows 
#   tasks: 
#     - script: upgrade_to_ps3.ps1 

# Get version of OS 

# 6.0 is 2008 
# 6.1 is 2008 R2 
# 6.2 is 2012 
# 6.3 is 2012 R2 

 if ($PSVersionTable.psversion.Major -ge 3) 
 { 
     write-host "Powershell 3 Installed already; You don't need this" 
    Exit 
} 

 $powershellpath = "C:\powershell" 

function download-file 
 { 
     param ([string]$path, [string]$local) 
     $client = new-object system.net.WebClient 
    $client.Headers.Add("user-agent", "PowerShell") 
    $client.downloadfile($path, $local) 
 } 

 if (!(test-path $powershellpath)) 
{ 
    New-Item -ItemType directory -Path $powershellpath 
} 

# .NET Framework 4.0 is necessary. 

 #if (($PSVersionTable.CLRVersion.Major) -lt 2) 
 #{ 
#    $DownloadUrl = "http://download.microsoft.com/download/B/A/4/BA4A7E71-2906-4B2D-A0E1-80CF16844F5F/dotNetFx45_Full_x86_x64.exe" 
#    $FileName = $DownLoadUrl.Split('/')[-1] 
#    download-file $downloadurl "$powershellpath\$filename" 
#    ."$powershellpath\$filename" /quiet /norestart 
#} 

 #You may need to reboot after the .NET install if so just run the script again. 

 # If the Operating System is above 6.2, then you already have PowerShell Version > 3 
 if ([Environment]::OSVersion.Version.Major -gt 6) 
 { 
     write-host "OS is new; upgrade not needed." 
    Exit 
} 

 $osminor = [environment]::OSVersion.Version.Minor 

$architecture = $ENV:PROCESSOR_ARCHITECTURE 

 if ($architecture -eq "AMD64") 
 { 
     $architecture = "x64" 
 }   
 else 
 { 
     $architecture = "x86"  
}  

if ($osminor -eq 1) 
 { 
     $DownloadUrl = "http://download.microsoft.com/download/E/7/6/E76850B8-DA6E-4FF5-8CCE-A24FC513FD16/Windows6.1-KB2506143-" + $architecture + ".msu" 
} 
elseif ($osminor -eq 0) 
 { 
     $DownloadUrl = "http://download.microsoft.com/download/E/7/6/E76850B8-DA6E-4FF5-8CCE-A24FC513FD16/Windows6.0-KB2506146-" + $architecture + ".msu" 
} 
 else 
 { 
    # Nothing to do; In theory this point will never be reached. 
     Exit 
} 

$FileName = $DownLoadUrl.Split('/')[-1] 
download-file $downloadurl "$powershellpath\$filename" 

Start-Process -FilePath "$powershellpath\$filename" -ArgumentList /quiet 

腳本來源于github upgrade_to_ps3.ps1

右擊-->以管理員運(yùn)行 稍等幾分鐘(具體時(shí)間看下載的速度,只要任務(wù)管理器中有powershell就說明還在下載安裝),系統(tǒng)會(huì)自動(dòng)重啟升級(jí)安裝powershell到3.0
如圖:
ansible自動(dòng)化管理windows系統(tǒng)實(shí)戰(zhàn)
重啟后查看powershell信息
ansible自動(dòng)化管理windows系統(tǒng)實(shí)戰(zhàn)

d、設(shè)置Windows遠(yuǎn)端管理(WS-Management,WinRM)服務(wù)
winrm 服務(wù)默認(rèn)都是未啟用的狀態(tài);注意以下操作在cmd中執(zhí)行,而非powershell中
對(duì)winrm服務(wù)進(jìn)行基礎(chǔ)配置:

winrm quickconfig
C:\Users\san02>winrm quickconfig
已在此計(jì)算機(jī)上運(yùn)行 WinRM 服務(wù)。
WinRM 沒有設(shè)置成為了管理此計(jì)算機(jī)而允許對(duì)其進(jìn)行遠(yuǎn)程訪問。
必須進(jìn)行以下更改:
在 HTTP://* 上創(chuàng)建 WinRM 偵聽程序接受 WS-Man 對(duì)此機(jī)器上任意 IP 的請求。
啟用 WinRM 防火墻異常。
執(zhí)行這些更改嗎[y/n]? y
WinRM 已經(jīng)進(jìn)行了更新,以用于遠(yuǎn)程管理。
在 HTTP://* 上創(chuàng)建 WinRM 偵聽程序接受 WS-Man 對(duì)此機(jī)器上任意 IP 的請求。
WinRM 防火墻異常已啟用。

查看winrm service listener
winrm e winrm/config/listener
C:\Users\san02>winrm e winrm/config/listener
Listener
    Address = *
    Transport = HTTP
    Port = 5985
    Hostname
    Enabled = true
    URLPrefix = wsman
    CertificateThumbprint
    ListeningOn = 127.0.0.1, 172.16.3.137, ::1, fe80::100:7f:fffe%13, fe80::5efe
:172.16.3.137%12, fe80::4865:97de:bb1f:877%11

配置auth 為true(默認(rèn)為false)
winrm set winrm/config/service/auth @{Basic="true"}C:\Users\san02>winrm set winrm/config/service/auth @{Basic="true"}
Auth
    Basic = true
    Kerberos = true
    Negotiate = true
    Certificate = false
    CredSSP = false
    CbtHardeningLevel = Relaxed

配置允許非加密方式
winrm set winrm/config/service @{AllowUnencrypted="true"}
C:\Users\san02>winrm set winrm/config/service @{AllowUnencrypted="true"}
Service
    RootSDDL = O:NSG:BAD:P(A;;GA;;;BA)(A;;GR;;;IU)S:P(AU;FA;GA;;;WD)(AU;SA;GXGW;
;;WD)
    MaxConcurrentOperations = 4294967295
    MaxConcurrentOperationsPerUser = 1500
    EnumerationTimeoutms = 240000
    MaxConnections = 300
    MaxPacketRetrievalTimeSeconds = 120
    AllowUnencrypted = true
    Auth
        Basic = true
        ......以下省略.......

至此被管理端win7的環(huán)境配置完成!

四、測試Ansible管理windows

1、查看連接狀態(tài)

[root@localhost ~]# ansible win7 -m win_ping
172.16.3.188 | SUCCESS => {
    "attempts": 1, 
    "changed": false, 
    "failed": false, 
    "ping": "pong"
}

2、獲取Windows Facts

[root@localhost ~]# ansible win7 -m   setup
172.16.3.188 | SUCCESS => {
    "ansible_facts": {
        "ansible_architecture": "32-bit", 
        "ansible_bios_date": "12/01/2006", 
        "ansible_bios_version": "VirtualBox", 
        "ansible_date_time": {
            "date": "2018-01-24", 
            "day": "24", 
            "epoch": "1516816620.86637", 
            "hour": "17", 
            "iso8601": "2018-01-24T09:57:00Z", 
            "iso8601_basic": "20180124T175700861308", 
            "iso8601_basic_short": "20180124T175700", 
            "iso8601_micro": "2018-01-24T09:57:00.861308Z", 
            "minute": "57", 
            "month": "01", 
            "second": "00", 
    ......以下省略.......

3、遠(yuǎn)程執(zhí)行命令
遠(yuǎn)程執(zhí)行命令分為遠(yuǎn)程執(zhí)行windows 原生自有命令通過raw 模塊,如:"ipconfig "
遠(yuǎn)程執(zhí)行ansible的win_command模塊也可以執(zhí)行命令,即ansible的擴(kuò)展命令如"whoami"
默認(rèn)是亂碼,需要修改winrm模塊文件

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
a、獲取ip地址
[root@localhost ~]# ansible win7 -m raw -a "ipconfig"
172.16.3.188 | SUCCESS | rc=0 >>
Windows IP Configuration
Ethernet adapter 本地連接:

   Connection-specific DNS Suffix  . : 
   Link-local IPv6 Address . . . . . : fe80::c55d:90f1:8d60:5d97%11
   IPv4 Address. . . . . . . . . . . : 172.16.3.188
   Subnet Mask . . . . . . . . . . . : 255.255.255.0
   Default Gateway . . . . . . . . . : fe80::daae:90ff:fe02:9d81%11
                                       172.16.3.1
         .....省略.....

b、win_command模塊遠(yuǎn)程獲取身份
[root@localhost ansible]# ansible win7 -m win_command -a "whoami"
172.16.3.188 | SUCCESS | rc=0 >>
virtual_san\virtual

c、移動(dòng)文件
[root@localhost ansible]# ansible win7 -m raw -a "cmd /c 'move /y d:\issue c:\issue'"
172.16.3.188 | SUCCESS | rc=0 >>
        1 file(s) moved

d、創(chuàng)建文件夾
[root@localhost ansible]# ansible win7 -m raw -a "mkdir d:\\tst"
172.16.3.188 | SUCCESS | rc=0 >>
    Directory: D:\
Mode                LastWriteTime     Length Name                              
----                -------------     ------ ----                              
d----         2018/1/25     16:44            tst   

e、刪除文件或目錄
[root@localhost ansible]# ansible win7 -m win_file -a "path=D:\1.txt state=absent"
172.16.3.188 | SUCCESS => {
    "attempts": 1, 
    "changed": true, 
    "failed": false
}

f、結(jié)束某程序
先通過 tasklist獲取運(yùn)行程序信息
[root@localhost ansible]# ansible win7 -m raw -a "taskkill /F /IM QQ.exe /T" 
172.16.3.188 | SUCCESS | rc=0 >>
SUCCESS: The process with PID 3504 (child process of PID 2328) has been terminated

4、文件傳輸?shù)絯in7被管理端
把/etc/issue文件復(fù)制到當(dāng)前目錄(也可以直接/etc/issue)再傳送到目標(biāo)主機(jī)D盤下(可以修改文件名)

[root@localhost ~]# ansible win7 -m  win_copy -a "src=issue dest=D:\issue"
172.16.3.188 | SUCCESS => {
    "attempts": 1, 
    "changed": true, 
    "checksum": "5c76e3b565c91e21bee303f15c728c71e6b39540", 
    "dest": "D:\\issue", 
    "failed": false, 
    "operation": "file_copy", 
    "original_basename": "issue", 
    "size": 23, 
    "src": "issue"
}

5、添加用戶

[root@localhost ansible]# ansible win7 -m win_user -a "name=san2 passwd=123.c0m groups=Administrators"
172.16.3.188 | SUCCESS => {
    "account_disabled": false, 
    "account_locked": false, 
    "attempts": 1, 
    "changed": true, 
    "description": "", 
    "failed": false, 
    "fullname": "san2", 
    "groups": [
        {
            "name": "Administrators", 
            "path": "WinNT://WORKGROUP/VIRTUAL_SAN/Administrators"
        }
    ], 
    "name": "san2", 
    "password_expired": true, 
    "password_never_expires": false, 
    "path": "WinNT://WORKGROUP/VIRTUAL_SAN/san2", 
    "sid": "S-1-5-21-2708087092-4192450616-382865091-1004", 
    "state": "present", 
    "user_cannot_change_password": false
}

通過以上的實(shí)踐我得知,要想通過ansible批量管理windows,前提是windows上要基于powershell配置好winrm服務(wù);然后ansible通過模塊和winrm服務(wù)遠(yuǎn)程指管理;這里只是簡單的列舉了向個(gè)常用管理模塊;更多好用的模塊請參考官方windows可用模塊,包括自動(dòng)配置等;

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI