Skip to content

Instantly share code, notes, and snippets.

@jstaursky
Last active July 21, 2024 15:15
Show Gist options
  • Save jstaursky/618ab94ccad035a235914bfa26b9d993 to your computer and use it in GitHub Desktop.
Save jstaursky/618ab94ccad035a235914bfa26b9d993 to your computer and use it in GitHub Desktop.
cmdline keystone assembler
#!/usr/bin/env python3
from keystone import *
import sys
import argparse
import binascii
def main(filename=None, raw=False):
if filename is None:
print("No file specified.")
exit()
if filename != None:
try:
# Initialize engine in X86-32bit mode
with open(filename, "r") as f:
buf = f.read()
ks = Ks(KS_ARCH_X86, KS_MODE_32)
encoding, count = ks.asm(buf)
if raw:
with open(sys.stdout.fileno(), "wb") as output:
output.write(bytes(encoding))
else:
print(f"Assembling file: {filename}")
print(f"hex: {binascii.hexlify(bytes(encoding))}")
except KsError as e:
print("ERROR: %s" % e)
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument(
"-f",
"--filename",
type=str,
help="The path to the assembly file to be assembled.",
)
parser.add_argument(
"-r",
"--raw",
action="store_true",
help="Whether to output the raw encoded binary.",
)
args = parser.parse_args()
main(**vars(args))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment