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

简介: 1、windows客户端需要安装winrm组件,通过5985和5986两个端口进行通信,其中5985为非加密端口,5986为加密端口。2、windows主机在hosts文件中的添加方法是:[testwin]172.

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

目录
相关文章
|
5天前
|
NoSQL Redis 数据安全/隐私保护
Redis 最流行的图形化界面下载及使用超详细教程(带安装包)! redis windows客户端下载
文章提供了Redis最流行的图形化界面工具Another Redis Desktop Manager的下载及使用教程,包括如何下载、解压、连接Redis服务器以及使用控制台和查看数据类型详细信息。
32 6
Redis 最流行的图形化界面下载及使用超详细教程(带安装包)! redis windows客户端下载
|
5天前
|
NoSQL Redis 数据库
Redis 图形化界面下载及使用超详细教程(带安装包)! redis windows下客户端下载
文章提供了Redis图形化界面工具的下载及使用教程,包括如何连接本地Redis服务器、操作键值对、查看日志和使用命令行等功能。
41 0
Redis 图形化界面下载及使用超详细教程(带安装包)! redis windows下客户端下载
|
1天前
|
Oracle 关系型数据库 MySQL
Mysql(1)—简介及Windows环境下载安装
MySQL 是一个流行的关系型数据库管理系统(RDBMS),基于 SQL 进行操作。它由瑞典 MySQL AB 公司开发,后被 Sun Microsystems 收购,现为 Oracle 产品。MySQL 是最广泛使用的开源数据库之一,适用于 Web 应用程序、数据仓库和企业应用。
16 2
|
2天前
|
JavaScript Windows
windows安装vue
windows安装vue
|
3天前
|
应用服务中间件 Apache Windows
免安装版的Tomcat注册为windows服务
免安装版的Tomcat注册为windows服务
13 3
|
16天前
|
存储 JavaScript 前端开发
Node 版本控制工具 NVM 的安装和使用(Windows)
本文介绍了NVM(Node Version Manager)的Windows版本——NVM for Windows的安装和使用方法,包括如何安装Node.js的特定版本、列出已安装版本、切换使用不同版本的Node.js,以及其他常用命令,以实现在Windows系统上对Node.js版本的便捷管理。
Node 版本控制工具 NVM 的安装和使用(Windows)
|
2天前
|
Ubuntu Linux 开发工具
windows11安装WLS2+Ubuntu
windows11安装WLS2+Ubuntu
|
7天前
|
并行计算 开发工具 异构计算
在Windows平台使用源码编译和安装PyTorch3D指定版本
【10月更文挑战第6天】在 Windows 平台上,编译和安装指定版本的 PyTorch3D 需要先安装 Python、Visual Studio Build Tools 和 CUDA(如有需要),然后通过 Git 获取源码。建议创建虚拟环境以隔离依赖,并使用 `pip` 安装所需库。最后,在源码目录下运行 `python setup.py install` 进行编译和安装。完成后即可在 Python 中导入 PyTorch3D 使用。
|
5月前
|
数据安全/隐私保护 虚拟化 Windows
如何在 VM 虚拟机中安装 Windows Server 2012 操作系统保姆级教程(附链接)
如何在 VM 虚拟机中安装 Windows Server 2012 操作系统保姆级教程(附链接)
|
5月前
|
安全 网络安全 虚拟化
VMware中安装Windows Server 2012系统
在VMware中安装Windows Server 2012系统
431 2