Python Cheatsheet for SOAR

I find that the vast majority of vendor integrations and playbooks automations are 90% identical: ingest inbound data (array, object, etc), parse through it whilst validating and extracting, then finally pushing it out.

This means I use the same code aaaaaall the time. So I thought I would make a little cheatsheet for the basics (to prevent me googling the same things over and over). This list will change/grow over time.

Not covered in this cheatsheet:

  • Local file handling (open, read, close, etc)
  • HTTP and SSL request/replies
  • Time/date handling

To keep formatting simple, “<<tab>>” respresents a real Tab in the code

#******
#Common Lib Imports
import json, re, pprint, time, random, base64
#Basic string
myString = “hi”
myString += ” I added a bit”
#Convert
myNum = int(myString)
myInt = str(myNumber)
#If
if varA > 5:
<<tab>>print(“High”)
elif varA > 0:
<<tab>>print(“Medium”)
else:
<<tab>>print(“Zero”)
Basic structure
Remember indents are tabs
if myString == “compare me”:Simple string comparison
if myVar is None:None / Null
if not myVar:Check if value exists, but is empty
if (a == b) and (not b == c):
if (a < 5 < b):If both are true
if isinstance(myVar, list):list, dict, str, int… etc
#Lists (arrays)
myList = []
myList.append(“bob”)
[output1, output2] = myList.split(‘character’)
myList = myString.split(” “)
myString = “-“.join(myList)
#Python Dict
myDict = {}alternative >> myDict = dict()
myVar = myDict.get(“key”, default_value)Extract a value into another var
myVar = myObject[‘key’]Similar to above, but will return error if not found
myDict[‘key’] = ‘value’Set a new value to the Dict
if myKey in myDict:Check if key exists
myList = myDict.keys()Same for “.values()”
#Json(Technically not a Dict, but handled very similarly)
myJson = {}
myJson = json.loads(string)Where string is in the form  “{‘key’:value}”
myString = myJson[‘key’]
myJson[‘key’] = newValue
myJsonAsString = json.dumps(myJson)
if myKey in myJson:
#Loops
for value in myList:
<<tab>>print(value)
Loop a List
while condition == True:Simple while
for myInt in range(5):myInt will be 1,2,3,4,5
for index in range(len(myList)):index will represent a number of the position in array
for key, value in myJson.items():Loop through Json/Dict
for key in jsonObject:
<<tab>>value = jsonObject[key]
Alternative to the above
breakBreak out of the current loop (1 layer) to next code
continueStop processing this loop, and go to next iteration of this loop structure
#Regex
newString = re.sub(r”pattern”, “replaceWith”, targetString))regex substitution
arrayResults = re.findall(r’pattern’, targetString)regex findall
matches = re.match(r”Goodbye”, “Hello”)
if match is None:
regex match and test
objectResults = re.search(“[a-z]+”,myVar)Returns complex output
#base64
encoded = base64.b64encode(‘Hello World’)Encode a string into Base64
readableData = base64.b64decode(encoded)Convert Base64 back into the original string
#Try
try:
<<tab>>print(nonExistentVariable)
except:
<<tab>>print(“Something went wrong”)
finally:
<<tab>>print(“The ‘try except’ is finished”)
Remember tab indents
#Debug
print()Simple print
pprint()Print more complicated objects
from pprint import pprint
#Bits and Bobs
random.seed()
myInt = random.random()
Int between 0.0 and 1.0
randomInt = random.randint(1,100)Int between x and y
time.sleep(1)

Leave a Reply

Your email address will not be published. Required fields are marked *