码迷,mamicode.com
首页 > 数据库 > 详细

MSSQL/WMI/PowerShell结合篇(三)执行PowerShell远程脚本

时间:2017-09-22 17:45:43      阅读:196      评论:0      收藏:0      [点我收藏+]

标签: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远程脚本

标签:powershell

原文地址:http://aimax.blog.51cto.com/11610508/1967783

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!