Jump to content

LastPass Helper for Remote Desktop Sessions


pboom
 Share

Recommended Posts

The following is an AutoIt application designed to allow LastPass for Applications to launch and log into Remote Desktop Session also known as RDP or mstc.exe.

LastPass is a cloud based password manager, their clients support the widest range of browsers and OS's out there. All clients sync the data well, while maintaining a local catch for when you are offline. For premium users, (which I have been for 4 years) they have available Lastpass for Application which is designed for Applications verus Websites. Unfortunately it does not work with the Windows Remote Desktop Client. This is where the following script comes in.

LastPass for applications launches RDPlp.EXE passing it the server name, user name, and password. RDPlp.EXE then launches the Remote Desktop session using the information pass to it by LastPass. RDPlp.EXE also insures full screen sessions are moved to the second monitor if it exist.

Why do this when RDP settings files can be used as shortcuts that will launch a Remote Desktop Session?

1) I have a lot of servers I need to connect to on a periodic bases, the corresponding collection of short cuts would be hard to manage

2) RDP settings files with saved passwords only work on the computer they where created for. With this utility and LastPass's cloud approach all my remote Desktop entries work on any of my computers that have LastPass for Application and this LastPass Helper install. That turns out to be any computer I use.

3) When I do a routine password change LastPass offers to update all my password entries for the same domain/username. In this way all my remote desktop connections get updated as well. If I used a collection of RDP setting files I would need to update each separately.

Further documentation can be found in the source code and the help screen created by RDPlp.exe

The attached ZIp contains the source, compiled EXE and two sample RDP settings files.

 

This application has been tested on Win7, Win8, Win10. It was marginally written to work on XP as well but since the version 2 rewrite this has not been tested, I have no XP development machines anymore. It works with Remote Desktop sessions on all versions of Server 2003, 2008, 2012 and 2014.

Below is the source for those who want to take a peek.

I hope someone else finds this as useful as I have.

As of 2020 LogMeIn has depreciated LastPass for Applications so to regain some storage space on the Forum I have removed the ZIP file with this code.

#Region ;**** Directives created by AutoIt3Wrapper_GUI ****
#AutoIt3Wrapper_icon=RDPlp_icon.ico
#AutoIt3Wrapper_Res_Description=Launch RDP from LastPass
#AutoIt3Wrapper_Res_Fileversion=2.2.0.3
#AutoIt3Wrapper_Res_FileVersion_AutoIncrement=P
#AutoIt3Wrapper_Res_ProductVersion=2.2
://////=__=.
://////=__=
://////=__=
#AutoIt3Wrapper_Res_LegalCopyright=© Copyright Paul Verboom 2015
#AutoIt3Wrapper_Res_Comment=Launch Remote Desktop Session from LastPass for Applications
#EndRegion ;**** Directives created by AutoIt3Wrapper_GUI ****

#include <Array.au3>
#include <File.au3>
#include <MsgBoxConstants.au3>
#include <WinAPIGdi.au3>
#include <WindowsConstants.au3>


#comments-start
Revisions
Ver 2.0     - First rewrite that edits RPD settings file directly
Ver 2.1     - Added labels to field in training window, moved splash off to pre pixel count for old login style login window
Ver 2.2     - Added check for Windows 10 RDP credentials screen
#Comments-end


;RDPlp
#comments-start
LastPast Helper to Launch RDP session.
The formate of the command is straight forward.
Lastpast for applications is used to launch this program.
If the program is launched with no parameters a help screen
is displayed that explains how to set up an entry in last past to use this program.

RDPlp Server UserName Password [RDP Settings file]

If Domain needs to be specified as part of the user name
place it in front of User name in format domain\user

A RDP settings file is required. This program will edit it and use it to make the connection.
By default a settings file with the same name as this executable will be used,
switching the extension from .EXE to .RDP
The executable can be renamed and the default RDP settings file will also change
OR a alternate RDP file can be specified as the 4th parameter

