MSSQL/WMI/PowerShell结合篇(三)执行PowerShell远程脚本
实时监控的基本原理:WMI Monitor—>数据库服务器(内网)—>PowerShell—>监控服务器(内外网)—>发送微信
我们提供的服务有:网站制作、成都网站建设、微信公众号开发、网站优化、网站认证、龙口ssl等。为上1000+企事业单位解决了网站和推广的问题。提供周到的售前咨询和贴心的售后服务,是有科学管理、有技术的龙口网站制作公司
前面已介绍如何创建WMI Monitor,本文介绍如何执行PowerShell远程脚本,实现将WMI获取到的信息从数据库服务器传到监控服务器,即数据库服务器(内网)—>PowerShell—>监控服务器(内外网)
一、帐号密码信息加密
设置密钥,并将密钥、帐号、密码加密后信息存放于文本中
1、设置加密密钥
function Set-Key {
param([string]$string)
$length = $string.length
$pad = 32-$length
if (($length -lt 16) -or ($length -gt 32)) {Throw "String must be between 16 and 32 characters"}
$encoding = New-Object System.Text.ASCIIEncoding
$bytes = $encoding.GetBytes($string + "0" * $pad)
return $bytes
}
2、加密方法
##set Encrypted Data
function Set-EncryptedData {
param($key,[string]$plainText)
$securestring = new-object System.Security.SecureString
$chars = $plainText.toCharArray()
foreach ($char in $chars) {$secureString.AppendChar($char)}
$encryptedData = ConvertFrom-SecureString -SecureString $secureString -Key $key
return $encryptedData
}
3、解密方法
##get Encrypted Data
function Get-EncryptedData {
param($key,$data)
$data | ConvertTo-SecureString -key $key |
ForEach-Object {[Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR($_))}
}
二、创建远程会话,并执行远程脚本
获取密钥,并对帐号密码进行解密
$idkeystr=gc D:\xxx\IDkey.txt
$userid=gc D:\xxx\ID.txt
$IDkey=set-key $idkeystr
$appServerUser=get-EncryptedData $IDkey $userid
$pwkeystr=gc D:\xxx\PWkey.txt
$passwd=gc D:\xxx\PW.txt
$PWkey=set-key $pwkeystr
$appServerPwd=get-EncryptedData $PWkey $passwd
$appServer='MonitorServer'
$password = ConvertTo-SecureString $appServerPwd -AsPlainText -Force
$appCred = New-Object System.Management.Automation.PsCredential($appServerUser,$password)
##创建会话
$s = New-PSSession -ComputerName $appServer -Credential $appCred -UseSSL -SessionOption (New-PSSessionOption -SkipCACheck -SkipCNCheck) -Authentication Negotiate
##执行无参数脚本
Invoke-Command -Session $s -ScriptBlock {powershell -File E:\\xxx\\xxx.ps1}
##执行带参数脚本
Invoke-Command -Session $s -ScriptBlock {powershell -File E:\\xxx\\xxx.ps1 $args[0] $args[1] $args[2]} -ArgumentList $text1,$text2,$text3
##删除会话
$s|Remove-PSSession
下一篇介绍如何通过PowerShell发送微信信息
文章名称:MSSQL/WMI/PowerShell结合篇(三)执行PowerShell远程脚本
标题链接:http://azwzsj.com/article/pshooh.html