Executing Shellcode with Python

This week will be about executing shellcode with Python, so that I can cover another Python script from my tools collection, as well as keep up the variety of posts.

So, normally an easy way to test shellcode is inside a simple C application, like the following.

char code[] = "shellcode";

int main(int argc, char **argv)
  int (*func)();
  func = (int (*)()) code;

But, sometimes I don't have access to a compiler, feel like using Python instead of C, or just want to learn something new.

After some research and learning, I found the following code. Note that this will only work on Windows at the moment due to needing the ctypes windll library.

import ctypes

# Shellcode
# x86/shikata_ga_nai succeeded with size 227 (iteration=1)
# Metasploit windows/exec calc.exe
shellcode = bytearray(
ptr = ctypes.windll.kernel32.VirtualAlloc(ctypes.c_int(0),
buf = (ctypes.c_char * len(shellcode)).from_buffer(shellcode)
ht = ctypes.windll.kernel32.CreateThread(ctypes.c_int(0),

While not the most game-changing script, it was definitely fun to find, and I could see myself using it every once in awhile in the future.

As before, the code and updates can always be found in my GitHub repository as well.

For more information, please see the following post.

doyler on Githubdoyler on Twitter
Ray Doyle is an avid pentester/security enthusiast/beer connoisseur who has worked in IT for almost 16 years now. From building machines and the software on them, to breaking into them and tearing it all down; he's done it all. To show for it, he has obtained an OSCE, OSCP, eCPPT, GXPN, eWPT, eWPTX, SLAE, eMAPT, Security+, ICAgile CP, ITIL v3 Foundation, and even a sabermetrics certification!

He currently serves as a Senior Staff Adversarial Engineer for Avalara, and his previous position was a Principal Penetration Testing Consultant for Secureworks.

When he's not figuring out what cert to get next or side project to work on, he enjoys playing video games, traveling, and watching sports.

As an Amazon Associate I earn from qualifying purchases.

Common passed on this blog, I made it to a jam.


Filed under Security Not Included

2 Responses to Executing Shellcode with Python

  1. Tenadi Bhebhe

    Thank you for the tutorial Mr Doyle but how do you inject shellcode into a remote machine on a network

Leave a Reply

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

ERROR: si-captcha.php plugin: GD image support not detected in PHP!

Contact your web host and ask them to enable GD image support for PHP.

ERROR: si-captcha.php plugin: imagepng function not detected in PHP!

Contact your web host and ask them to enable imagepng for PHP.

This site uses Akismet to reduce spam. Learn how your comment data is processed.