# Python Memory Editing I had a binary running in memory and I wanted to be able to extract and edit bytes in it. I could use a tool like cheat engine and copy and paste them out, but I wanted something more scriptable. This isn't as simple of as task as you think it would be in python. This is basically how it is done. https://stackoverflow.com/questions/1794579/how-can-i-read-the-memory-of-another-process-in-python-in-windows https://stackoverflow.com/questions/61845537/reading-memory-address-from-a-process-with-a-static-address-and-offsets-in-pytho This library actually helps a bunch https://github.com/vsantiago113/ReadWriteMemory and has an example trainer for an open source game. Here's an example writing a byte to an address ``` from ReadWriteMemory import ReadWriteMemory rwm = ReadWriteMemory() process = rwm.get_process_by_name('binary.exe') process.open() process.writeByte(0x188F280,[0x0b]) process.close() ``` Open just requests read/write access to the process. ReadWriteMemory does not calculate the base address of the process in memory for you. The first value passed to writeByte() is the hex address in all memory to read from. For example: If the process binary.exe starts at 0xd70000 and you want to write to the 0xb1f280 byte. You would use 0xd70000+0xb1f280, which is 0x188F280. The second value passed to writeByte() is the output of hex() saved as a list. When writing bytes with `writeByte` you are actually writing a list of single byte integers ``` bytes = [] bytes.append(int("0x01",16)) bytes.append(int("0x02",16)) writeByte(0x188F280,bytes) ``` hex() is a python 3 builtin that converts a single int to a hexadecimal string starting with 0x. hex() does not output in 2 digit form ``` hex(1) '0x1' ``` You can use ord() convert a single char to an int and pass it to hex() ``` hex(ord("A")) '0x41' ``` To remove the 0x from the string do ``` '%x' % ord("Z") '5a' ``` To remove the 0x and convert to upper case two characters do ``` # create a hex string a = ord("Z") b = hex(a) # now convert the string to int c = int(b,16) # and format '%02X' % c 5A # or as one line '%02X' % int(hex(ord("Z")),16) ``` Here's an example reading bytes from an address ``` from ReadWriteMemory import ReadWriteMemory rwm = ReadWriteMemory() process = rwm.get_process_by_name('binary.exe') process.open() thebytes = process.readByte(0x188F280,1000) process.close() ``` readByte returns a list of hexadecimal strings These can be converted to readable two character space separated hexadecimal with: ``` allbytes = "" for x in thebytes: allbytes += "{:02X} ".format(int(x,16)) allbytes = allbytes.rstrip() print(allbytes) ```