Jump to content
woody-cz

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

MsgBox(64,"Info","Success!")

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: 

image.png.0d3ee47a4924f83408d7db5f46d4e907.png

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 🙂 

Remote_test.reg

Share this post


Link to post
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

 

Adam

 

Share this post


Link to post
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"
popd

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. 

Share this post


Link to post
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'
;https://www.autoitscript.com/forum/topic/196067-prevent-screensaver-to-turn-off-monitor-spi_setblocksendinputresets/
;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))
;BigDaddyO
;Global $Power = _WinAPI_SetThreadExecutionState(BitOR($ES_CONTINUOUS, $ES_DISPLAY_REQUIRED, $ES_SYSTEM_REQUIRED))
;mLipok
;~ Global $Power = _WinAPI_SetThreadExecutionState(BitOR($ES_DISPLAY_REQUIRED, $ES_CONTINUOUS, $ES_SYSTEM_REQUIRED, $ES_AWAYMODE_REQUIRED))

;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
;https://stackoverflow.com/questions/3867584/autoit-how-to-get-system-idle-time-or-if-screensaver-is-active
;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 >>")
Else
   AdlibRegister("_CheckIdleTime", 1000)
   While 1 ;use infinite loop since ExitLoop will get called
      If $Quit = True Then
         ;ConsoleWrite("Fin")
         ExitLoop
      EndIf
      Sleep(1000)
   WEnd
   ;Outra forma
   ;Do
      ;Sleep(1000)
   ;Until $Quit = True
EndIf

If Not WinExists("10._._.__ - Conexión a Escritorio remoto") Then
   ;https://www.autoitscript.com/forum/topic/97501-auto-mstsc/
   ;RunWait('"' & @ComSpec & '" /c MSTSC.EXE C:/yourfile.rdp', '', @SW_HIDE)
   ;http://support.microsoft.com/kb/941641
   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)
   ;WinActivate($hWnd)
   ;WinWaitActive($hWnd, "", 60)
Else
   Local $hWnd = WinActivate("10._._.__ - Conexión a Escritorio remoto")
   WinWaitActive($hWnd, "", 90)
   WinSetState($hWnd, "", @SW_MAXIMIZE)
EndIf
Sleep(5000)

;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)

   FileDelete($sFilePath)

   Sleep(25000)
   ;execute windows command
   Send ("#r")
   Sleep(1000)

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

   Local $aArray = StringSplit("C:\Users\UserName\Desktop\TestRemote.exe " & $Parameter1 & " " & $Parameter2, "")
   Sleep(100)
   For $i = 1 To $aArray[0]
      Send($aArray[$i])
      Sleep(100)
   Next
   Sleep(1000)
   Send("{ENTER}")

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

      While 1
         If Not WinExists("10._._.__ - Conexión a Escritorio remoto") Then
            ExitLoop
         Else
            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
               Sleep(25000)
            Else
               ExitLoop
            EndIf
         EndIf
      WEnd

;~    ;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
            ;https://www.autoitscript.com/forum/topic/187718-http-lib-get-post-and-upload/
            ;https://github.com/jesobreira/HTTP.au3
            ;~ #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
   Else
      ;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.")
      ;EndIf
      ;Write some data.
      FileWrite($hFileOpen, "ERROR: ___")
      ;Close the handle returned by FileOpen.
      FileClose($hFileOpen)
   EndIf
Else
   ;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.")
   ;EndIf
   ;Write some data.
   FileWrite($hFileOpen, "ERROR: _____")
   ;Close the handle returned by FileOpen.
   FileClose($hFileOpen)
EndIf

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
      AdlibUnRegister("_CheckIdleTime")
   EndIf
EndFunc

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

 

Share this post


Link to post
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

×
×
  • Create New...