derikl

patch_string.py

Sep 27th, 2025
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.14 KB | None | 0 0
  1. #!/usr/bin/env python3
  2. # patch_string.py
  3. import sys
  4.  
  5. if len(sys.argv) < 4:
  6.     print("Usage: python3 patch_string.py <file> <old_string> <new_string>")
  7.     sys.exit(1)
  8.  
  9. fn=sys.argv[1]
  10. old=sys.argv[2]
  11. new=sys.argv[3]
  12.  
  13. data=open(fn,"rb").read()
  14.  
  15. def patch_bytes(orig_bytes, new_bytes, suffix_label):
  16.     i = data.find(orig_bytes)
  17.     if i == -1:
  18.         print(f"{suffix_label}: pattern not found.")
  19.         return None
  20.     if len(new_bytes) > len(orig_bytes):
  21.         print(f"{suffix_label}: new string longer ({len(new_bytes)}) than old ({len(orig_bytes)}). Aborting.")
  22.         return None
  23.     padded = new_bytes + b'\x00'*(len(orig_bytes)-len(new_bytes))
  24.     newdata = data[:i] + padded + data[i+len(orig_bytes):]
  25.     out = fn + ".patched"
  26.     open(out,"wb").write(newdata)
  27.     print(f"{suffix_label}: patched and wrote {out} (offset 0x{i:x})")
  28.     return out
  29.  
  30. # ASCII
  31. old_a = old.encode('ascii',errors='ignore')
  32. new_a = new.encode('ascii',errors='ignore')
  33. patch_bytes(old_a,new_a,"ASCII")
  34.  
  35. # UTF-16LE
  36. old_u = old.encode('utf-16le',errors='ignore')
  37. new_u = new.encode('utf-16le',errors='ignore')
  38. patch_bytes(old_u,new_u,"UTF-16LE")
Advertisement
Add Comment
Please, Sign In to add comment