Commit dcbdb0e7 authored by Ivan Maslov's avatar Ivan Maslov

# Fix in RobotRDPActive (for production run)

parent bc562453
......@@ -63,7 +63,7 @@ def RenderRobotRDPActive(inGlobalConfiguration):
################################
#Session state
lItemSessionState='<span style=\"color:red\">Disconnected</span>'
if lItem.get("FlagSessionIsActive",False):
if lItem.get("SessionIsWindowExistBool",False):
lItemSessionState='<span style=\"color:green\">Connected</span>'
lResultDict["BodyKeyValueList"].append({"Key":f"[{str(lRDPListIndex)}]{lLabelSessionFullScreen}{lLabelIsIgnored}{lItem.get('Host','localhost')}:{lItem.get('Port','--')}","Value":f"{lItem.get('Login','--')}, {lItem.get('SessionHex','--')}, State {lItemSessionState}, {lSetFullScreenA}, {lIgnoreIndexListLink}"})
lRDPListIndex = lRDPListIndex + 1
......
......@@ -11,4 +11,14 @@ def ProcessStop(inProcessName, inFlagForceClose):
lResult = f'taskkill /im "{inProcessName}" /fi "username eq %USERNAME%"'
if inFlagForceClose:
lResult+= " /F"
return lResult
\ No newline at end of file
return lResult
# Send file from Host to Session RDP using shared drive in RDP (force copy)
def FileStoredSend(inHostFilePath, inRDPFilePath):
lHostFileAbsPath = os.path.join("\\\\tsclient", os.path.abspath(inHostFilePath).replace(":","")) # \\tsclient\C\path\to\file
lHostRDPFileAbsPath = os.path.abspath(inRDPFilePath) # File location in RDP
lResult = f'copy /Y "{lHostFileAbsPath}" "{lHostRDPFileAbsPath}"'
# Send file from Session RDP to Host using shared drive in RDP (force copy)
def FileStoredRecieve(inRDPFilePath, inHostFilePath):
lHostFileAbsPath = os.path.join("\\\\tsclient", os.path.abspath(inHostFilePath).replace(":","")) # \\tsclient\C\path\to\file
lHostRDPFileAbsPath = os.path.abspath(inRDPFilePath) # File location in RDP
lResult = f'copy /Y "{lHostRDPFileAbsPath}" "{lHostFileAbsPath}"'
\ No newline at end of file
......@@ -2,15 +2,16 @@ import win32clipboard
import keyboard # keyboard functions
import time # Some operations need wait
import random # random number for test
gWaitTextInClipboardSec = 1 # Second for wait text will be set in clipboard (for get operations)
# set clipboard data
def TextSet(inTextStr):
win32clipboard.OpenClipboard()
win32clipboard.EmptyClipboard()
win32clipboard.SetClipboardText(inTextStr)
win32clipboard.CloseClipboard()
# get clipboard data
def TextGet():
def TextGet(inWaitTextInClipboardSec = gWaitTextInClipboardSec):
time.sleep(inWaitTextInClipboardSec) # Wait for clipboard will save
win32clipboard.OpenClipboard()
data = win32clipboard.GetClipboardData()
win32clipboard.CloseClipboard()
......
#####################################
# RobotRDPActive Exceptions class
#####################################
class SessionWindowNotExistError(Exception): pass #Error when Window not exists
class SessionWindowNotResponsibleError(Exception): pass # Error when Window not responding
class HostNoGUIError(Exception): pass # Orchestrator session has no GUI
#try:
# raise SessionWindowNotResponsibleError("Test")
#except SessionWindowNotResponsibleError as e:
# print("Catched")
# ATTENTION! HERE IS NO Relative import because it will be imported dynamically
# All function check the flag SessionIsWindowResponsibleBool == True else no cammand is processed
# All functions can return None, Bool or Dict { "IsSuccessful": True }
from pyOpenRPA.Tools.RobotRDPActive import CMDStr # Create CMD Strings
from pyOpenRPA.Tools.RobotRDPActive import Connector # RDP API
def ProcessStartIfNotRunning(inGlobalDict, inSessionIndex, inProcessName, inFilePath, inFlagGetAbsPath=True):
lResult = True
lCMDStr = CMDStr.ProcessStartIfNotRunning(inProcessName,inFilePath, inFlagGetAbsPath= inFlagGetAbsPath)
# Calculate the session Hex
lSessionHex = inGlobalDict["RDPList"][inSessionIndex]["SessionHex"]
# Run CMD
Connector.SessionCMDRun(inSessionHex=lSessionHex, inCMDCommandStr=lCMDStr, inModeStr="RUN")
# Check is Session is responsible
if inGlobalDict["RDPList"][inSessionIndex]["SessionIsWindowResponsibleBool"]:
# Run CMD
Connector.SessionCMDRun(inSessionHex=lSessionHex, inCMDCommandStr=lCMDStr, inModeStr="RUN")
else:
# Write in logger - warning
inGlobalDict["Logger"].warning(f"GlobalDictSessionIndex_Defs.ProcessStartIfNotRunning: SessionIndex: {str(inSessionIndex)}, ProcessName: {inProcessName}:: Session is not responsible!")
lResult = False # Set false result - function has not been done
return lResult
# Create CMD str to stop process
def ProcessStop(inGlobalDict, inSessionIndex, inProcessName, inFlagForceClose):
lResult = True
lCMDStr = f'taskkill /im "{inProcessName}" /fi "username eq %USERNAME%"'
if inFlagForceClose:
lCMDStr+= " /F"
# Calculate the session Hex
lSessionHex = inGlobalDict["RDPList"][inSessionIndex]["SessionHex"]
# Run CMD
Connector.SessionCMDRun(inSessionHex=lSessionHex, inCMDCommandStr=lCMDStr, inModeStr="RUN")
\ No newline at end of file
# Check is Session is responsible
if inGlobalDict["RDPList"][inSessionIndex]["SessionIsWindowResponsibleBool"]:
# Run CMD
Connector.SessionCMDRun(inSessionHex=lSessionHex, inCMDCommandStr=lCMDStr, inModeStr="RUN")
else:
# TODO Write in logger - warning
inGlobalDict["Logger"].warning(f"GlobalDictSessionIndex_Defs.ProcessStop: SessionIndex: {str(inSessionIndex)}, ProcessName: {inProcessName}:: Session is not responsible!")
lResult = False # Set false result - function has not been done
return lResult
# Send file from Host to Session RDP using shared drive in RDP
def FileStoredSend(inGlobalDict, inSessionIndex, inHostFilePath, inRDPFilePath):
lResult = True
lCMDStr = CMDStr.FileStoredSend(inHostFilePath = inHostFilePath, inRDPFilePath = inRDPFilePath):
# Calculate the session Hex
lSessionHex = inGlobalDict["RDPList"][inSessionIndex]["SessionHex"]
# Check is Session is responsible
if inGlobalDict["RDPList"][inSessionIndex]["SessionIsWindowResponsibleBool"]:
# Run CMD
Connector.SessionCMDRun(inSessionHex=lSessionHex, inCMDCommandStr=lCMDStr, inModeStr="LISTEN", inClipboardTimeoutSec = 120)
else:
# Write in logger - warning
inGlobalDict["Logger"].warning(f"GlobalDictSessionIndex_Defs.FileStoredSend: SessionIndex: {str(inSessionIndex)}, HostFilePath: {inHostFilePath}:: Session is not responsible!")
lResult = False # Set false result - function has not been done
return lResult
# Recieve file from Session RDP to Host using shared drive in RDP
def FileStoredRecieve(inGlobalDict, inSessionIndex, inRDPFilePath, inHostFilePath):
lResult = True
lCMDStr = CMDStr.FileStoredRecieve(inRDPFilePath = inRDPFilePath, inHostFilePath = inHostFilePath):
# Calculate the session Hex
lSessionHex = inGlobalDict["RDPList"][inSessionIndex]["SessionHex"]
# Check is Session is responsible
if inGlobalDict["RDPList"][inSessionIndex]["SessionIsWindowResponsibleBool"]:
# Run CMD
Connector.SessionCMDRun(inSessionHex=lSessionHex, inCMDCommandStr=lCMDStr, inModeStr="LISTEN", inClipboardTimeoutSec = 120)
else:
# Write in logger - warning
inGlobalDict["Logger"].warning(f"GlobalDictSessionIndex_Defs.FileStoredRecieve: SessionIndex: {str(inSessionIndex)}, HostFilePath: {inHostFilePath}:: Session is not responsible!")
lResult = False # Set false result - function has not been done
return lResult
\ No newline at end of file
......@@ -19,7 +19,7 @@ class Scheduler:
# Init the threads
lTimerMainThread = threading.Thread(target = self.TimerMainThreadRun)
lTimerMainThread.start() # Start the Timer main thread
print (f"Class instance configuration: {self.mSchedulerDict}, Init has been completed")
#print (f"Class instance configuration: {self.mSchedulerDict}, Init has been completed")
########################
# Main timer thread - run when init class instance
def TimerMainThreadRun(self):
......@@ -102,5 +102,5 @@ class Scheduler:
#Timer.activityLoopStart(lItem["ActivityIntervalSeconds"], lActivityTimeEndDateTime, lItem["Activity"])
lTimer = Timer.RepeatedTimer(lItem["ActivityIntervalSeconds"], lActivityTimeEndDateTime, lDef, *lItem["Activity"]["ArgList"], **lItem["Activity"]["ArgDict"]) # it auto-starts, no need of rt.start()
#Уснуть до следующего прогона
print (f"Loop has been completed")
#print (f"Loop has been completed")
time.sleep(lDaemonLoopSeconds)
\ No newline at end of file
......@@ -31,22 +31,21 @@ if lSubmoduleFunctionName in dir(lTechModuleFromSpec):
from pyOpenRPA.Tools.RobotRDPActive import Connector
from pyOpenRPA.Tools.RobotRDPActive import Monitor
from pyOpenRPA.Tools.RobotRDPActive import Scheduler # Scheduler operations
#Disable certificate warning
lCMDString = 'reg add "HKEY_CURRENT_USER\\Software\\Microsoft\\Terminal Server Client" /v "AuthenticationLevelOverride" /t "REG_DWORD" /d 0 /f'
os.system(lCMDString)
#time.sleep()
for lConfigurationItem in mGlobalDict["RDPList"]:
try:
Connector.Session(lConfigurationItem)
lConfigurationItem["FlagSessionIsActive"]=True #Flag that session is started
except Exception:
pass
#Run monitor
#print(mGlobalDict)
Scheduler.Scheduler(mGlobalDict["Scheduler"]) # Init & Run Scheduler
Monitor.Monitor(mGlobalDict, 1)
#Enable certificate warning
lCMDString = 'reg add "HKEY_CURRENT_USER\\Software\\Microsoft\\Terminal Server Client" /v "AuthenticationLevelOverride" /t "REG_DWORD" /d 2 /f'
os.system(lCMDString)
#Close all thread from OrchestratorConnection
mGlobalDict["OrchestratorConnectorTerminateAll"]()
\ No newline at end of file
#### Global error handler
try:
#time.sleep()
######## Init the RDP List
for lConfigurationItem in mGlobalDict["RDPList"]:
lConfigurationItem["SessionIsWindowExistBool"]=False #Flag that session is not started
lConfigurationItem["SessionIsWindowResponsibleBool"]=False #Flag that session is not started
lConfigurationItem["SessionHex"]=" 77777sdfsdf77777dsfdfsf77777777" #Flag that session is not started
##########
#Run monitor
Scheduler.Scheduler(mGlobalDict["Scheduler"]) # Init & Run Scheduler
Monitor.Monitor(mGlobalDict, 1)
except Exception as e:
# Write in logger - warning
mGlobalDict["Logger"].exception(f"!!! ATTENTION !!! Global error handler - look at code")
finally:
#Close all thread from OrchestratorConnection
mGlobalDict["OrchestratorConnectorTerminateAll"]()
\ No newline at end of file
......@@ -4,6 +4,7 @@ from pyOpenRPA.Tools import RobotRDPActive # For RobotRDPActive folder purposes
import os
import logging
import datetime
import sys
#Definitions
lOrchestratorHost="localhost"
lOrchestratorPort=8081
......@@ -29,10 +30,13 @@ def Settings():
"DepthBit": "32" # "32" or "24" or "16" or "15"
},
"SharedDriveList":["c"], # List of the Root sesion hard drives
###### Will updated in program ############
"SessionHex":"", # Hex is created when robot runs
"FlagSessionIsActive": False
"SessionIsWindowExistBool": False , # Flag if the RDP window is exist, old name "FlagSessionIsActive". Check every n seconds
"SessionIsWindowResponsibleBool": False # Flag if RDP window is responsible (recieve commands). Check every nn seconds. If window is Responsible - window is Exist too
}
],
"ResponsibilityCheckIntervalSec": None, # Seconds interval when Robot check the RDP responsibility. if None - dont check
"FullScreenSessionIndex": None, #Index of the current session which is full screened, None is no session in fullscreen
"Logger": logging.getLogger("RobotRDPActive"),
"OrchestratorToRobotStorage": {
......@@ -151,12 +155,17 @@ def Settings():
#Подготовка логгера Robot
#########################
mRobotLogger=mDict["Logger"]
mRobotLogger.setLevel(logging.INFO)
mRobotLogger.setLevel(logging.INFO) #logging.DEBUG
# create the logging file handler
mRobotLoggerFH = logging.FileHandler("Reports\ReportRobotRDPActive_"+datetime.datetime.now().strftime("%Y_%m_%d")+".log")
mRobotLoggerFormatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
mRobotLoggerFH.setFormatter(mRobotLoggerFormatter)
# add handler to logger object
mRobotLogger.addHandler(mRobotLoggerFH)
####################Add console output
if mDict["Logs"]["FlagShowInConsole"]:
handler = logging.StreamHandler(sys.stdout)
handler.setFormatter(lRobotLoggerFormatter)
mRobotLogger.addHandler(handler)
############################################
return mDict
\ No newline at end of file
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment