Jump to content

Executing a script on a remote machine


Recommended Posts

Yes, I know...there are a lot of solved topics about that. It's even in FAQ. Unfortunately, I spent almost two days to solve my problem or find other solution for the same task. After all, I still haven't found it.

Task is: Execute AutoIt script (e.g. simple MsgBox() compiled to *.exe) on remote computer at the same network


I decided to use script based on PsExec (PStools v.2.45) to achieve that. Unfortunately I works just partially.

I'm running two Win10 sessions:

  1. the first one where the main command is being initiated
  2. the second one where the main command has to be proceeded (Firewall's down)

Both of them are being logged as the same user with Admin rights.

I tried several complete scripts focused on "executing remotely", but they doesn't work for me and I have no clue why...  Basic commands executed through PsExec even WMI, like starting up notepad.exe or calc.exe works well:

RunWait("psexec \\PcName C:\Windows\System32\calc.exe", "", @SW_SHOW)

An executing of command above returns "0" (success) and proceed calc start immediately. 

An executing of following command takes approx. 15 sec. and returns "0" as well, however nothing happens.

RunWait("psexec \\PcName C:\Users\UserName\Desktop\TestRemote.exe", "", @SW_SHOW)

Permissions wouldn't be problem, following command works as well:

RunWait("psexec \\PcName -u Domain\UserName -p Pass C:\Windows\System32\calc.exe", "", @SW_SHOW)


I tried running it under "-i". No success. I guess it has something to do with -h parameter: 


This topic links to an adding new reg value and opening port 445:

RegWrite("HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\system", "LocalAccountTokenFilterPolicy", "REG_DWORD", "1")

I'm not an expert about Windows User Permissions or Rights and simple adding of key and opening the port 445 doesn't work.


Many thanks for any idea in advance!


p.s. sorry my grammar, I'm not an native English speaker 🙂 


Link to comment
Share on other sites

Is the script you trying to execute with PSEXEC already on the remote PC?  If not, it could be an issue with File and Print Sharing, as PSEXEC tries to copy the file.  Try running the following on the remote PC as Admin, and then try again.  

REM Enable File and Print Setting for public, private, and domain
netsh advfirewall firewall set rule group="File and Printer Sharing" new enable=Yes




Link to comment
Share on other sites

I am not a big fan of PsExec

I had to do something similar recently but made it so that the helpdesk could run this as a simple CMD file.

Easy enough to port this technique to autoit.


pushd %~dp0
set /p id=Enter PCN:
xcopy ospp.vbs \\%id%\c$\automate
xcopy ospprearm.exe \\%id%\c$\automate
xcopy reactivate_office.bat \\%id%\c$\automate
SCHTASKS /s %id% /RU "SYSTEM" /create /tn "Rearm Office" /tr "C:\automate\reactivate_office.bat" /sc ONCE /sd 01/01/1910 /st 00:00
SCHTASKS /s %id% /run /TN "Rearm Office"

The thing to take to mind is user sessions, if you want a msgbox to run and show on the user session it must execute as that user, this can be done.  Also look up something like MDT's ServiceUI just a simple script that detects what session a process is running and will display to that session even if executed under a different context. 

Link to comment
Share on other sites

I'm using this for some reports from windows task scheduler

#include <Timers.au3>
;~ #include <ScreenCapture.au3>
;for _WinAPI_FileInUse
;~ #include <WinAPIFiles.au3>
;~ #include <WinAPIProc.au3>

Opt('WinWaitDelay', 250)
Opt('WinDetectHiddenText', 1)
Opt('MouseCoordMode', 0)
Opt("WinTitleMatchMode", 1) ;1=start, 2=subStr, 3=exact, 4=advanced, -1 to -4=Nocase

Opt("MustDeclareVars", 1)
;Be sure to register this to reenable power-saving, screensaver, etc
;~ OnAutoItExitRegister("OnAutoItExit")

Global $sms = True

;Not used finally
;Disable ScreenSaver and other windows sleep features. Save the current power-savings 'execution state'
;Danyfirex, October, 2018
;You can use _WinAPI_SetThreadExecutionState.
;Remarks say: This function does not stop the screen saver from executing.
;But actually You could do this to prevent screen saver execution.
;Global $Power = _WinAPI_SetThreadExecutionState(BitOR($ES_DISPLAY_REQUIRED, $ES_CONTINUOUS))

;I'm using the Window Task Scheduler, usually from suspended mode: thinking an initial pause could help
;~ Send("{DOWN}")
;~ Sleep(20000)
;~ MouseMove(10, 100)

;Check if user is inactive
;How to get system idle time, or if screensaver is active?
;The _Timer_GetIdleTime() function uses GetLastInputInfo from user32.dll.
Global $Quit, $iLimit = 30 ; idle limit in seconds  (5 segundos)
If _Timer_GetIdleTime() > $iLimit * 1000 Then
   ;MsgBox(0, "", "Continue >>")
   AdlibRegister("_CheckIdleTime", 1000)
   While 1 ;use infinite loop since ExitLoop will get called
      If $Quit = True Then
   ;Outra forma
   ;Until $Quit = True

If Not WinExists("10._._.__ - Conexión a Escritorio remoto") Then
   ;RunWait('"' & @ComSpec & '" /c MSTSC.EXE C:/yourfile.rdp', '', @SW_HIDE)
   Run("C:\windows\system32\mstsc.exe /v:" & "10._._.__")
   ;RunWait("C:\windows\system32\mstsc.exe /v:" & "10._._.__")

   ;~ ;Wait 90 seconds for the window to appear.
   Local $hWnd = WinWait("10._._.__ - Conexión a Escritorio remoto", "", 90)
   ;WinWaitActive($hWnd, "", 60)
   Local $hWnd = WinActivate("10._._.__ - Conexión a Escritorio remoto")
   WinWaitActive($hWnd, "", 90)
   WinSetState($hWnd, "", @SW_MAXIMIZE)

;Test if the window is now activated
;You can use the WinActive() function to check if WinActivate() succeeded.
If WinActive($hWnd, "") Then
   ;WinSetState($hWnd, "", @SW_MAXIMIZE)
   ;MsgBox(0, "", "Window NOW active")

   Global $Day = @MDAY
   Global $sFilePath = @DesktopDir & "\switch"
   ;Global $sFilePath3 = @DesktopDir & "\snapshots\"

   Global $sCoords[4] = [10, 45, 800, 600]
;~    DirCreate($sFilePath3)


   ;execute windows command
   Send ("#r")

   Global $Parameter1 = "FirstParameter"
   Global $Parameter2 = "SecondParameter"

   Local $aArray = StringSplit("C:\Users\UserName\Desktop\TestRemote.exe " & $Parameter1 & " " & $Parameter2, "")
   For $i = 1 To $aArray[0]

   If FileExists($sFilePath) Then
      Global $mouse, $offset = 100, $count = 0

      While 1
         If Not WinExists("10._._.__ - Conexión a Escritorio remoto") Then
            If FileExists($sFilePath) Then
               ;~ If WinActive($hWnd, "") Then
               ;~    $mouse = MouseGetPos()
               ;~    MouseMove($mouse[0] + $offset, $mouse[1] + $offset)
               ;~    $offset = -$offset
               ;~    Sleep(100)
               ;~    Send("{UP}")
               ;~    Sleep(100)
               ;~    ;$count += 1
               ;~    ;If $count = 5 Then
               ;~     ;$count = 0
               ;~     ;_ScreenCapture_Capture($sFilePath3 & $Day & @HOUR & @MIN & ".png" , $sCoords[0], $sCoords[1], $sCoords[2], $sCoords[3], False)
               ;~    ;EndIf
               ;~ EndIf

;~    ;File not locked
;~    Global $iFileExists
;~    For $j = 0 To 60
;~       $iFileExists = FileExists($sFilePath2)
;~       If $iFileExists Then
;~          While _WinAPI_FileInUse($sFilePath2)
;~             Sleep(1000)
;~          WEnd
;~          ExitLoop
;~       Else
;~          Sleep(1000)
;~       EndIf
;~    Next

;~    If FileExists($sFilePath2) Then
;~       If $sms Then
            ;~ #include "HTTP.au3"
;~          ;Global $sResp = _HTTP_Post("http://api.mensatek.com/sms/v5/enviar.php", "Correo=" & URLEncode("MyUserName") & "&Passwd=12345&Remitente=MyName&Destinatarios=" & URLEncode("34123456789") & "&Mensaje=" & URLEncode("OK") & "&Resp=JSON")

;~          ;Open the file for write access.
;~          Global $hFileOpen = FileOpen(@DesktopDir & "\Resp_mensatek.txt", 2)
;~          ;If $hFileOpen = -1 Then
;~           ;MsgBox(0, "", "An error occurred when reading/writing the file.")
;~          ;EndIf
;~          ;Write some data.
;~          FileWrite($hFileOpen, $sResp)
;~          ;Close the handle returned by FileOpen.
;~          FileClose($hFileOpen)
;~       EndIf
;~    EndIf
      ;Open the file for write access.
      Global $hFileOpen = FileOpen(@DesktopDir & "\ERROR.txt", 2)
      ;If $hFileOpen = -1 Then
       ;MsgBox(0, "", "An error occurred when reading/writing the file.")
      ;Write some data.
      FileWrite($hFileOpen, "ERROR: ___")
      ;Close the handle returned by FileOpen.
   ;MsgBox(0, "Error", "Window not active")
   ;Local $hActive = WinGetHandle("[active]")
   ;Local $sTitle = WinGetTitle("[active]")
   ;MsgBox(0, "Error", $sTitle)

   ;Open the file for write access.
   Global $hFileOpen = FileOpen(@DesktopDir & "\ERROR.txt", 2)
   ;If $hFileOpen = -1 Then
    ;MsgBox(0, "", "An error occurred when reading/writing the file.")
   ;Write some data.
   FileWrite($hFileOpen, "ERROR: _____")
   ;Close the handle returned by FileOpen.

Func _CheckIdleTime()
   If _Timer_GetIdleTime() > $iLimit * 1000 Then
      ;AdLib functions don't run while a blocking function is shown e.g. MsgBox, InputBox, WinWait, WinWaitClose etc.
      ;MsgBox(16, "Timeout", "You haven't done anything in " & $iLimit & " seconds...  Get busy!")
      $Quit = True

;~ Func OnAutoItExit()
;~    ;_WinAPI_SetThreadExecutionState($Power)
;~    ;back to normal windows behavior
;~    _WinAPI_SetThreadExecutionState($ES_CONTINUOUS)
;~ EndFunc


Link to comment
Share on other sites

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

  • Recently Browsing   0 members

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