You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
212 lines
8.6 KiB
212 lines
8.6 KiB
6 years ago
|
import datetime
|
||
|
import http.client
|
||
|
import json
|
||
6 years ago
|
import pdb
|
||
6 years ago
|
import os
|
||
6 years ago
|
import sys
|
||
6 years ago
|
import subprocess
|
||
5 years ago
|
import copy
|
||
5 years ago
|
import importlib
|
||
|
#Input arg
|
||
6 years ago
|
# [
|
||
|
# {
|
||
5 years ago
|
# "Type": <RemoteMachineProcessingRun>,
|
||
6 years ago
|
# host: <localhost>,
|
||
|
# port: <port>,
|
||
|
# bodyObject: <object dict, int, str, list>
|
||
6 years ago
|
# },
|
||
|
# {
|
||
5 years ago
|
# "Type": "CMDStart",
|
||
|
# "Command": ""
|
||
6 years ago
|
# },
|
||
|
# {
|
||
5 years ago
|
# "Type": "OrchestratorRestart"
|
||
6 years ago
|
# },
|
||
|
# {
|
||
5 years ago
|
# "Type": "GlobalDictKeyListValueSet",
|
||
|
# "KeyList": ["key1","key2",...],
|
||
|
# "Value": <List, Dict, String, int>
|
||
6 years ago
|
# },
|
||
|
# {
|
||
5 years ago
|
# "Type": "GlobalDictKeyListValueGet",
|
||
|
# "KeyList": ["key1","key2",...]
|
||
5 years ago
|
# },
|
||
|
# {
|
||
5 years ago
|
# "Type":"ProcessStart",
|
||
|
# "Path":"",
|
||
|
# "ArgList":[]
|
||
|
#
|
||
5 years ago
|
# },
|
||
|
# {
|
||
5 years ago
|
# "Type":"ProcessStop",
|
||
|
# "Name":"",
|
||
|
# "FlagForce":True,
|
||
|
# "User":"" #Empty, user or %username%
|
||
5 years ago
|
# },
|
||
5 years ago
|
# {
|
||
|
# "Type":"PythonStart",
|
||
|
# "ModuleName":"",
|
||
|
# "FunctionName":"",
|
||
|
# "ArgList":[],
|
||
|
# "ArgDict":{}
|
||
5 years ago
|
# },
|
||
|
# {
|
||
|
# "Type":"WindowsLogon",
|
||
|
# "Domain":"",
|
||
|
# "User":"",
|
||
|
# "Password":""
|
||
|
# # Return "Result": True - user is logged on, False - user is not logged on
|
||
5 years ago
|
# }
|
||
6 years ago
|
# ]
|
||
5 years ago
|
##################################
|
||
|
#Output result
|
||
|
# <input arg> with attributes:
|
||
|
# "DateTimeUTCStringStart"
|
||
|
# "DateTimeUTCStringStop"
|
||
|
# "Result"
|
||
|
def Activity(inActivity):
|
||
|
#Глобальная переменная - глобальный словарь унаследованный от Settings.py
|
||
|
global mGlobalDict
|
||
|
#Fill DateTimeUTCStringStart
|
||
|
inActivity["DateTimeUTCStringStart"] = datetime.datetime.strftime(datetime.datetime.now(),"%Y-%m-%dT%H:%M:%S.%f")
|
||
|
#Alias (compatibility)
|
||
|
lItem = inActivity
|
||
|
###########################################################
|
||
|
#Обработка запроса на отправку команды на удаленную машину
|
||
|
###########################################################
|
||
|
if lItem["Type"]=="RemoteMachineProcessingRun":
|
||
|
lHTTPConnection = http.client.HTTPConnection(lItem["host"], lItem["port"], timeout=5)
|
||
|
try:
|
||
|
lHTTPConnection.request("POST","/ProcessingRun",json.dumps(lItem["bodyObject"]))
|
||
|
except Exception as e:
|
||
|
#Объединение словарей
|
||
|
lItem["Result"] = {"State":"disconnected","ExceptionString":str(e)}
|
||
|
else:
|
||
|
lHTTPResponse=lHTTPConnection.getresponse()
|
||
|
lHTTPResponseByteArray=lHTTPResponse.read()
|
||
|
lItem["Result"] = json.loads(lHTTPResponseByteArray.decode('utf8'))
|
||
|
###########################################################
|
||
|
#Обработка команды CMDStart
|
||
|
###########################################################
|
||
|
if lItem["Type"]=="CMDStart":
|
||
5 years ago
|
lCMDCode="cmd /c "+lItem["Command"]
|
||
5 years ago
|
subprocess.Popen(lCMDCode)
|
||
|
lResultCMDRun=1#os.system(lCMDCode)
|
||
|
lItem["Result"] = str(lResultCMDRun)
|
||
|
###########################################################
|
||
|
#Обработка команды OrchestratorRestart
|
||
|
###########################################################
|
||
|
if lItem["Type"]=="OrchestratorRestart":
|
||
|
os.execl(sys.executable,os.path.abspath(__file__),*sys.argv)
|
||
|
lItem["Result"] = True
|
||
|
sys.exit(0)
|
||
|
###########################################################
|
||
|
#Обработка команды GlobalDictKeyListValueSet
|
||
|
###########################################################
|
||
|
if lItem["Type"]=="GlobalDictKeyListValueSet":
|
||
|
for lItem2 in lItem["KeyList"][:-1]:
|
||
|
#Check if key - value exists
|
||
|
if lItem2 in mGlobalDict:
|
||
|
pass
|
||
6 years ago
|
else:
|
||
5 years ago
|
mGlobalDict[lItem2]={}
|
||
|
mGlobalDict=mGlobalDict[lItem2]
|
||
|
#Set value
|
||
|
mGlobalDict[lItem["KeyList"][-1]]=lItem["value"]
|
||
|
###########################################################
|
||
|
#Обработка команды GlobalDictKeyListValueGet
|
||
|
###########################################################
|
||
5 years ago
|
if lItem["Type"]=="GlobalDictKeyListValueGet":
|
||
5 years ago
|
for lItem2 in lItem["KeyList"][:-1]:
|
||
|
#Check if key - value exists
|
||
|
if lItem2 in mGlobalDict:
|
||
|
pass
|
||
|
else:
|
||
|
mGlobalDict[lItem2]={}
|
||
|
mGlobalDict=mGlobalDict[lItem2]
|
||
|
#Return value
|
||
|
lItem["Result"]==mGlobalDict.get(lItem["KeyList"][-1],None)
|
||
|
#Определить вид активности
|
||
|
lActivityDateTime=inActivity["DateTimeUTCStringStart"]
|
||
|
#####################################
|
||
|
#ProcessStart
|
||
|
#####################################
|
||
|
if lItem["Type"]=="ProcessStart":
|
||
|
#Вид активности - запуск процесса
|
||
|
#Запись в массив отработанных активностей
|
||
|
#Лог
|
||
|
mGlobalDict["Processor"]["LogList"].append({"activityType":lItem["activityType"], "activityDateTime":str(lActivityDateTime), "processPath":lItem["processPath"], "activityStartDateTime":str(lCurrentDateTime)})
|
||
|
#Запустить процесс
|
||
|
lItemArgs=[lItem["processPath"]]
|
||
|
lItemArgs.extend(lItem["processArgs"])
|
||
|
subprocess.Popen(lItemArgs,shell=True)
|
||
|
#################################
|
||
|
#ProcessStop
|
||
|
#################################
|
||
|
if lItem["Type"]=="ProcessStop":
|
||
|
#Вид активности - остановка процесса
|
||
|
#часовой пояс пока не учитываем
|
||
|
#Сформировать команду на завершение
|
||
|
lActivityCloseCommand='taskkill /im '+lItem["processName"]
|
||
|
#TODO Сделать безопасную обработку,если параметра нет в конфигурации
|
||
|
if lItem.get('FlagForce',False):
|
||
|
lActivityCloseCommand+=" /F"
|
||
|
#Завершить процессы только текущего пользоваиеля
|
||
|
if lItem.get('User',"")!="":
|
||
|
lActivityCloseCommand+=f' /fi "username eq {lItem["User"]}"'
|
||
|
#Лог
|
||
|
mGlobalDict["Processor"]["LogList"].append({"activityType":lItem["activityType"], "activityDateTime":str(lActivityDateTime), "processPath":lItem["processName"], "activityStartDateTime":str(lCurrentDateTime)})
|
||
|
#Завершить процесс
|
||
|
os.system(lActivityCloseCommand)
|
||
|
#################################
|
||
|
#PythonStart
|
||
|
#################################
|
||
|
if lItem["Type"]=="PythonStart":
|
||
|
try:
|
||
|
#Подключить модуль для вызова
|
||
|
lModule=importlib.import_module(lItem["ModuleName"])
|
||
|
#Найти функцию
|
||
|
lFunction=getattr(lModule,lItem["FunctionName"])
|
||
|
lItem["Result"]=lFunction(*lItem.get("ArgList",[]),**lItem.get("ArgDict",{}))
|
||
|
except Exception as e:
|
||
|
logging.exception("Loop activity error: module/function not founded")
|
||
5 years ago
|
#################################
|
||
|
# Windows logon
|
||
|
#################################
|
||
|
if lItem["Type"] == "WindowsLogon":
|
||
|
import win32security
|
||
|
try:
|
||
|
hUser = win32security.LogonUser(
|
||
|
lItem["User"],
|
||
|
lItem["Domain"],
|
||
|
lItem["Password"],
|
||
|
win32security.LOGON32_LOGON_NETWORK,
|
||
|
win32security.LOGON32_PROVIDER_DEFAULT
|
||
|
)
|
||
|
except win32security.error:
|
||
|
lItem["Result"] = False
|
||
|
else:
|
||
|
lItem["Result"] = True
|
||
|
###################################
|
||
5 years ago
|
#Set datetime stop
|
||
|
lItem["DateTimeUTCStringStop"] = datetime.datetime.now().strftime("%Y-%m-%dT%H:%M:%S.%f")
|
||
|
##################
|
||
|
#Trace activity
|
||
|
##################
|
||
|
if mGlobalDict["Processor"].get(f"LogType_{lItem['Type']}",True):
|
||
|
#Add activity in TransactionList if it is applicable
|
||
|
mGlobalDict["Processor"]["LogList"].append(copy.deepcopy(lItem))
|
||
6 years ago
|
#Вернуть результат
|
||
5 years ago
|
return lItem
|
||
|
|
||
|
def ActivityListOrDict(inActivityListOrDict):
|
||
|
#Check arg type (list or dict)
|
||
|
if type(inActivityListOrDict)==list:
|
||
|
#List activity
|
||
5 years ago
|
lResult=[]
|
||
5 years ago
|
for lItem in inActivityListOrDict:
|
||
|
lResult.append(Activity(lItem))
|
||
|
return lResult
|
||
|
if type(inActivityListOrDict)==dict:
|
||
|
#Dict activity
|
||
|
return Activity(inActivityListOrDict)
|