用powershell 管理windows 服務(wù)器
1 連接遠(yuǎn)程powershell
1.1 服務(wù)器端配置
開(kāi)啟winrm服務(wù)
net start winrm
如果不確定是否開(kāi)啟赃泡,通過(guò)以下方式查看兄淫,狀態(tài)running
Get-Service | findstr "WinRM"
啟用powershell 遠(yuǎn)程管理谒出,全部按照默認(rèn)選項(xiàng)執(zhí)行
Enable-PSRemoting -Force
關(guān)閉本地防火墻
netsh advfirewall set allprofiles state off
1.2 客戶(hù)端配置
開(kāi)啟winrm服務(wù)
net start winrm
如果不確定是否開(kāi)啟忧饭,通過(guò)以下方式查看逾滥,狀態(tài)running
Get-Service | findstr "WinRM"
啟用powershell 遠(yuǎn)程管理徐勃,全部按照默認(rèn)選項(xiàng)執(zhí)行
Enable-PSRemoting -Force
將需要遠(yuǎn)程的客戶(hù)端IP加入信任列表(e.g 172.16.2.111)
Set-Item WSMan:\localhost\Client\TrustedHosts -Value "172.16.2.111"
Get-Item WSMan:\localhost\Client\TrustedHosts
連接到遠(yuǎn)程powershell,輸入賬號(hào)密碼進(jìn)行連接
Enter-PSSession -ComputerName "x.x.x.x" -Credential $X
此時(shí)如果有報(bào)錯(cuò)如下羡儿,檢查一下在客戶(hù)端的信任列表 是否加入了遠(yuǎn)程ip
Enter-PSSession : 連接到遠(yuǎn)程服務(wù)器 x.x.x.x 失敗礼患,并顯示以下錯(cuò)誤消息: WinRM 客戶(hù)端無(wú)法處理該請(qǐng)求。如果身份驗(yàn)證方案
與 Kerberos 不同掠归,或者客戶(hù)端計(jì)算機(jī)未加入到域中缅叠, 則必須使用 HTTPS 傳輸或者必須將目標(biāo)計(jì)算機(jī)添加到 TrustedHosts 配置設(shè)置
。 使用 winrm.cmd 配置 TrustedHosts虏冻。請(qǐng)注意肤粱,TrustedHosts 列表中的計(jì)算機(jī)可能未經(jīng)過(guò)身份驗(yàn)證。 通過(guò)運(yùn)行以下命令可獲得有關(guān)
此內(nèi)容的更多信息: winrm help config厨相。 有關(guān)詳細(xì)信息领曼,請(qǐng)參閱 about_Remote_Troubleshooting 幫助主題鸥鹉。
所在位置 行:1 字符: 1
+ Enter-PSSession -ComputerName "x.x.x.x" -Credential $a
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (x.x.x.x:String) [Enter-PSSession],PSRemotingTransportException
+ FullyQualifiedErrorId : CreateRemoteRunspaceFailed
1.3 遠(yuǎn)程賬號(hào)連接信息管理
上一節(jié)中通過(guò) Enter-PSSession 命令連接需要每次管理員手動(dòng)輸入密碼庶骄,對(duì)于多臺(tái)服務(wù)器管理十分繁瑣毁渗。可以通過(guò)設(shè)置變量的方式单刁,保存賬號(hào)密碼灸异。
#第一種方式 with UI
$dev Get-Credential
Enter-PSSession -ComputerName "x.x.x.x" -Credential $dev
#第二種方式
$devu = "administrator"
$devp = ConvertTo-SecureString "password" -AsPlainText -Force
$dev = New-Object System.Management.Automation.PSCredential($devu,$devp)
Enter-PSSession -ComputerName "x.x.x.x" -Credential $dev
查看dev對(duì)象
$dev | Get-Member
將dev對(duì)象的秘鑰轉(zhuǎn)換成加密字符
ConvertFrom-SecureString -SecureString $dev.Password
1.4 自動(dòng)化腳本
1.4.1 配置腳本(ps服務(wù)端執(zhí)行)
$WinRMStatus = (Get-Service | Where-Object {$_.Name -ieq "WinRM"} | Select-Object -ExpandProperty Status | Out-String).TrimEnd()
if ($WinRMStatus -ieq "Running"){ Write-Host -ForegroundColor Red "Winrm already start" }
else {
Write-Host -ForegroundColor Red "starting winrm..."
net start winrm
}
Write-Host -ForegroundColor Red "enable psremoting...".
Enable-PSRemoting -Force
1.4.2 連接腳本(ps客戶(hù)端執(zhí)行)
#$1 client ip
#$2 username
#$3 password
$ipadd = $1
$pass = $3
function CreateSession {
param($ipadd,$pass)
Set-Item WSMan:\localhost\Client\TrustedHosts -Value $ipadd -Force
$u = "administrator"
$p = ConvertTo-SecureString $pass -AsPlainText -Force
$credent = New-Object System.Management.Automation.PSCredential($u,$p)
$connection = New-PSSession -ComputerName $ipadd -Credential $credent
return $connection
}
$s = CreateSession $ipadd $pass
Invoke-Command -Session $s -ScriptBlock { ls }
Disconnect-PSSession -Session $s
2 管理遠(yuǎn)程IIS
2.1 連接到遠(yuǎn)程powershell
參考 1 連接遠(yuǎn)程powershell 連接到遠(yuǎn)程服務(wù)器
安裝IIS相關(guān)模塊
GET-WindowsFeature web*
Install-WindowsFeature Web-Server
Install-WindowsFeature Web-WebServer
Install-WindowsFeature Web-Security
Install-WindowsFeature Web-Filtering
Install-WindowsFeature Web-Windows-Auth
Install-WindowsFeature Web-Basic-Auth
Install-WindowsFeature Web-Common-Http
Install-WindowsFeature Web-Http-Errors
Install-WindowsFeature Web-Static-Content
Install-WindowsFeature Web-Default-Doc
Install-WindowsFeature Web-Dir-Browsing
Install-WindowsFeature Web-Http-Redirect
Install-WindowsFeature Web-Performance
Install-WindowsFeature Web-Stat-Compression
Install-WindowsFeature Web-Health
Install-WindowsFeature Web-Http-Logging
Install-WindowsFeature Web-App-Dev
Install-WindowsFeature Web-Net-Ext
Install-WindowsFeature Web-Net-Ext45
Install-WindowsFeature Web-ASP
Install-WindowsFeature Web-Asp-Net45
Install-WindowsFeature Web-ISAPI-Ext
Install-WindowsFeature Web-ISAPI-Filter
添加 webadministration 模塊
Import-Module WebAdministration
2.2 管理IIS
2.2.1 新建站點(diǎn)
- 新建應(yīng)用程序池
New-Item iis:\AppPools\testweb
- 修改Framework 版本
Set-ItemProperty iis:\AppPools\testweb managedRuntimeVersion v4.0
- 新建站點(diǎn),綁定端口羔飞,設(shè)置站點(diǎn)物理物理路徑
New-Item iis:\Sites\testweb -bindings @{protocol="http";bindingInformation=":8080:"} -physicalPath d:\
- 更改應(yīng)用程序池
Set-ItemProperty IIS:\Sites\testweb -Name applicationPool -value testweb
2.2.2 物理路徑切換
- 物理路徑切換
Set-ItemProperty iis:\Sites\testweb -Name physicalPath -Value c:\
2.2.3 文件拷貝
統(tǒng)一上傳版本到文件服務(wù)器
版本文件規(guī)則 packagename_version (e.g AppLogging_1_0_2)
使用xcopy 對(duì)程序文件進(jìn)行管理
#$ipadd 目標(biāo)服務(wù)器IP地址
#$version 版本號(hào)
#$passwords 服務(wù)器密碼
#$sitename 站點(diǎn)名稱(chēng)
#$conect 遠(yuǎn)程連接會(huì)話(huà)
Invoke-Command -Session $conect -ScriptBlock { Import-Module WebAdministration }
#獲取當(dāng)前版本路徑 D$\detpath
$oldpath = (Invoke-Command -Session $conect -ArgumentList $sitename -ScriptBlock{ param($sitename) Get-ChildItem IIS:\Sites | Where-Object {$_.Name -ieq $sitename } | Select-Object -ExpandProperty PhysicalPath | Out-String }).TrimEnd() -replace '[:\t]','$'
#標(biāo)準(zhǔn)路徑格式保存 D:\detpath
$newpath = $oldpath -replace '[$\t]',':'
#建立遠(yuǎn)程連接
net use \\$ipadd\ipc$ $pass /user:Administrator
#為新版本創(chuàng)建目錄肺樟,全量拷貝上一個(gè)版本
xcopy \\$ipadd\$oldpath \\$ipadd\${oldpath}_$version\ /D /E /Y /H /K
#拷貝增量到新版本路徑
#
#切換站點(diǎn)到新版本目錄
Invoke-Command -Session $conect -ArgumentList $newpath,$sitename,$version -ScriptBlock { param($newpath,$sitename,$version)Set-ItemProperty IIS:\Sites\$sitename -Name PhysicalPath -Value "${newpath}_$version" }
net use \\$ipadd /del
通過(guò)Invoke-Command 執(zhí)行遠(yuǎn)程命令傳參時(shí),務(wù)必將本地參數(shù)在遠(yuǎn)程腳本中聲明
2.3 站點(diǎn)管理自動(dòng)化腳本
2.3.1 參數(shù)申明
param(
$ip,
$passwords,
$sitename,
$port,
$version, # 1_2_1
$sourceroot, #文件服務(wù)器根目錄
$dstroot #遠(yuǎn)程站點(diǎn)根目錄
)
2.3.2 創(chuàng)建連接
function CreateSession {
param($ipadd,$pass)
Set-Item WSMan:\localhost\Client\TrustedHosts -Value $ipadd -Force
$u = "administrator"
$p = ConvertTo-SecureString $pass -AsPlainText -Force
$credent = New-Object System.Management.Automation.PSCredential($u,$p)
$connection = New-PSSession -ComputerName $ipadd -Credential $credent
return $connection
}
2.3.3 新建站點(diǎn)
function CreateWebSite {
# $conection is a Object create by function CreateSession
param($conection, $sitename, $port )
Invoke-Command -Session $conection -ArgumentList $sitename,$port -ScriptBlock {
param($sitename,$port)
Function Test-PortAvailable {
param(
[validaterange(1,65535)]
[int]$Port
)
$sockt=New-Object System.Net.Sockets.Socket -ArgumentList 'InterNetwork','Stream','TCP'
$ip = (Get-NetIPConfiguration).IPv4Address | Select -First 1 -ExpandProperty IPAddress
$ipAddress = [Net.IPAddress]::Parse($ip)
Try {
$ipEndpoint = New-Object System.Net.IPEndPoint $ipAddress,$port
$sockt.Bind($ipEndpoint)
return $true
}
Catch [exception] {
return $false
}
Finally {
$sockt.Close()
}
}
Import-Module WebAdministration
if ( (Test-Path iis:\AppPools\$sitename) -or (Test-Path iis:\Sites\$sitename) -or !(Test-PortAvailable -Port $port) ) {
if (Test-Path iis:\AppPools\$sitename) { echo "[error] apppools $sitename has already exist." }
if (Test-Path iis:\Sites\$sitename) { echo "[error] Site $sitename has already exist." }
if (!(Test-PortAvailable -Port $port)) { echo "[error] Port $port is unavilabel." }
return $false
}
else {
try {
New-Item iis:\AppPools\$sitename
echo "[info] AppPool $sitename created. "
Set-ItemProperty iis:\AppPools\$sitename managedRuntimeVersion v4.0
echo "[info] Set AppPool $sitename managedRuntimeVersion v4.0. "
New-Item iis:\Sites\$sitename -bindings @{protocol="http";bindingInformation=":${port}:"}
echo "[info] Site $sitename created.And Binding http ${port}."
Set-ItemProperty IIS:\Sites\$sitename -Name applicationPool -value $sitename
echo "[info] Set Site $sitename AppPool iis:\AppPools\$sitename ."
return $true
}
catch {
echo "Error $Error[0]"
return $false
}
Finally {
}
}
}
}
2.3.2 文件傳輸
2.3.3 版本切換