Powershell 自動執行的幫助工具, 俺忘記啥時用過, 反正就按裝


http://wp.me/ph3BR-1gF

 

每天的密碼太多了, 要輸入很多又麻煩.

以前都用 DOS 的年代, 使用 BAT 執行一些自動化的簡單劇本, 但是到了 WINDOWS 系統, 很多 BAT 都不行, 但是某些動作還是可以用 BAT 完成, Windows95 到 Windows8 都可以. 但是如果一個應用程式啟動後要求是使用者互動或輸入密碼之類的工作, BAT 就無能為力. 俺記得用 CC:MAIL  (LOTUS 買斷的產品EMAIL軟體) 的時候, 那是 WIN98 和 XP 的交替時間, 俺刨了一些網上的資料, 使用 WIN32 的 API, 可以自動在 EMAIL 內容加入當下時間印記以及一些當時流行的 ASCII 圖形的簽名檔, 其實是可以做到的, 不過需要用到 WIN32 API 的底層, 首先找到那個 CCMAIL 的 PID, 再提取她的 HANDLE, 然後向 HANDLE 內 [編輯WINDOW] 內注入文字, 達到自動化輸入文字的效果, 然後生成一封有特色的 EMAIL. 需要用到 WIN32ASM 編譯的, 而且不是一般使用者可以修改的. 不過太久, 已經不記得實際的編碼過程了.

這次突然要用到 Microsoft Daynamic AX, 想要自動化執行自動連接 VPN 然後啟動 AX, 所以抄了一個劇本, 看她的內容, 細心讀了一下和編排的格式, 大約明白, 她的方法和使用 WIN32 API 寫 EMAIL 很類似的方法, 畢竟 WINDOWS 的 API, 應該都是那套, 除了增加新功能以外 (WIN64API ??). 基本測試完畢, 俺的機器完全沒問題, 可是 Deploy 到其他機器發現不能執行, 後來有再看看 Powershell 的使用要求, 原來要先修改設定 PowerShell 的那個 ExecutionPolicy, 預設是 Restricted, 要執行自己寫的 ps1 script, 要設成 ExecutionPolicy RemoteSigned 或者是 ExecutionPolicy AllSigned, 還要自己給自己簽發一個 Certificate, 然後才能執行 Powershell 的劇本, file Extension 是 Ps1

俺記得曾經搞過一次給自己簽發一個 Certificate, 好像是 Visual Studio 2012 寫傳真軟件的時候, 已經完全忘記, 而這次更麻煩, 要手動, 沒有 Visual Studio 2012

看了一大堆網站, 也測試很多, 反正神馬的一堆, 有可參考的, 也有錯誤的資料, 終於也做好了. 記以下, 不然下次又要花時間了.

 

俺自己的碼,

 


REM -- file name : login_vpn_ax.bat

C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe "D:\AX_Powershell_auto_login\Cisco_VPN_AutoLogin.ps1"

pause

 

 


# Procedure : how to sign your own PS1 (powershell script)

# file name : how_to_sign_ps1.txt

# ref: http://www.hanselman.com/blog/SigningPowerShellScripts.aspx

2014-07-09, xiaolaba

# Run As Administrator
# start powershell

## for Jane and her PC
cd D:\AX_Powershell_auto_login

## for Dorthy and her PC
cd C:\AX_Powershell_auto_login

copy makecert.exe to local folder

############################################################
#### creates a local certificate authority for your computer
############################################################
# makecert -n "CN=MyRoot" -a sha1 -eku 1.3.6.1.5.5.7.3.3 -r -sv root.pvk root.cer -ss Root -sr localMachine

## Visual Studio 2012 installed, use below
makecert -n "CN=PowerShell Local Certificate Root" -a sha1 -eku 1.3.6.1.5.5.7.3.3 -r -sv root.pvk root.cer -ss Root -sr localMachine

# uses makecert.exe at local folder
.\makecert -n "CN=PowerShell Local Certificate Root" -a sha1 -eku 1.3.6.1.5.5.7.3.3 -r -sv root.pvk root.cer -ss Root -sr localMachine

############################################################
#### generates a personal certificate from the above certificate authority
############################################################
# makecert -pe -n "CN=MyCertificate" -ss MY -a sha1 -eku 1.3.6.1.5.5.7.3.3 -iv root.pvk -ic root.cer

