65.9K
CodeProject 正在变化。 阅读更多。
Home

一键登录思科 AnyConnect 安全移动客户端 VPN

starIconstarIconstarIconstarIconstarIcon

5.00/5 (2投票s)

2018 年 6 月 29 日

CPOL

2分钟阅读

viewsIcon

14170

通过思科一键登录 VPN,在 30 秒内跳转到您的 VPN 系统!

引言

每天通过思科登录 VPN 是一项非常枯燥的过程。只需设置一次,您就可以一直使用,直到您的 VPN 登录密码过期。此 PowerShell 脚本仅适用于从您的本地系统通过思科 AnyConnect 安全移动客户端连接到您的 AD 服务器的 Windows 7 及更高版本的系统。

必备组件

  1. PowerShell 版本 4+(如果您使用的是较低版本,请从此处下载)。
  2. .NET Framework 3.5+
  3. 思科 AnyConnect 安全移动客户端 v4.6

设置过程

复制脚本并粘贴到 Windows PowerShell 编辑器中,阅读注释并进行设置。

我仅测试了使用思科 AnyConnect 安全移动客户端 v4.6 的 Windows 环境。

<#

========================================================================
-- Author                 : RAMANAREDDY V
-- Create date            : 26-06-2018
-- Description            : VPN SERVER Login with single click
-- Script Name            : VPN SERVER.ps1
===========================================================================

