Search code examples
pythonwindowspython-2.7registry

Python Registry Persistence


I’m trying to make a python script that is persistent within the windows environment. I am using PyInstaller to create an exe. I have managed to get this script only to function on the Windows XP environment and not on any other versions of windows. I can move the exe to the %temp% folder, however It will not write to "Software\Microsoft\Windows\CurrentVersion\Run" within the registry. I’d love to have you guys give me your opinions on the code. Is there a more efficient way to write to the registry?

import sys, base64, os, socket, subprocess
from _winreg import *

def autorun(tempdir, fileName, run):
# Copy executable to %TEMP%:
    os.system('copy %s %s'%(fileName, tempdir))

# Queries Windows registry for the autorun key value
# Stores the key values in runkey array
    key = OpenKey(HKEY_LOCAL_MACHINE, run)
    runkey =[]
    try:
        i = 0
        while True:
            subkey = EnumValue(key, i)
            runkey.append(subkey[0])
            i += 1
    except WindowsError:
        pass

# If the autorun key "helloworld" isn't set this will set the key:
    if 'helloworld' not in runkey:
        try:
            key= OpenKey(HKEY_LOCAL_MACHINE, run,0,KEY_ALL_ACCESS)
            SetValueEx(key ,'helloworld',0,REG_SZ,r"%TEMP%\hello.exe")
            key.Close()
        except WindowsError:
            pass

def hello():
    print "hello world"

def main():
    tempdir = '%TEMP%'
    fileName = sys.argv[0]
    run = "Software\Microsoft\Windows\CurrentVersion\Run"
    autorun(tempdir, fileName, run)
    hello()

if __name__ == "__main__":
        main()

Solution

  • The thing with writing to registry is that you may find you need to be running the application as Administrator. This could be why you have different performances in different environments.

    If you are not strictly bound to the registry, you could try using pickle to save information between sessions. This has the benefit of being cross platform.