1、windows用戶端需要安裝winrm元件,通過5985和5986兩個端口進行通信,其中5985為非加密端口,5986為加密端口。
2、windows主機在hosts檔案中的添加方法是:
[testwin]
172.16.54.222 ansible_ssh_user=administrator ansible_ssh_pass="xxxxx" ansible_ssh_port=5985 ansible_connection="winrm" ansible_winrm_server_cert_validation=ignore
3、Windows主機要進行些設定,步驟如下:
·将winrm.reg儲存成檔案,并執行
Windows Registry Editor Version 5.00
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\PowerShell\1\ShellIds\ScriptedDiagnostics]
"ExecutionPolicy"="remotesigned"
·以下内容儲存成configureansible.ps1檔案,并在powershell中執行,如果powershell版本未達到3.0,則必須更新版本
Requires -Version 3.0
[CmdletBinding()]
Param (
[string]$SubjectName = $env:COMPUTERNAME,
[int]$CertValidityDays = 1095,
[switch]$SkipNetworkProfileCheck,
$CreateSelfSignedCert = $true,
[switch]$ForceNewSSLCert,
[switch]$GlobalHttpFirewallAccess,
[switch]$DisableBasicAuth = $false,
[switch]$EnableCredSSP
)
Function Write-Log
{
$Message = $args[0]
Write-EventLog -LogName Application -Source $EventSource -EntryType Information -EventId 1 -Message $Message
}
Function Write-VerboseLog
Write-Verbose $Message
Write-Log $Message
Function Write-HostLog
Write-Output $Message
Function New-LegacySelfSignedCert
[string]$SubjectName,
[int]$ValidDays = 1095
$name = New-Object -COM "X509Enrollment.CX500DistinguishedName.1"
$name.Encode("CN=$SubjectName", 0)
$key = New-Object -COM "X509Enrollment.CX509PrivateKey.1"
$key.ProviderName = "Microsoft RSA SChannel Cryptographic Provider"
$key.KeySpec = 1
$key.Length = 4096
$key.SecurityDescriptor = "D:PAI(A;;0xd01f01ff;;;SY)(A;;0xd01f01ff;;;BA)(A;;0x80120089;;;NS)"
$key.MachineContext = 1
$key.Create()
$serverauthoid = New-Object -COM "X509Enrollment.CObjectId.1"
$serverauthoid.InitializeFromValue("1.3.6.1.5.5.7.3.1")
$ekuoids = New-Object -COM "X509Enrollment.CObjectIds.1"
$ekuoids.Add($serverauthoid)
$ekuext = New-Object -COM "X509Enrollment.CX509ExtensionEnhancedKeyUsage.1"
$ekuext.InitializeEncode($ekuoids)
$cert = New-Object -COM "X509Enrollment.CX509CertificateRequestCertificate.1"
$cert.InitializeFromPrivateKey(2, $key, "")
$cert.Subject = $name
$cert.Issuer = $cert.Subject
$cert.NotBefore = (Get-Date).AddDays(-1)
$cert.NotAfter = $cert.NotBefore.AddDays($ValidDays)
$cert.X509Extensions.Add($ekuext)
$cert.Encode()
$enrollment = New-Object -COM "X509Enrollment.CX509Enrollment.1"
$enrollment.InitializeFromRequest($cert)
$certdata = $enrollment.CreateRequest(0)
$enrollment.InstallResponse(2, $certdata, 0, "")
$parsed_cert = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2
$parsed_cert.Import([System.Text.Encoding]::UTF8.GetBytes($certdata))
return $parsed_cert.Thumbprint
Function Enable-GlobalHttpFirewallAccess
Write-Verbose "Forcing global HTTP firewall access"
$fw = New-Object -ComObject HNetCfg.FWPolicy2
$add_rule = $false
$matching_rules = $fw.Rules | ? { $.Name -eq "Windows Remote Management (HTTP-In)" }
$rule = $null
If ($matching_rules) {
If ($matching_rules -isnot [Array]) {
Write-Verbose "Editing existing single HTTP firewall rule"
$rule = $matching_rules
Else {
$rule = $matching_rules | % { $.Profiles -band 4 }[0]
If (-not $rule -or $rule -is [Array]) {
Write-Verbose "Editing an arbitrary single HTTP firewall rule (multiple existed)"
$rule = $matching_rules[0]
If (-not $rule) {
Write-Verbose "Creating a new HTTP firewall rule"
$rule = New-Object -ComObject HNetCfg.FWRule
$rule.Name = "Windows Remote Management (HTTP-In)"
$rule.Description = "Inbound rule for Windows Remote Management via WS-Management. [TCP 5985]"
$add_rule = $true
$rule.Profiles = 0x7FFFFFFF
$rule.Protocol = 6
$rule.LocalPorts = 5985
$rule.RemotePorts = ""
$rule.LocalAddresses = ""
$rule.RemoteAddresses = "*"
$rule.Enabled = $true
$rule.Direction = 1
$rule.Action = 1
$rule.Grouping = "Windows Remote Management"
If ($add_rule) {
$fw.Rules.Add($rule)
Write-Verbose "HTTP firewall rule $($rule.Name) updated"
Trap
$_
Exit 1
$ErrorActionPreference = "Stop"
$myWindowsID=[System.Security.Principal.WindowsIdentity]::GetCurrent()
$myWindowsPrincipal=new-object System.Security.Principal.WindowsPrincipal($myWindowsID)
$adminRole=[System.Security.Principal.WindowsBuiltInRole]::Administrator
if (-Not $myWindowsPrincipal.IsInRole($adminRole))
Write-Output "ERROR: You need elevated Administrator privileges in order to run this script."
Write-Output " Start Windows PowerShell by using the Run as Administrator option."
Exit 2
$EventSource = $MyInvocation.MyCommand.Name
If (-Not $EventSource)
$EventSource = "Powershell CLI"
If ([System.Diagnostics.EventLog]::Exists('Application') -eq $False -or [System.Diagnostics.EventLog]::SourceExists($EventSource) -eq $False)
New-EventLog -LogName Application -Source $EventSource
If ($PSVersionTable.PSVersion.Major -lt 3)
Write-Log "PowerShell version 3 or higher is required."
Throw "PowerShell version 3 or higher is required."
If (!(Get-Service "WinRM"))
Write-Log "Unable to find the WinRM service."
Throw "Unable to find the WinRM service."
ElseIf ((Get-Service "WinRM").Status -ne "Running")
Write-Verbose "Setting WinRM service to start automatically on boot."
Set-Service -Name "WinRM" -StartupType Automatic
Write-Log "Set WinRM service to start automatically on boot."
Write-Verbose "Starting WinRM service."
Start-Service -Name "WinRM" -ErrorAction Stop
Write-Log "Started WinRM service."
If (!(Get-PSSessionConfiguration -Verbose:$false) -or (!(Get-ChildItem WSMan:\localhost\Listener)))
If ($SkipNetworkProfileCheck) {
Write-Verbose "Enabling PS Remoting without checking Network profile."
Enable-PSRemoting -SkipNetworkProfileCheck -Force -ErrorAction Stop
Write-Log "Enabled PS Remoting without checking Network profile."
Write-Verbose "Enabling PS Remoting."
Enable-PSRemoting -Force -ErrorAction Stop
Write-Log "Enabled PS Remoting."
Else
Write-Verbose "PS Remoting is already enabled."
$listeners = Get-ChildItem WSMan:\localhost\Listener
If (!($listeners | Where {$_.Keys -like "TRANSPORT=HTTPS"}))
$thumbprint = New-LegacySelfSignedCert -SubjectName $SubjectName -ValidDays $CertValidityDays
Write-HostLog "Self-signed SSL certificate generated; thumbprint: $thumbprint"
$valueset = @{
Hostname = $SubjectName
CertificateThumbprint = $thumbprint
$selectorset = @{
Transport = "HTTPS"
Address = ""
Write-Verbose "Enabling SSL listener."
New-WSManInstance -ResourceURI 'winrm/config/Listener' -SelectorSet $selectorset -ValueSet $valueset
Write-Log "Enabled SSL listener."
Write-Verbose "SSL listener is already active."
If ($ForceNewSSLCert)
Remove-WSManInstance -ResourceURI 'winrm/config/Listener' -SelectorSet $selectorset
$basicAuthSetting = Get-ChildItem WSMan:\localhost\Service\Auth | Where-Object {$_.Name -eq "Basic"}
If ($DisableBasicAuth)
If (($basicAuthSetting.Value) -eq $true)
Write-Verbose "Disabling basic auth support."
Set-Item -Path "WSMan:\localhost\Service\Auth\Basic" -Value $false
Write-Log "Disabled basic auth support."
Write-Verbose "Basic auth is already disabled."
If (($basicAuthSetting.Value) -eq $false)
Write-Verbose "Enabling basic auth support."
Set-Item -Path "WSMan:\localhost\Service\Auth\Basic" -Value $true
Write-Log "Enabled basic auth support."
Write-Verbose "Basic auth is already enabled."
If ($EnableCredSSP)
$credsspAuthSetting = Get-ChildItem WSMan:\localhost\Service\Auth | Where {$_.Name -eq "CredSSP"}
If (($credsspAuthSetting.Value) -eq $false)
Write-Verbose "Enabling CredSSP auth support."
Enable-WSManCredSSP -role server -Force
Write-Log "Enabled CredSSP auth support."
If ($GlobalHttpFirewallAccess) {
Enable-GlobalHttpFirewallAccess
$fwtest1 = netsh advfirewall firewall show rule name="Allow WinRM HTTPS"
$fwtest2 = netsh advfirewall firewall show rule name="Allow WinRM HTTPS" profile=any
If ($fwtest1.count -lt 5)
Write-Verbose "Adding firewall rule to allow WinRM HTTPS."
netsh advfirewall firewall add rule profile=any name="Allow WinRM HTTPS" dir=in localport=5986 protocol=TCP action=allow
Write-Log "Added firewall rule to allow WinRM HTTPS."
ElseIf (($fwtest1.count -ge 5) -and ($fwtest2.count -lt 5))
Write-Verbose "Updating firewall rule to allow WinRM HTTPS for any profile."
netsh advfirewall firewall set rule name="Allow WinRM HTTPS" new profile=any
Write-Log "Updated firewall rule to allow WinRM HTTPS for any profile."
Write-Verbose "Firewall rule already exists to allow WinRM HTTPS."
$httpResult = Invoke-Command -ComputerName "localhost" -ScriptBlock {$env:COMPUTERNAME} -ErrorVariable httpError -ErrorAction SilentlyContinue
$httpsOptions = New-PSSessionOption -SkipCACheck -SkipCNCheck -SkipRevocationCheck
$httpsResult = New-PSSession -UseSSL -ComputerName "localhost" -SessionOption $httpsOptions -ErrorVariable httpsError -ErrorAction SilentlyContinue
If ($httpResult -and $httpsResult)
Write-Verbose "HTTP: Enabled | HTTPS: Enabled"
ElseIf ($httpsResult -and !$httpResult)
Write-Verbose "HTTP: Disabled | HTTPS: Enabled"
ElseIf ($httpResult -and !$httpsResult)
Write-Verbose "HTTP: Enabled | HTTPS: Disabled"
Write-Log "Unable to establish an HTTP or HTTPS remoting session."
Throw "Unable to establish an HTTP or HTTPS remoting session."
Write-VerboseLog "PS Remoting has been successfully configured for Ansible."
· 在powershell分别執行以下三條語句
winrm qc
winrm set winrm/config/service '@{AllowUnencrypted="true"}'
winrm set winrm/config/service/auth '@{Basic="true"}'
4、window的通信檢測為:ansible testwin -m win_ping
5、Windows下可用子產品雖不及Linux豐富,但基礎功能均包括在内,以下幾個子產品為常用子產品:
win_acl (E) —設定檔案/目錄屬主屬組權限;
win_copy—拷貝檔案到遠端Windows主機;
win_file —建立,删除檔案或目錄;
win_lineinfile—比對替換檔案内容;
win_package (E) —安裝/解除安裝本地或網絡軟體包;
win_ping —Windows系統下的ping子產品,常用來測試主機是否存活;
win_service—管理Windows Services服務;
win_user —管理Windows本地使用者。
更多子產品及詳細功能介紹:
http://docs.ansible.com/ansible/list_of_windows_modules.html除win開頭的子產品外,scripts,raw,slurp,setup子產品在Windows 下也可正常使用。
6、複制檔案到window:
ansible windows -m win_copy -a "src=/etc/passwd dest=E:filepasswd"
7、删除檔案:
ansible windows -m win_file -a "path=E:filepasswd state=absent"
8、新增使用者:
ansible windows -m win_user -a "name=stanley passwd=magedu@123 group=Administrators"
9、重新開機服務:
ansible windows -m win_service -a "name=spooler state=restarted"
10、擷取window主機資訊:
ansible windows -m setup
11、執行ps腳本:
ansible windows -m script -a "E://test.ps1"
12、擷取IP位址:
ansible windows -m win_command -a "ipconfig"
13、檢視檔案狀态:
ansible windows -m win_stat -a "path='C://Windows/win.ini'"
14、移動檔案:
ansible windows -m raw -a "cmd /c 'move /y d:\issue c:\issue'"
15、建立檔案夾:
ansible windows-m raw -a "mkdir d:\tst"
16、重新開機:
ansible windows -m win_reboot
17、結束程式:
ansible windows-m raw -a "taskkill /F /IM QQ.exe /T"
18、如果window主機傳回來的中文是亂碼,則修改ansible控制機上的python編碼:
sed -i "s#tdout_buffer.append(stdout)#tdout_buffer.append(stdout.decode('gbk').encode('utf-8'))#g" /usr/lib/python2.6/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.6/site-packages/winrm/protocol.py
19、window子產品操作手冊:
http://docs.ansible.com/ansible/latest/list_of_windows_modules.html