## Visual Studio 2012 installed, use below
makecert -pe -n "CN=My_Powershell_Certificate" -ss MY -a sha1 -eku 1.3.6.1.5.5.7.3.3 -iv root.pvk -ic root.cer

## uses makecert.exe at local folder
.\makecert -pe -n "CN=MyCertificate" -ss MY -a sha1 -eku 1.3.6.1.5.5.7.3.3 -iv root.pvk -ic root.cer

############################################################
#### verify from Powershell that the certificate was generated correctly
############################################################
gci cert:\CurrentUser\My -codesigning

############################################################
#### sign the script, 2 command line version or 1 command line
############################################################
# $cert = @(gci cert:\currentuser\my -codesigning)[0]
# Set-AuthenticodeSignature CiscoVPNAutoLogin.ps1 $cert
Set-AuthenticodeSignature CiscoVPNAutoLogin.ps1 @(Get-ChildItem cert:\CurrentUser\My -codesign)[0]

#### done, your script is signed

#### set policy to be with signed script, win7 & win8.1, tested
Set-ExecutionPolicy AllSigned

#### if want to check certificate, Win7, win8.1 tested
certmgr.msc

.

.

.


# this is a script, auto login VPN and to start AX

# file name : Cisco_VPN_AutoLogin.ps1

#ref :

#http://www.joshuasjohnson.com/how-to-script-a-login-for-a-cisco-vpn-client/

2014-07-08, xiaolaba

#Source http://www.cze.cz
#This script is tested with “Cisco AnyConnect Secure Mobility Client version 3.0.5080〃
#Please change following variables

#IP address or host name of cisco vpn
[string]$CiscoVPNHost = "www.myciscovpn.ip"
[string]$Login = "ciscovpn_user_name"
[string]$Password = "ciscovpn_pass_word"

#Please check if file exists on following paths
[string]$vpnuiAbsolutePath = 'C:\Program Files (x86)\Cisco\Cisco AnyConnect Secure Mobility Client\vpnui.exe'
[string]$vpncliAbsolutePath = 'C:\Program Files (x86)\Cisco\Cisco AnyConnect Secure Mobility Client\vpncli.exe'

[string]$axRdp = "AX.rdp"

#****************************************************************************
#**** Please do not modify code below unless you know what you are doing ****
#****************************************************************************

Add-Type -AssemblyName System.Windows.Forms -ErrorAction Stop

#Set foreground window function
#This function is called in VPNConnect
Add-Type @’
using System;
using System.Runtime.InteropServices;
public class Win {
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool SetForegroundWindow(IntPtr hWnd);
}
‘@ -ErrorAction Stop

#quickly start VPN
#This function is called later in the code
Function VPNConnect()
{
Start-Process -FilePath $vpncliAbsolutePath -ArgumentList “connect $CiscoVPNHost”
$counter = 0; $h = 0;
while($counter++ -lt 1000 -and $h -eq 0)
{
#sleep -m 30 #30 minisecond
sleep -m 10 #10 mini second
$h = (Get-Process vpncli).MainWindowHandle
}
#if it takes more than 10 seconds then display message
if($h -eq 0){echo “Could not start VPNUI it takes too long.”}
else{[void] [Win]::SetForegroundWindow($h)}
}

#Terminate all vpnui processes.
Get-Process | ForEach-Object {if($_.ProcessName.ToLower() -eq “vpnui”)
{$Id = $_.Id; Stop-Process $Id; echo “Process vpnui with id: $Id was stopped”}}

#Terminate all vpncli processes.
Get-Process | ForEach-Object {if($_.ProcessName.ToLower() -eq “vpncli”)
{$Id = $_.Id; Stop-Process $Id; echo “Process vpncli with id: $Id was stopped”}}

#Disconnect from VPN
echo “Trying to terminate remaining vpn connections”
start-Process -FilePath $vpncliAbsolutePath -ArgumentList ‘disconnect’ -wait

#Connect to VPN
echo “Connecting to VPN address ‘$CiscoVPNHost’ as user ‘$Login’.”
VPNConnect

#Write login and password
[System.Windows.Forms.SendKeys]::SendWait(“$Login{Enter}”)
[System.Windows.Forms.SendKeys]::SendWait(“$Password{Enter}”)