A RDP settings file can be created by launching Remote Desktop Connection usually
located under Start->Programs->Accessories.
Click options in the bottom right corner. Use the Save Connection Settings that
is now availble to save the file as RDPlp.RDP
You may wish to set other settings such as screen size, bandwidth etc. before
saving the connect file. This program will add the server and username so the same
connection file can be used for numerous servers and logins.
Do not check Allow me to save credentials as this program will enter the password each time.
You may wish to change the "If Server authentication fails" setting on the Advanced tab so
these warning do not interrupt the login process.

The Remote Desktop Connection file only allows standard screen sizes be set however the
RDP file can be edited directly in notepad and these settings made to any arbitrary value
look for the entries where X is the screen width and Y is it's height
    desktopwidth:i:X
    desktopheight:i:Y
This is very useful when doing remoted on windows 8 tablets with limited screen size.

This script will edit the specified RDP settings file adding the Server and UserName
If will also adjust the window position to one of the following conditions
    - Full Screen RDP session and 2 or more monitors RDP session moved to 2nd monitor on right
    - Full Screen RDp session and 1 window move window to primary monitor
    - Not Full Screen adjust window size to be big enough to display RDP session

It will then launch the RDP file watching for one of the following windows
1) Windows Security
2) RDPlp - SERVERNAME - Remote Desktop Connection
    (where SERVERNAME is the address of the server being connected to)
3) Remote Desktop Connection with OK as part of the visable text
    (this indicates an error in making the connection)

RDP Settings for Remote Desktop Services in Windows Server 2008 R2
can be found at
https://technet.microsoft.com/en-us/library/ff393699%28v=ws.10%29.aspx
#comments-end


;RDP command line options
#comments-start
---------------------------
Remote Desktop Connection Usage
---------------------------
MSTSC [<connection file>] [/v:<server[:port]>] [/admin] [/f[ullscreen]]
[/w:<width> /h:<height>] [/public] | [/span] [/edit "connection file"] [/migrate]
"connection file" -- Specifies the name of an .rdp file for the connection.
/v:<server[:port]> -- Specifies the remote computer to which you want to connect.
/admin -- Connects you to the session for administering a server.
/f -- Starts Remote Desktop in full-screen mode.
/w:<width> -- Specifies the width of the Remote Desktop window.
/h:<height> -- Specifies the height of the Remote Desktop window.
/public -- Runs Remote Desktop in public mode.
/span -- Matches the remote desktop width and height with the local
        virtual desktop, spanning across multiple monitors if necessary. To span
        across monitors, the monitors must all have the same height and be aligned
        vertically.
/edit -- Opens the specified .rdp connection file for editing.
#comments-end

Local $Server
Local $User
Local $Password

;Debug variable set to 2 or higher to run from devolpment enviroment
$Debug = 0

;! for debugging
If $Debug > 1 Then
    $Server = ""
    $User = ""
    $Password = ""
EndIf

