Ansible windows客户端安装及部分模块使用(学习笔记十六)

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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 204,445评论 6 478
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 85,889评论 2 381
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 151,047评论 0 337
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,760评论 1 276
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,745评论 5 367
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,638评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 38,011评论 3 398
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,669评论 0 258
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,923评论 1 299
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,655评论 2 321
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,740评论 1 330
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,406评论 4 320
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,995评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,961评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,197评论 1 260
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 45,023评论 2 350
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,483评论 2 342

推荐阅读更多精彩内容