#Start vpnui
start-Process -FilePath $vpnuiAbsolutePath

#Wait for keydown
# 2014-07-06 xiaolaba, remove key press requirement, unless debug purpose
#echo “Press any key to continue …”

#try{$x = $host.UI.RawUI.ReadKey(“NoEcho,IncludeKeyDown”)}catch{}

#Start AX rdp
# 2014-07-08 xiaolaba
sleep -s 30 #wait 30 seconds
start-Process $axRdp

#end of script

# the following part, only available when you are signed this script

# SIG # Begin signature block
# MIIFtwYJKoZIhvcNAQcCoIIFqDCCBaQCAQExCzAJBgUrDgMCGgUAMGkGCisGAQQB
# gjcCAQSgWzBZMDQGCisGAQQBgjcCAR4wJgIDAQAABBAfzDtgWUsITrck0sYpfvNR
# AgEAAgEAAgEAAgEAAgEAMCEwCQYFKw4DAhoFAAQUFr0YcW5r/SziasRp7fWPwiVS
# A6ygggNAMIIDPDCCAiigAwIBAgIQ8neafehn55RAbJ78ArmxRDAJBgUrDgMCHQUA
# MCwxKjAoBgNVBAMTIVBvd2VyU2hlbGwgTG9jYWwgQ2VydGlmaWNhdGUgUm9vdDAe
# Fw0xNDA3MTAwMDA4NDNaFw0zOTEyMzEyMzU5NTlaMBgxFjAUBgNVBAMTDU15Q2Vy
# dGlmaWNhdGUwggEi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3AgEMMQowCKACgAChAoAAMBkGCSqG
# SIb3DQEJAzEMBgorBgEEAYI3AgEEMBwGCisGAQQBgjcCAQsxDjAMBgorBgEEAYI3
# AgEVMCMGCSqGSIb3DQEJBDEWBBT78zggG5reQpZowOaR/eGfFKJ95jANBgkqhkiG
# 9w0BAQEFAASCAQA1gnzPhmCfmfXI3uE/HwJsqOlRX+/xh9WtNCdPFoq382iAQ4qo
# 4qow+HxOZuExAQEnCEfA1AOdJRHqfxVeG2wlPUqJPyOX7qZdNywqooP+nPezL7LS
# DInNqBG3M3qfTYJLUjHEdFZBbQ/AtYB1MG/3AG4i83Mb5nVyrNQluzdnq+ZIOSc2
# so277bSpemECmGWiUnPbEmlV3w4EdB51a75HDsqiUAL3QRxz2Yq9QpKH0Ho59kNG
# JTEFyidwR1Lepcie/mhVtlRa/GxQkIB8WYpS4bLe2EFlV9mtwg6nJH6g774iM7iR
# qsmWreQeCRU1sFOCKbz9XXF/3kHjKuGARoBi
# SIG # End signature block

 

ref :

http://technet.microsoft.com/en-us/library/ee176949.aspx
http://www.hanselman.com/blog/SigningPowerShellScripts.aspx
http://msdn.microsoft.com/zh-tw/library/bfsktky3(VS.80).aspx
http://msdn.microsoft.com/zh-tw/library/bfsktky3(v=vs.110).aspx
http://technet.microsoft.com/zh-tw/magazine/2008.04.powershell.aspx
http://msdn.microsoft.com/en-us/library/windows/desktop/jj835832(v=vs.85).aspx
http://www.spadeworx.net/WINDOWS/SysWOW64/windowspowershell/v1.0/zh-cht/about_signing.help.txt
http://technet.microsoft.com/zh-tw/magazine/2008.01.powershell.aspx
http://technet.microsoft.com/en-us/magazine/2008.04.powershell.aspx

廣告

發表迴響

在下方填入你的資料或按右方圖示以社群網站登入:

WordPress.com Logo

您的留言將使用 WordPress.com 帳號。 登出 / 變更 )

Twitter picture

您的留言將使用 Twitter 帳號。 登出 / 變更 )

Facebook照片

您的留言將使用 Facebook 帳號。 登出 / 變更 )

Google+ photo

您的留言將使用 Google+ 帳號。 登出 / 變更 )

連結到 %s