def cmnd( self, interactive=False, # Can also be called non-interactively userName=None, # or Cmnd-Input role=None, # or Cmnd-Input acGroups=None, # or Cmnd-Input ): cmndOutcome = self.getOpOutcome() if interactive: if not self.cmndLineValidate(outcome=cmndOutcome): return cmndOutcome callParamsDict = { 'userName': userName, 'role': role, 'acGroups': acGroups, } if not icm.cmndCallParamsValidate( callParamsDict, interactive, outcome=cmndOutcome): return cmndOutcome userName = callParamsDict['userName'] role = callParamsDict['role'] acGroups = callParamsDict['acGroups'] ####+END: outBearerToken = BearerToken() outUserInfo = BearerTokenUserInfo() if userName: outUserInfo.setUserName(userName) if role: outUserInfo.setRole(role) if acGroups: outUserInfo.setResGroupIds(acGroups) outBearerToken.setUserInfo(outUserInfo) bearerTokenStr = outBearerToken.encodeAsJsonStr() icm.LOG_here(bearerTokenStr) bearerTokenDict = outBearerToken.selfAsDict() encoded = jwt.encode(bearerTokenDict, 'secret', algorithm='HS256') if interactive: print(encoded) else: icm.LOG_here(encoded) return cmndOutcome.set( opError=icm.OpError.Success, opResults=encoded, )
def getOperationWithResourceAndOpName( spec, origin_url, resource, opName, ): ####+END: """Returns op object.""" pp = pprint.PrettyPrinter(indent=4) spec = Spec.from_dict(spec, origin_url=origin_url) #pp.pprint(spec) for res_name, res in list(spec.resources.items()): if res_name != resource: continue for op_name, op in list(res.operations.items()): if op_name != opName: continue name = get_command_name(op) icm.LOG_here( "Invoking: resource={resource} opName={opName}".format( resource=resource, opName=op_name)) return op
def connect(self): """ """ accessParams = self.accessParamsGet() if not accessParams.accessMethodValue == 'ssh': # EH_problem() pass try: icm.TM_here( format('ssh -l %s %s' % (accessParams.userNameValue, accessParams.targetFqdnValue))) connection = pexpect.spawn( 'ssh -l %s %s' % (accessParams.userNameValue, accessParams.targetFqdnValue)) except Exception as e: icm.TM_here('EXCEPTION: ' + str(e)) raise try: icm.TM_here('pexpect -- waiting for COMMAND_PROMPT=' + COMMAND_PROMPT) i = connection.expect( [pexpect.TIMEOUT, SSH_NEWKEY, COMMAND_PROMPT, '(?i)password']) except Exception as e: icm.TM_here('EXCEPTION: ' + str(e)) raise #icm.TM_here() if i == 0: # Timeout icm.TM_here() print('ERROR! could not login with SSH. Here is what SSH said:') print(connection.before, connection.after) print(str(connection)) sys.exit(1) if i == 1: # In this case SSH does not have the public key cached. icm.TM_here() connection.sendline('yes') connection.expect('(?i)password') if i == 2: icm.TM_here("Auto Login -- Public Key") # This may happen if a public key was setup to automatically login. # But beware, the COMMAND_PROMPT at this point is very trivial and # could be fooled by some output in the MOTD or login message. #pass # 20170428 -- Mohsen Fix connection.sendline(' ') return connection if i == 3: icm.TM_here( format('Received: ' + connection.before + connection.after)) icm.TM_here('Sending: Passwd') #icm.TM_here('Sending: ' + accessParams.passwordValue ) connection.sendline(accessParams.passwordValue) # Now we are either at the command prompt or # the login process is asking for our terminal type. icm.LOG_here("Connected ....") return connection
def cmnd( self, interactive=False, # Can also be called non-interactively bxoId=None, # or Cmnd-Input sr=None, # or Cmnd-Input ): cmndOutcome = self.getOpOutcome() if interactive: if not self.cmndLineValidate(outcome=cmndOutcome): return cmndOutcome callParamsDict = { 'bxoId': bxoId, 'sr': sr, } if not icm.cmndCallParamsValidate( callParamsDict, interactive, outcome=cmndOutcome): return cmndOutcome bxoId = callParamsDict['bxoId'] sr = callParamsDict['sr'] ####+END: trackDeliveryLogFile = trackDeliveryLogFileGet( bxoId=bxoId, sr=sr, ) icm.LOG_here(trackDeliveryLogFile) return cmndOutcome.set( opError=icm.OpError.Success, opResults=None, )
def initFromJsonStr( self, jsonStr, ): """ """ jsonData = json.loads(jsonStr) pp = pprint.PrettyPrinter(indent=4) icm.LOG_here(pp.pformat(jsonData)) self.__class__._userInfoDict = jsonData['userInfo'] userInfo = BearerTokenUserInfo(jsonData['userInfo']) self.setUserInfo(userInfo)
def passwdGet(self): ####+END: """ Return passwd.""" keyringPasswd = keyring.get_password(self.system, self.user) outcome = symCrypt.decrypt().cmnd( interactive=False, rsrc="policy/{}".format(self.__class__.ucryptPolicy), cipherText=keyringPasswd, ).log() if outcome.isProblematic(): return (icm.EH_badOutcome(outcome)) clearPasswd = outcome.results icm.LOG_here(clearPasswd) return clearPasswd
def __init__( self, userInfoDict=None, ): if not userInfoDict: return pp = pprint.PrettyPrinter(indent=4) icm.LOG_here(pp.pformat(userInfoDict)) if 'userId' in list(userInfoDict.keys()): self.setUserId(userInfoDict['userId']) if 'userName' in list(userInfoDict.keys()): self.setUserName(userInfoDict['userName']) if 'role' in list(userInfoDict.keys()): self.setRole(userInfoDict['role']) if 'acGroups' in list(userInfoDict.keys()): self.setResGroupIds(userInfoDict['acGroups']) if 'serviceBlackList' in list(userInfoDict.keys()): self.setServiceBlackList(userInfoDict['serviceBlackList'])
def passwdSet( self, passwd, ): ####+END: """ Return passwd string from keyring. """ outcome = symCrypt.encrypt().cmnd( interactive=False, rsrc="policy/{}".format(self.__class__.ucryptPolicy), clearText=passwd, ).log() if outcome.isProblematic(): return (icm.EH_badOutcome(outcome)) cipheredPasswd = outcome.results keyring.set_password(self.system, self.user, cipheredPasswd) keyringPasswd = keyring.get_password(self.system, self.user) icm.LOG_here(keyringPasswd) return keyringPasswd
def paramProc(thisParam): """At this point, we have the target and the parameter, ready for processing. - From thisParam's fileParams, get the agent and parName, - Then remoteExec the agent on target and get the results. - Record the obtained results with local invokation of the agent. """ icm.TM_here( 'targetPath=' + thisPathTarget) # Target Access Information icm.TM_here(format('ticmoBase=' + thisTicmoBase)) # TICMO Base paramBase = thisParam.base() icm.TM_here('paramBase=' + paramBase) agent = icm.FILE_ParamValueReadFrom(parRoot=paramBase, parName='agent') if not agent: return (icm.EH_problem_unassignedError()) parName = icm.FILE_ParamValueReadFrom( parRoot=paramBase, parName='parName') if not parName: return (icm.EH_problem_unassignedError()) commandLine = format(agent + ' -p mode=agent -i ' + parName) icm.LOG_here('RemoteExec: ' + commandLine) resultLines = linuxTarget.runCommand( connection, commandLine) pipeableResultLines = "" for thisResultLine in resultLines: pipeableResultLines = pipeableResultLines + thisResultLine + '\n' icm.LOG_here('ResultLines: ' + str(resultLines)) # We can now dateVer and empnaPkg write the resultLines for parName in TICMO #fileParWriteBase = os.path.join(thisTicmoBase, empnaPkg, dateVer) # updated = icm.FILE_ParamWriteTo(parRoot=fileParWriteBase, # parName=parName, # parValue=resultLines[0]) # # We ask the agent to capture the resultLines in ticmo # commandLine = format( agent + ' ' + '-n showRun -p mode=capture -p ticmoBase=' + ' -i ' + parName) commandArgs = shlex.split(commandLine) icm.LOG_here('SubProc: ' + commandLine) p = subprocess.Popen(commandArgs, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) out, err = p.communicate( input=format(pipeableResultLines.encode())) if out: icm.ANN_note("Stdout: " + out) if err: icm.ANN_note("Stderr: " + err) return
def cmnd( self, interactive=False, # Can also be called non-interactively userName=None, # or Cmnd-Input role=None, # or Cmnd-Input acGroups=None, # or Cmnd-Input argsList=[], # or Args-Input ): cmndOutcome = self.getOpOutcome() if interactive: if not self.cmndLineValidate(outcome=cmndOutcome): return cmndOutcome effectiveArgsList = G.icmRunArgsGet().cmndArgs else: effectiveArgsList = argsList callParamsDict = { 'userName': userName, 'role': role, 'acGroups': acGroups, } if not icm.cmndCallParamsValidate( callParamsDict, interactive, outcome=cmndOutcome): return cmndOutcome userName = callParamsDict['userName'] role = callParamsDict['role'] acGroups = callParamsDict['acGroups'] cmndArgsSpecDict = self.cmndArgsSpec() if not self.cmndArgsValidate( effectiveArgsList, cmndArgsSpecDict, outcome=cmndOutcome): return cmndOutcome ####+END: outBearerToken = BearerToken() outUserInfo = BearerTokenUserInfo() if userName: outUserInfo.setUserName(userName) if role: outUserInfo.setRole(role) if acGroups: outUserInfo.setResGroupIds(acGroups) outBearerToken.setUserInfo(outUserInfo) bearerTokenStr = outBearerToken.encodeAsJsonStr() icm.LOG_here(bearerTokenStr) bearerTokenDict = outBearerToken.selfAsDict() encoded = jwt.encode(bearerTokenDict, 'secret', algorithm='HS256') icm.LOG_here(encoded) base64Str = base64.standard_b64encode(bearerTokenStr) icm.LOG_here(base64Str) outFilePath = self.cmndArgsGet("0", cmndArgsSpecDict, effectiveArgsList) icm.LOG_here("Writing BearerToken to {outFilePath}".format( outFilePath=outFilePath, )) with open(outFilePath, 'w') as outfile: outfile.write(base64Str) outfile.close()
def ro_opInvokeCapture(roOp, ): ####+END: pp = pprint.PrettyPrinter(indent=4) #icm.TM_here("svcSpec={svcSpec} -- perfSap={perfSap}".format(svcSpec=roOp.svcSpec, perfSap=roOp.perfSap)) loadedSvcSpec, origin_url = loadSvcSpec(roOp.svcSpec, roOp.perfSap) if roOp.perfSap: #origin_url = "http://localhost:8080" origin_url = roOp.perfSap # # NOTYET LOG level changes here # #icm.TM_here("{}".format(pp.pformat(loadedSvcSpec))) opBravadoObj = getOperationWithResourceAndOpName( loadedSvcSpec, origin_url, roOp.resource, roOp.opName, ) if not opBravadoObj: icm.EH_problem_usageError( """getOperationWithResourceAndOpName Failed: resource={resource} opName={opName}""" .format( resource=roOp.resource, opName=roOp.opName, )) return None requestOptions = dict() params = roOp.roParams headerParams = params.headerParams if headerParams: requestOptions["headers"] = headerParams urlParams = params.urlParams if urlParams == None: urlParams = dict() bodyParams = params.bodyParams icm.TM_here("{}".format(pp.pformat(bodyParams))) if bodyParams: # # With ** we achieve kwargs # # func(**{'type':'Event'}) is equivalent to func(type='Event') # request = construct_request(opBravadoObj, requestOptions, body=bodyParams, **urlParams) else: request = construct_request(opBravadoObj, requestOptions, **urlParams) icm.LOG_here("request={request}".format(request=pp.pformat(request))) c = RequestsClient() # # This is where the invoke request goes out # future = c.request(request) # # This where the invoke response comes in # opResults = {} try: result = future.result() except Exception as e: #icm.EH_critical_exception(e) opResults = None roResults = ro.Ro_Results( httpResultCode=500, # type=int httpResultText="Internal Server Error", # type=str opResults=opResults, opResultHeaders=None, ) if opResults != None: # # result # # 2018-10-01 -- https://github.com/Yelp/bravado/blob/master/bravado/requests_client.py # class RequestsResponseAdapter(IncomingResponse): # # type(result._delegate.text) = unicode # type(result._delegate.content) = str # opResults = None if result._delegate.content: try: opResults = result.json() except Exception as e: icm.EH_critical_exception(e) opResults = None roResults = ro.Ro_Results( httpResultCode=result._delegate.status_code, # type=int httpResultText=result._delegate.reason, # type=str opResults=opResults, opResultHeaders=result._delegate.headers, ) icm.LOG_here( "RESPONSE: status_code={status_code} -- reason={reason} -- text={text}" .format( status_code=result._delegate.status_code, reason=result._delegate.reason, text=result._delegate.text, )) icm.LOG_here("RESPONSE: responseHeaders: {headers}".format( headers=pp.pformat(result._delegate.headers))) roOp.roResults = roResults return roOp
def opInvoke(headers, op, *args, **kwargs): ####+END: """ NOTYET, Important, opInvoke should be layered on top of opInvokeCapture """ pp = pprint.PrettyPrinter(indent=4) headerLines = list() if headers: with open(headers, 'rb') as file: headerLines = file.readlines() # else: # print("Has No Headers") headerLinesAsDict = dict() for each in headerLines: headerLineAsList = each.split(":") headerLineAsListLen = len(headerLineAsList) if headerLineAsListLen == 2: headerLineTag = headerLineAsList[0] headerLineValue = headerLineAsList[1] else: icm.EH_problem_usageError( "Expected 2: {}".format(headerLineAsListLen)) continue headerLinesAsDict[headerLineTag] = headerLineValue.lstrip(' ').rstrip() requestOptions = dict() if headerLinesAsDict: requestOptions["headers"] = headerLinesAsDict def bodyArgToDict( bodyAny, bodyFile, bodyStr, bodyFunc, ): """ Returns None if all Args were None, and returns "" if one of the args was "", Otherwize a dict or {}.""" def bodyStrAsDict(bodyStr): return ast.literal_eval(bodyStr) def bodyFileAsDict(bodyFile): with open(bodyFile, 'r') as myfile: data = myfile.read().replace('\n', '') return ast.literal_eval(data) def bodyFuncAsDict(bodyFunc): resDict = eval(bodyFunc) # NOTYET, verify that we have a dict return resDict if bodyAny != None: icm.TM_here("bodyAny={}".format(pp.pformat(bodyAny))) if bodyAny == "": return "" # Be it file, function or string if os.path.isfile(bodyAny): return bodyFileAsDict(bodyAny) elif bodyAny == "NOTYET-valid func": return bodyFuncAsDict(bodyAny) else: # We then take bodyAny to be a string return bodyStrAsDict(bodyAny) elif bodyFile != None: icm.TM_here("bodyFile={}".format(pp.pformat(bodyFile))) if bodyFile == "": return "" if os.path.isfile(bodyAny): return bodyFileAsDict(bodyFile) else: return {} elif bodyFunc != None: icm.TM_here("bodyFunc={}".format(pp.pformat(bodyFunc))) if bodyFunc == "": return "" if bodyFunc == "NOTYET-valid func": return bodyFuncAsDict(bodyFunc) else: return {} elif bodyStr != None: icm.TM_here("bodyStr={}".format(pp.pformat(bodyStr))) if bodyStr == "": return "" bodyValue = bodyStrAsDict(bodyStr) return bodyValue else: # So they were all None, meaning that no form of "body" was specified. return None # icm.TM_here("Args: {}".format(args)) # for key in kwargs: # icm.TM_here("another keyword arg: %s: %s" % (key, kwargs[key])) bodyAny = kwargs.pop('body', None) bodyFile = kwargs.pop('bodyFile', None) bodyStr = kwargs.pop('bodyStr', None) bodyFunc = kwargs.pop('bodyFunc', None) bodyValue = bodyArgToDict(bodyAny, bodyFile, bodyStr, bodyFunc) icm.TM_here(pp.pformat(requestOptions)) if bodyValue == None: request = construct_request(op, requestOptions, **kwargs) elif bodyValue == "": # Causes An Exception That Describes Expected Dictionary request = construct_request(op, requestOptions, body=None, **kwargs) else: request = construct_request(op, requestOptions, body=bodyValue, **kwargs) icm.LOG_here("request={request}".format(request=pp.pformat(request))) c = RequestsClient() future = c.request(request) try: result = future.result() except Exception as e: #icm.EH_critical_exception(e) result = None if result: icm.LOG_here("responseHeaders: {headers}".format( headers=pp.pformat(result._delegate.headers))) icm.ANN_write("Operation Status: {result}".format(result=result)) icm.ANN_write("Operation Result: {result}".format( result=pp.pformat(result.json())))
def cmnd( self, interactive=False, # Can also be called non-interactively bxoId=None, # or Cmnd-Input sr=None, # or Cmnd-Input inFile=None, # or Cmnd-Input msg=None, # asFunc when interactive==False ): cmndOutcome = self.getOpOutcome() if interactive: if not self.cmndLineValidate(outcome=cmndOutcome): return cmndOutcome callParamsDict = { 'bxoId': bxoId, 'sr': sr, 'inFile': inFile, } if not icm.cmndCallParamsValidate( callParamsDict, interactive, outcome=cmndOutcome): return cmndOutcome bxoId = callParamsDict['bxoId'] sr = callParamsDict['sr'] inFile = callParamsDict['inFile'] ####+END: G = icm.IcmGlobalContext() if not msg: if inFile: msg = msgIn.getMsgFromFile(inFile) else: # Stdin then msg = msgIn.getMsgFromStdin() else: # non-interactive call with msg if not bxoId: icm.EH_problem_usageError("") return cmndOutcome icm.LOG_here(msgOut.strLogMessage( "Msg As Input:", msg, )) icm.LOG_here(G.icmRunArgsGet().runMode) outcome = msgOut.sendingRunControlSet(msg, G.icmRunArgsGet().runMode) if outcome.isProblematic(): return (icm.EH_badOutcome(outcome)) bx822Set_setMandatoryFields(msg) outcome = bx822Get_sendingFieldsPipelineLoad( bxoId, sr, msg, ) if outcome.isProblematic(): return (icm.EH_badOutcome(outcome)) if outcome.results != "INCOMPLETE": icm.LOG_here("Complete Message Being Sent") return (msgOut.sendBasedOnHeadersInfo(msg)) icm.LOG_here("Incomplete Message -- using qmail+dryrun") msgOut.injectionParams( msg, injectionProgram=msgOut.InjectionProgram.qmail, sendingRunControl=msgOut.SendingRunControl.dryRun, ) return msgOut.sendBasedOnHeadersInfo(msg)
def cmnd( self, interactive=False, # Can also be called non-interactively outMailAcct=None, # or Cmnd-Input inFile=None, # or Cmnd-Input sendingMethod=None, # or Cmnd-Input msg=None, # asFunc when interactive==False ): cmndOutcome = self.getOpOutcome() if interactive: if not self.cmndLineValidate(outcome=cmndOutcome): return cmndOutcome callParamsDict = { 'outMailAcct': outMailAcct, 'inFile': inFile, 'sendingMethod': sendingMethod, } if not icm.cmndCallParamsValidate( callParamsDict, interactive, outcome=cmndOutcome): return cmndOutcome outMailAcct = callParamsDict['outMailAcct'] inFile = callParamsDict['inFile'] sendingMethod = callParamsDict['sendingMethod'] ####+END: G = icm.IcmGlobalContext() if not msg: if inFile: msg = msgIn.getMsgFromFile(inFile) else: # Stdin then msg = msgIn.getMsgFromStdin() icm.LOG_here(msgOut.strLogMessage( "Msg As Input:", msg, )) if not sendingMethod: sendingMethod = msgOut.SendingMethod.submit if msgOut.sendingMethodSet(msg, sendingMethod).isProblematic(): return msgOut.sendingMethodSet(msg, sendingMethod) print(G.usageParams.runMode) if msgOut.sendingRunControlSet(msg, G.usageParams.runMode).isProblematic(): return msgOut.sendingRunControlSet(msg, G.usageParams.runMode) envelopeAddr = msg['From'] recipientsList = msg['To'] msgOut.envelopeAddrSet( msg, mailBoxAddr=envelopeAddr, # Mandatory ) msgOut.crossRefInfo( msg, crossRefInfo="XrefForStatusNotifications" # Mandatory ) msgOut.nonDeliveryNotificationRequetsForTo( msg, recipientsList=recipientsList, notifyTo=envelopeAddr, ) msgOut.nonDeliveryNotificationActions( msg, coRecipientsList=recipientsList, ) msgOut.deliveryNotificationRequetsForTo( msg, recipientsList=recipientsList, notifyTo=envelopeAddr, ) msgOut.dispositionNotificationRequetsForTo( msg, recipientsList=recipientsList, notifyTo=envelopeAddr, ) if msgOut.sendingMethodSet(msg, sendingMethod).isProblematic(): return icm.EH_badLastOutcome() if not marmeSendLib.bx822Set_sendWithEnabledAcct(msg, sendingMethod): return icm.EH_badOutcome(cmndOutcome) cmndOutcome = marmeSendLib.sendCompleteMessage().cmnd( interactive=False, msg=msg, ) return cmndOutcome
def cmnd( self, interactive=False, # Can also be called non-interactively bxoId=None, # or Cmnd-Input sr=None, # or Cmnd-Input controlProfile=None, # or Cmnd-Input inMailAcct=None, # or Cmnd-Input inMbox=None, # or Cmnd-Input argsList=[], # or Args-Input ): cmndOutcome = self.getOpOutcome() if interactive: if not self.cmndLineValidate(outcome=cmndOutcome): return cmndOutcome effectiveArgsList = G.icmRunArgsGet().cmndArgs else: effectiveArgsList = argsList callParamsDict = { 'bxoId': bxoId, 'sr': sr, 'controlProfile': controlProfile, 'inMailAcct': inMailAcct, 'inMbox': inMbox, } if not icm.cmndCallParamsValidate( callParamsDict, interactive, outcome=cmndOutcome): return cmndOutcome bxoId = callParamsDict['bxoId'] sr = callParamsDict['sr'] controlProfile = callParamsDict['controlProfile'] inMailAcct = callParamsDict['inMailAcct'] inMbox = callParamsDict['inMbox'] cmndArgsSpecDict = self.cmndArgsSpec() if not self.cmndArgsValidate( effectiveArgsList, cmndArgsSpecDict, outcome=cmndOutcome): return cmndOutcome ####+END: #cmndArgsSpec = {0: ['msgDisect', 'coRecepientNdr']} cmndArgs = self.cmndArgsGet("0&-1", cmndArgsSpecDict, effectiveArgsList) inMailDir = marmeAcctsLib.getPathForAcctMbox( controlProfile, inMailAcct, inMbox, bxoId=bxoId, sr=sr, ) icm.LOG_here(inMailDir) mbox = mailbox.Maildir( inMailDir, factory=None, # important!! default does not work ) for msgProc in cmndArgs: #icm.ANN_here("thisArg={thisArg}".format(thisArg=msgProc)) #for msg in mbox: for key in mbox.iterkeys(): try: msg = mbox[key] except email.errors.MessageParseError: icm.EH_problem_info(msg) continue # The message is malformed. Just leave it. try: eval(msgProc + '(bxoId, sr, inMailDir, mbox, key, msg)') except Exception as e: icm.EH_critical_exception(e) icm.EH_problem_info( "Invalid Action: {msgProc}".format(msgProc=msgProc)) raise # NOTYET, in production, the raise should be commented out return cmndOutcome.set( opError=icm.OpError.Success, opResults=None, )