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
{
$Message = $args[0]
Write-Verbose $Message
Write-Log $Message
}
Function Write-HostLog
{
$Message = $args[0]
Write-Output $Message
Write-Log $Message
}
Function New-LegacySelfSignedCert
{
Param (
[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."
}
Else {
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."
}
Else
{
Write-Verbose "SSL listener is already active."
If ($ForceNewSSLCert)
{
$thumbprint = New-LegacySelfSignedCert -SubjectName $SubjectName -ValidDays $CertValidityDays
Write-HostLog "Self-signed SSL certificate generated; thumbprint: $thumbprint"
$valueset = @{
CertificateThumbprint = $thumbprint
Hostname = $SubjectName
}
$selectorset = @{
Address = ""
Transport = "HTTPS"
}
Remove-WSManInstance -ResourceURI 'winrm/config/Listener' -SelectorSet $selectorset
New-WSManInstance -ResourceURI 'winrm/config/Listener' -SelectorSet $selectorset -ValueSet $valueset
}
}
$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."
}
Else
{
Write-Verbose "Basic auth is already disabled."
}
}
Else
{
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."
}
Else
{
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."
}
Else
{
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"
}
Else
{
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