;Help screen with fields to train lastPass
;a simple dialog to capture 3 values
If ($CmdLine[0] < 3 or $CmdLine[0] > 5) and $Debug = 0 Then
    #include <EditConstants.au3>
    #include <GUIConstantsEx.au3>
    #include <StaticConstants.au3>
    #include <WindowsConstants.au3>
    $Form1_1 = GUICreate("RDPlp Ver 2.0", 480, 550, 341, 203)
    $Label0 = GUICtrlCreateLabel("LastPass Training window", 180, 16, 127, 17)
    $Label1 = GUICtrlCreateLabel("Server", 85, 50, 217, 21)
    $Input1 = GUICtrlCreateInput("Server", 124, 48, 217, 21)
    $Label2 = GUICtrlCreateLabel("User", 90, 90, 217, 21)
    $Input2 = GUICtrlCreateInput("User", 124, 88, 217, 21)
    $Label3 = GUICtrlCreateLabel("Password", 70, 130, 217, 21)
    $Input3 = GUICtrlCreateInput("Password", 124, 128, 217, 21)
    $Button1 = GUICtrlCreateButton("Exit", 164, 160, 145, 33)
    $Button2 = GUICtrlCreateButton("Copy to clipboard", 200, 473, 120, 17)
    $T1 = GUICtrlCreateLabel("RDPlp allows LastPass for Applications to Launch Remote Desktop sessions.",20,210,400,17)
    $T2 = GUICtrlCreateLabel("Use this help screen to add a Remote Desktop session as an Application to ",20,230,500,17)
    $T3 = GUICtrlCreateLabel("LastPass for Applications. ",20,245,500,17)
    $T4 = GUICtrlCreateLabel("- Use the Add Application option in Last Pass for Applications.",20,265,400,17)
    $T5 = GUICtrlCreateLabel("- Find this window.",20,280,400,17)
    $T6 = GUICtrlCreateLabel("- Click Next.",20,295,400,17)
    $T7 = GUICtrlCreateLabel("- Edit The Name to reflect the actual server being connected to.",20,310,400,17)
    $T8 = GUICtrlCreateLabel("- Edit the 3 Fields as indicated.",20,325,400,17)
    $T9 = GUICtrlCreateLabel("- Click OK.",20,340,400,17)
    $T10 = GUICtrlCreateLabel("If you need to specify a domain use this format in the User field;",20,360,400,17)
    $T11 = GUICtrlCreateLabel("domain\username",40,375,400,17)
    $T12 = GUICtrlCreateLabel("Be sure to change the Password field to the password type so it is hidden by default.",20,390,500,17)
    $T13 = GUICtrlCreateLabel("The following password will cause the program to not do the login;",20,405,500,17)
    $T14 = GUICtrlCreateLabel("pause ",40,420,500,17)
    $T15 = GUICtrlCreateLabel("Once the application is added you will need to edit it.",20,440,500,17)
    $T16 = GUICtrlCreateLabel("Adding the following to the end of the application entry.",20,455,500,17)
    $T17 = GUICtrlCreateLabel("%field0% %field1% %field2%",40,475,150,17)
    $T18 = GUICtrlCreateLabel("RDPlp requires a RDP connection settings file of the same name be located in the same",20,495,500,17)
    $T19 = GUICtrlCreateLabel("folder as RDPlp.EXE This connect file is used to setup session values, screen size etc.",20,510,500,17)
    $T20 = GUICtrlCreateLabel("OR a different RDP connection file can be specified as the 4th parameter on the command line.",20,525,500,17)
    GUISetState(@SW_SHOW)

    While 1
        $nMsg = GUIGetMsg()
        Switch $nMsg
            Case $GUI_EVENT_CLOSE
                Exit
            Case $Button1
                Exit
            Case $Button2
                IF $Debug Then
                    ConsoleWrite("Placed %field0% %field1% %field2% into clipboard")
                EndIf
                ClipPut(" %field0% %field1% %field2%")
        EndSwitch
    WEnd

EndIf

;Place Splash Window up so User Knows Auto Login is running
;Options used in 3rd from last parameter
;$DLG_NOTITLE = 1
;$DLG_MOVEABLE = 16
SplashTextOn("","Starting Remote Desktop Login", 400, 50,@DesktopWidth/2 - 200, @DesktopHeight/2 -150, 17, "", 18)

If $Debug = 0 Then
    If $CmdLine[0] > 2 Then
        $Server = $CmdLine[1]
        $User = $CmdLine[2]
        $Password = $CmdLine[3]
    ENDIF
EndIf

If $Password = "pause" Then
    MsgBox(0,"RDPlp","Password = pause. Login will not be completed")
    $Login = "N"
Else
    $Login = "Y"
EndIf

IF $Debug Then
    ConsoleWrite("@WorkingDir = "&@WorkingDir&@CRLF)
    ConsoleWrite("@WindowsDir = "&@WindowsDir&@CRLF)
    ConsoleWrite("Server = -"&$Server&"-"&@CRLF)
    ConsoleWrite("User = -"&$User&"-"&@CRLF)
    ConsoleWrite("Password = -"&$Password&"-"&@CRLF)
EndIf

;--------------------------
;Get RDP settings file name
;--------------------------
$RDPSettings = StringReplace(@ScriptName,".exe",".RDP",1)       ;same as name of executable
$RDPSettings = StringReplace($RDPSettings,".au3",".RDP",1)      ;or script name
If $CmdLine[0] >= 4  Then                                       ;unless it is specified as 4th paramter
    $RDPSettings = $CmdLine[4]
    IF StringUpper(StringRight($RDPSettings ,4)) <> ".RDP" Then
        $RDPSettings = $RDPSettings & ".RDP"
    EndIf