#>
Set-ExecutionPolicy -ExecutionPolicy Bypass
TRY{
Set-ExecutionPolicy -ExecutionPolicy Bypass
If (-NOT ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::
GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator"))

{   
$arguments = "& '" + $myinvocation.mycommand.definition + "'"
Start-Process powershell -Verb runAs -ArgumentList $arguments
Break
}

Set-ExecutionPolicy -ExecutionPolicy Bypass

$vpnuiAbsolutePath = 'C:\Program Files (x86)\Cisco\Cisco AnyConnect Secure Mobility 
Client\vpnui.exe' # Check the location CISCO vpnui.exe presence must and should.
$ServerIpAddress="10.000.00.00"
$UserName="Your domain\username"
$Password="Your password"  # Here you can secure ur password by using encryption process. 
I am given just basic format.

Start-Process -FilePath $vpnuiAbsolutePath

$pinvokes = @'

using System;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using System.Text;
public class Program
{
private delegate bool EnumWindowProc(IntPtr hWnd, IntPtr parameter);
// Get a handle to an application window.
[DllImport("USER32.DLL", CharSet = CharSet.Unicode)]
public static extern IntPtr FindWindow(string lpClassName,
string lpWindowName);
[DllImport("user32.dll", EntryPoint = "FindWindow", SetLastError = true)]
private static extern IntPtr FindWindowByCaption(IntPtr zeroOnly, string lpWindowName);
[DllImport("user32.dll", EntryPoint = "GetWindowText", CharSet = CharSet.Auto)]
private static extern IntPtr GetWindowCaption(IntPtr hwnd, StringBuilder lpString, int maxCount);
[return: MarshalAs(UnmanagedType.Bool)]
[DllImport("user32.dll", SetLastError = true)]
private static extern bool PostMessage(IntPtr hWnd, uint msg, IntPtr wParam, IntPtr lParam);
[DllImport("User32.dll", SetLastError = true, CharSet = CharSet.Auto)]
static extern long GetWindowText(IntPtr hwnd, StringBuilder lpString, long cch);
// Activate an application window.
[DllImport("USER32.DLL")]
public static extern bool SetForegroundWindow(IntPtr hWnd);
[DllImport("user32")]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool EnumChildWindows(IntPtr window, EnumWindowProc callback, IntPtr i);
public static int disconnectValue = 0;

        public static void ClickButtonLabeledYes()
        {
            try
            {
                IntPtr focusWindow = FindWindow
                         ("SetFocus", "Cisco AnyConnect Secure Mobility Client");
                var windowCaption = FindWindowByCaption(IntPtr.Zero, 
                                     "Cisco AnyConnect Secure Mobility Client");
                if (windowCaption.ToString().Length >= 2)
                {
                    SetForegroundWindow(focusWindow);
                    EnumChildWindows(windowCaption, EnumChildWindowsCallback, IntPtr.Zero);
                }
            }
            catch (Exception e)
            {
                // new LogEntry(": " + e.ToString());
            }
        }

        public static bool EnumChildWindowsCallback(IntPtr handle, IntPtr pointer)
        {
            const uint WMLBUTTONDOWN = 0x0201;

            const uint WMLBUTTONUP = 0x0202;

            var sb = new StringBuilder(256);
            // Get the control's text.

            GetWindowCaption(handle, sb, 256);

            var text = sb.ToString();
            if (text.ToString().Equals("Connect", StringComparison.InvariantCultureIgnoreCase))
            {
                PostMessage(handle, WMLBUTTONDOWN, IntPtr.Zero, IntPtr.Zero);
                PostMessage(handle, WMLBUTTONUP, IntPtr.Zero, IntPtr.Zero);
            }
            else if (text.ToString().Equals
                       ("Disconnect", StringComparison.InvariantCultureIgnoreCase)) 
            {
                disconnectValue = 1;
            }

            return true;
        }

        public static void SecondWindowClick(string Password)
        {
            try
            {
                IntPtr focusWindow = FindWindow("SetFocus", "Cisco AnyConnect | 
                YOUR DOMAIN NAME"); // Enter your org domain name like shown on CISCO window Header 
                var windowCaption = FindWindowByCaption(IntPtr.Zero, "Cisco AnyConnect | 
                YOUR DOMAIN NAME"); // Enter your org domain name like shown on CISCO window Header 
                if (windowCaption.ToString().Length >= 2)
                {
                    SetForegroundWindow(focusWindow);
                    SendKeys.SendWait(Password);
                    EnumChildWindows(windowCaption, SecondWindowClickCallback, IntPtr.Zero);
                }
            }
            catch (Exception e)
            {
                // new LogEntry(": " + e.ToString());
            }
        }

        public static bool SecondWindowClickCallback(IntPtr handle, IntPtr pointer)
        {
            const uint WMLBUTTONDOWN = 0x0201;
            const uint WMLBUTTONUP = 0x0202;

            var sb = new StringBuilder(256);
            GetWindowCaption(handle, sb, 256);
            var text = sb.ToString();
            if (text.ToString().EndsWith("OK", StringComparison.InvariantCultureIgnoreCase))
            {
                PostMessage(handle, WMLBUTTONDOWN, IntPtr.Zero, IntPtr.Zero);
                PostMessage(handle, WMLBUTTONUP, IntPtr.Zero, IntPtr.Zero);
            }
            return true;
        }

        public static void ThirdWindowClick()
        {
            try
            {
                IntPtr focusWindow = FindWindow("SetFocus", "Cisco AnyConnect");
                var windowCaption = FindWindowByCaption(IntPtr.Zero, "Cisco AnyConnect");
                if (windowCaption.ToString().Length >= 2)
                {
                    SetForegroundWindow(focusWindow);
                    EnumChildWindows(windowCaption, ThirdWindowClickCallback, IntPtr.Zero);
                }
            }
            catch (Exception e)
            {
                // new LogEntry(": " + e.ToString());
            }
        }

        public static bool ThirdWindowClickCallback(IntPtr handle, IntPtr pointer)
        {
            const uint WMLBUTTONDOWN = 0x0201;
            const uint WMLBUTTONUP = 0x0202;

            var sb = new StringBuilder(256);
            GetWindowCaption(handle, sb, 256);
            var text = sb.ToString();
            if (text.ToString().EndsWith("Accept", StringComparison.InvariantCultureIgnoreCase))
            {
                PostMessage(handle, WMLBUTTONDOWN, IntPtr.Zero, IntPtr.Zero);
                PostMessage(handle, WMLBUTTONUP, IntPtr.Zero, IntPtr.Zero);
            }
            return true;
        }

}
'@

[Reflection.Assembly]::LoadWithPartialName("System")

[Reflection.Assembly]::LoadWithPartialName("System.Runtime.InteropServices")

[Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")

[Reflection.Assembly]::LoadFile("C:\Program Files 
 (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.0\mscorlib.dll") # Check the 
                                                      location library presence must and should.
 

$refs = @("System","System.Runtime.InteropServices","System.Windows.Forms")

Add-Type -TypeDefinition $pinvokes -ReferencedAssemblies $refs -IgnoreWarnings

Start-Sleep -s 7 # SET TIME interval based on your internet and RAM speed
[Program]::ClickButtonLabeledYes()

$testvarible = [Program]::disconnectValue

If ($testvarible  -eq '0') 
{
Start-Sleep -s 7  # SET TIME interval based on your internet and RAM speed
[program]::SecondWindowClick($Password)

Start-Sleep -s 7  # SET TIME interval based on your internet and RAM speed
[program]::ThirdWindowClick()

Start-Sleep -s 7 # SET TIME interval based on your internet and RAM speed
}
Else {
Start-Sleep -s 1
}
 cmdkey /generic:TERMSRV/$ServerIpAddress /user:$UserName /pass:$Password
 mstsc /v:$ServerIpAddress

}
catch
{

$ErrorMessage = $_.Exception.Message

$FailedItem = $_.Exception.ItemName

Write-Output($ErrorMessage)

Write-Output($FailedItem)
Start-Sleep -s 10
}

根据您的本地互联网和 RAM 速度设置时间间隔(例如,Start-Sleep -s 7)。

注意事项

  1. 系统开机后处于空闲状态时,只需运行脚本一次即可。
  2. 执行此脚本时,请不要打开任何窗口,这意味着不要更改正在执行的窗口的焦点。
  3. preferences.xml 文件在此位置是必需的:“C:\Users\输入您的本地机器名\AppData\Local\Cisco\Cisco AnyConnect Secure Mobility Client”。
    请确保该文件中包含 [<DefaultUser>您的用户名</DefaultUser>,<DefaultHostName>您的 VPN 地址 </DefaultHostName>] 这两个属性。
  4. 请确保首次保存您的思科登录用户名、VPN 地址和 MSTSC 登录 IP 和密码时,选中“记住我”复选框。

缺点

  1. 当您的 VPN 服务器密码更改时,它将无法工作。
  2. 当网络连接速度慢时,它将无法工作。
  3. 如果您删除本地机器上的思科系统缓存(临时文件),它将无法工作。
  4. 如果出现 MSTSC 警告弹出窗口,它将无法工作。(请确保您已选中“记住”复选框。)

注意

我对您的密码不负责。请保护您的本地机器,并单击一下即可运行您的脚本。如果脚本有任何问题,请告诉我,我会进行更正。

一键登录思科 AnyConnect 安全移动客户端 VPN - CodeProject - 代码之家
© . All rights reserved.