用powershell 管理windows 服务器
1 连接远程powershell
1.1 服务器端配置
开启winrm服务
net start winrm
如果不确定是否开启,通过以下方式查看,状态running
Get-Service | findstr "WinRM"
启用powershell 远程管理,全部按照默认选项执行
Enable-PSRemoting -Force
关闭本地防火墙
netsh advfirewall set allprofiles state off
1.2 客户端配置
开启winrm服务
net start winrm
如果不确定是否开启,通过以下方式查看,状态running
Get-Service | findstr "WinRM"
启用powershell 远程管理,全部按照默认选项执行
Enable-PSRemoting -Force
将需要远程的客户端IP加入信任列表(e.g 172.16.2.111)
Set-Item WSMan:\localhost\Client\TrustedHosts -Value "172.16.2.111"
Get-Item WSMan:\localhost\Client\TrustedHosts
连接到远程powershell,输入账号密码进行连接
Enter-PSSession -ComputerName "x.x.x.x" -Credential $X
此时如果有报错如下,检查一下在客户端的信任列表 是否加入了远程ip
Enter-PSSession : 连接到远程服务器 x.x.x.x 失败,并显示以下错误消息: WinRM 客户端无法处理该请求。如果身份验证方案
与 Kerberos 不同,或者客户端计算机未加入到域中, 则必须使用 HTTPS 传输或者必须将目标计算机添加到 TrustedHosts 配置设置
。 使用 winrm.cmd 配置 TrustedHosts。请注意,TrustedHosts 列表中的计算机可能未经过身份验证。 通过运行以下命令可获得有关
此内容的更多信息: winrm help config。 有关详细信息,请参阅 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 远程账号连接信息管理
上一节中通过 Enter-PSSession 命令连接需要每次管理员手动输入密码,对于多台服务器管理十分繁琐。可以通过设置变量的方式,保存账号密码。
#第一种方式 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对象
$dev | Get-Member
将dev对象的秘钥转换成加密字符
ConvertFrom-SecureString -SecureString $dev.Password
1.4 自动化脚本
1.4.1 配置脚本(ps服务端执行)
$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客户端执行)
#$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 管理远程IIS
2.1 连接到远程powershell
参考 1 连接远程powershell 连接到远程服务器
安装IIS相关模块
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 新建站点
- 新建应用程序池
New-Item iis:\AppPools\testweb
- 修改Framework 版本
Set-ItemProperty iis:\AppPools\testweb managedRuntimeVersion v4.0
- 新建站点,绑定端口,设置站点物理物理路径
New-Item iis:\Sites\testweb -bindings @{protocol="http";bindingInformation=":8080:"} -physicalPath d:\
- 更改应用程序池
Set-ItemProperty IIS:\Sites\testweb -Name applicationPool -value testweb
2.2.2 物理路径切换
- 物理路径切换
Set-ItemProperty iis:\Sites\testweb -Name physicalPath -Value c:\
2.2.3 文件拷贝
统一上传版本到文件服务器
版本文件规则 packagename_version (e.g AppLogging_1_0_2)
使用xcopy 对程序文件进行管理
#$ipadd 目标服务器IP地址
#$version 版本号
#$passwords 服务器密码
#$sitename 站点名称
#$conect 远程连接会话
Invoke-Command -Session $conect -ScriptBlock { Import-Module WebAdministration }
#获取当前版本路径 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]','$'
#标准路径格式保存 D:\detpath
$newpath = $oldpath -replace '[$\t]',':'
#建立远程连接
net use \\$ipadd\ipc$ $pass /user:Administrator
#为新版本创建目录,全量拷贝上一个版本
xcopy \\$ipadd\$oldpath \\$ipadd\${oldpath}_$version\ /D /E /Y /H /K
#拷贝增量到新版本路径
#
#切换站点到新版本目录
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
通过Invoke-Command 执行远程命令传参时,务必将本地参数在远程脚本中声明
2.3 站点管理自动化脚本
2.3.1 参数申明
param(
$ip,
$passwords,
$sitename,
$port,
$version, # 1_2_1
$sourceroot, #文件服务器根目录
$dstroot #远程站点根目录
)
2.3.2 创建连接
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 新建站点
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 版本切换
网友评论