1. 程式人生 > >MSSQL/WMI/PowerShell結合篇(三)執行PowerShell遠程腳本

MSSQL/WMI/PowerShell結合篇(三)執行PowerShell遠程腳本

powershell

實時監控的基本原理:WMI Monitor—>數據庫服務器(內網)—>PowerShell—>監控服務器(內外網)—>發送微信

前面已介紹如何創建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發送微信信息


本文出自 “aimax” 博客,請務必保留此出處http://aimax.blog.51cto.com/11610508/1967783

MSSQL/WMI/PowerShell結合篇(三)執行PowerShell遠程腳本