EndIf
IF $Debug Then
    ConsoleWrite("RDP Settings file: "&$RDPSettings&@CRLF)
EndIf
IF NOT StringInStr($RDPSettings,"\") Then                       ;add path to file name if not already there
    $FullRDPSettings = @WorkingDir & "\" & $RDPSettings
EndIf
IF FileExists($FullRDPSettings) = 0 Then                        ;Should be in working directory of script
    MsgBox(0,"RDPlp","RDP Settings file: " & $FullRDPSettings & " not found." & @CRLF & "Should be located in same folder as RDPlp.EXE")
    SplashOff()                                                 ;turn off Auto Login Starting message
    Exit
EndIf

;-------------------------------------------
;Check for extended desktop with 2nd display
;-------------------------------------------
Local $SecondMonitor = False
Const $monitor_count = _WinAPI_GetSystemMetrics($SM_CMONITORS)
IF $Debug Then
    ConsoleWrite("Number of monitors = " & $monitor_count & @CRLF)
EndIf
IF $monitor_count > 1 Then
    Const $aMonitor = _WinAPI_EnumDisplayMonitors()
    If NOT @error Then
        If $aMonitor[0][0] > 1 Then
            $SecondMonitor = True
            IF $Debug Then
                ConsoleWrite("Extended Mode" & @CRLF)
            EndIf
        EndIf
    EndIf
EndIf

;----------------------------
;Edit the RDP connection file
;----------------------------
Local $aRDP                                                     ;Array containing RDP settings file
Local $i                                                        ;index used to process array
Local $line                                                     ;Line currectly being processed
Local $AddServer = True                                         ;Server added to RDP settings file flag
Local $AddUser = True                                           ;User added to RDP settings file flag
Local $Width = 0                                                ;Width of remote desktop session
Local $Height = 0                                               ;Height of Remote Desktop session
Local $Brder = 100                                              ;number of pixels added to window sizes to account for boarders
Local $OffSt = 100                                              ;How far out of top left corner to place window
Local $Move1st = False                                          ;Flag to move RDP swindow to 1st screen
Local $Move2nd = False                                          ;Flag to move RDP swindow to 2nd screen
$aRDP = FileReadToArray($FullRDPSettings)                       ;read the RDP file to a array one line per element

FOR $i = 0 to ubound($aRDP)-1                                   ;look through file for existing server and user entries
    IF StringInStr($aRDP[$i],"full address:s:") Then            ;replacing them if found and set flag so we know
        $aRDP[$i] = "full address:s:" & $Server                 ;change has been done
        $AddServer = False
    EndIf
    IF StringInStr($aRDP[$i],"username:s:") Then
        $aRDP[$i] = "username:s:" & $User
        $AddUser = False
    EndIf
    IF StringInStr($aRDP[$i],"screen mode id:i:2") Then         ;If we are in full screen mode
        IF $SecondMonitor Then                                  ; and have Second Monitor then
            $Move2nd = True                                     ; set flag to alter the X position in RDP file to move to 2nd screen
        Else
            $Move1st = True                                     ;If no second monitor set flag to alter X position so
        EndIf                                                   ;window is on 1sst monitor
    EndIf
    IF StringInStr($aRDP[$i],"desktopwidth:i:") Then            ;Find the width and heigh of the Remote desktop window
        $atemp = StringSplit($aRDP[$i],":")
        IF $atemp[0] = 3 Then
            $Width = Number($atemp[3])
        EndIf
    EndIf
    IF StringInStr($aRDP[$i],"desktopheight:i:") Then
        $aTemp = StringSplit($aRDP[$i],":")
        IF $aTemp[0] = 3 Then
            $Height = Number($aTemp[3])
        EndIf
        If $Debug Then
            ConsoleWrite("Remote Desktop Size: " & STRING($Width) & " x " & STRING($Height) & @CRLF)
        EndIf
    EndIf

    IF StringInStr($aRDP[$i],"winposstr:s:") Then               ;Rewrite window position and size
        IF $Width = 0 Then                                      ;Set default Remote Desktop Size
            $Width = 1024
        EndIf
        IF $Height = 0 Then
            $Height = 768
        EndIf

        IF $Move1st Then                                        ;move window position so RDP window is on 1st monitor
            $aRDP[$i] = "winposstr:s:0,1," & STRING($OffSt) & "," & STRING($OffSt) & "," & STRING($Width + $OffSt + $Brder) & "," & STRING($Height + $OffSt + $Brder)
        EndIf

        IF $Move2nd Then                                        ;move window position so RDP window is on 2nd monitor
            $aRDP[$i] = "winposstr:s:0,1," & String(@DesktopWidth + $OffSt) & "," & STRING($OffSt) & "," & String(@DesktopWidth + $Width + $OffSt + $Brder) & "," & STRING($Height + $OffSt + $Brder)
        EndIf

        IF (NOT $Move1st) AND (NOT $Move2nd) THEN               ;not moving window therfore not full screen
            IF @DesktopWidth > $Width OR @DesktopHeight > $Height Then
                $Width = @DesktopWidth - $Brder - $OffSt        ;size of RDP window is larger then current screen
                $Height = @DesktopHeight - $Brder - $OffSt      ;therefore make new size based on screen size
            EndIf
                                                                ;write out window in the corrected size
            $aRDP[$i] = "winposstr:s:0,1," & STRING($OffSt) & "," & STRING($OffSt) & "," & STRING($Width + $OffSt + $Brder) & "," & STRING($Height + $OffSt + $Brder)
        EndIf
    EndIf
Next
IF $AddServer Then                                              ;if server and user entries where not found add them
    _ArrayAdd($aRDP,"full address:s:" & $Server)                ;to the array now
EndIf
IF $AddUser Then
    _ArrayAdd($aRDP,"username:s:" & $User)
EndIf
IF $Debug > 0 Then
    _ArrayDisplay($aRDP,"Altered Contents of RDP file")
EndIf
_FileWriteFromArray($FullRDPSettings,$aRDP)

;----------------------------
;Launch the RDP settings file
;----------------------------
ShellExecute($FullRDPSettings)

;Security warnings are not processed by this script
;Win7 and above versions of RDp have options to remember the bypass selected answers
;uses those options


;--------------------
;Now provide password
;--------------------
#comments-start
Some version of RDP such as the one with Windows 7 will do login on local machine if
server is 2008 and above so look for window titles
Windows Security
or
the Login is done on the remote machine so also look for the
title of the Remote desktop session in form
RDPlp - SERVERNAME - Remote Desktop Connection (Windows 7)
or
RDPlp - SERVERNAME - Remote Desktop (Windows XP)
where RDPlp is the name of the RDP settings file being used
where SERVERNAME is the address of the server being connected to
or
The connection will fail and a Dialog will be displayed
Titled "Remote Desktop Connection"
Containing the text "can't find the computer" (XP and Win7) not (Win8)
Containing the text "PK" (XP, Win7 & Win8)
#Comments-end

;Text match mode for window titles
AutoItSetOption("WinTextMatchMode",2)       ;1=complete, 2=quick

;determine title of created Remote Desktop Window has Server name in it etc.
;RDPlp - DC-SV-MUSE-temp - Remote Desktop Connection
$RmDSkWin = StringLeft($RDPSettings, StringLen($RDPSettings)-4) & " - " & $Server & " - Remote Desktop"
IF $Debug Then
    ConsoleWrite("For server < 2008 or XP will be looking for Window Title"&@CRLF)
    ConsoleWrite($RmDSkWin&@CRLF)
EndIf

;Some  versions of the RDP client (Windows 7) add word connection to the title
;So do match on leading characters only
AutoItSetOption("WinTitleMatchMode",1)      ;1=start, 2=subStr, 3=exact, 4=advanced, -1 to -4=Nocase

Local $hTimer = TimerInit()                                     ;Starting point for timer
While TimerDiff($hTimer) < (1000 * 45)                          ;Total wait 45 seconds in Milliseconds
                                                                ;Wait for Windows Security Login Screen
                                                                ; OR
                                                                ;Remote Desktop Connection where login takes
                                                                ;Place on remote system
                                                                ; OR
                                                                ;Can't connect error message

    ;See if Windows 10 Security window exist
    IF WinExists("[TITLE:Windows Security; CLASS:Credential Dialog Xaml Host]","") Then
        If $Debug Then
            ConsoleWrite("Windows 10 RDP login  was found"&@CRLF)
        EndIf

        ;Do we do actual login
        If $Login = "Y" Then

            IF $Debug Then
                ConsoleWrite("Blind Typing Password" & @CRLF)
            EndIf
            sleep(750)
            WinActivate("Windows Security")
            ;This can be done by direct manipulation of the controls by AutoIt
            ;BUT the control names have changed between WinXP/Win7 and Win8
            ;Blind entry of password works regardless of OS
            Send($Password,1)
            Send("{ENTER}")
        EndIf
        ;We have done all we set out to do so exit
        SplashOff()                                                 ;turn off Auto Login Starting message
        Exit
    EndIf

    ;See if Windows 7 Security window exist
    IF WinExists("Windows Security","Remember my credentials") Then
        If $Debug Then
            ConsoleWrite("Windows 7 RDP login  was found"&@CRLF)
        EndIf

        ;Do we do actual login
        If $Login = "Y" Then

            IF $Debug Then
                ConsoleWrite("Blind Typing Password" & @CRLF)
            EndIf
            sleep(750)
            WinActivate("Windows Security")
            ;This can be done by direct manipulation of the controls by AutoIt
            ;BUT the control names have changed between WinXP/Win7 and Win8
            ;Blind entry of password works regardless of OS
            Send($Password,1)
            Send("{ENTER}")
        EndIf
        ;We have done all we set out to do so exit
        SplashOff()                                                 ;turn off Auto Login Starting message
        Exit
    EndIf

    ;See if remote Desktop Window to open
    IF WinExists($RmDSkWin) Then
        IF $Debug Then
            ConsoleWrite("Main Remote Desktop Window was found"&@CRLF)
        EndIf

        ;Activate the Window
        WinActivate($RmDSkWin)
        ;WinSetState($RmDSkWin,"",@SW_MAXIMIZE)

        SplashOff()                                                 ;turn off Splash so it doesn't mess up pixel check sum

        ;get checksum of side of window and center.
        ;they need to be different which indicate login window has been generated
        Local $aPos = WinGetPos($RmDSkWin)
        Local $ChkXside = $aPos[0] + 100
        Local $ChkXcent = $aPos[0] + ($aPos[2] /2)
        Local $ChkY = $aPos[1] + ($aPos[3] /2  )
        Local $ChkSumSide = PixelChecksum($ChkXside,$ChkY,$ChkXside+56,$ChkY+56)
        Local $ChkSumCent = PixelChecksum($ChkXcent,$ChkY,$ChkXcent+56,$ChkY+56)
        IF $Debug Then
            ConsoleWrite("Check Sum Pixels Side of RDP window: "&$ChkSumSide&@CRLF)
            ConsoleWrite("Check Sum Pixels Center of RDP Window: "&$ChkSumCent&@CRLF)
        EndIf

        ;only proceed if something(login in window) is in center of window
        IF $ChkSumCent <> $ChkSumSide Then

            ;Do we do actual login
            If $Login = "Y" Then

                ;Type in password
                IF $Debug Then
                    ConsoleWrite("Blind Typing Password" & @CRLF)
                EndIf
                Send($Password,1)
                Send("{ENTER}")

            EndIf
            ;We have done all we set out to do so exit
            Exit
        Else
            IF $Debug Then
                ConsoleWrite("Login dialog not ready yet" & @CRLF)
            EndIf
        EndIf
    EndIf

    ;Does Failed connect dialog exist
;   IF WinWait("Remote Desktop Connection","can't find the computer",1) <> 0 Then
    IF WinExists("Remote Desktop Connection","OK") Then
        IF $Debug Then
            ConsoleWrite("Connection fail dialog found exiting"&@CRLF)
        EndIf
        ;nothing more we can do so let's abort
        SplashOff()                                             ;turn off Auto Login Starting message
        Exit
    EndIf

Wend
MsgBox(0,"RDPlp","No Login Windows seen after wait.")
;We are finished
Exit

 

Edited by pboom
Lastpass for Applictaions is no longer available removed ZIP file
Link to comment
Share on other sites

  • 2 years later...
  • 3 months later...

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...