Access Denied when entering value in windows registry by Python

Asked

Viewed 529 times

1

In an attempt to create a function that inserted a value in a windows registry key, I came across an error. I use Windows 8 and Python 3.5. The function is as follows:

def inserir1(nome,path):
    import winreg
    key=winreg.OpenKey(winreg.HKEY_CURRENT_USER,'Software\\Microsoft\\Windows\\CurrentVersion\\Run')
    winreg.SetValueEx(key,nome,0,winreg.REG_SZ,path)
    key.Close()

inserirchave('teste','C:\\Users\\Usuario\\Desktop\\teste.txt')

The error this script generates is as follows::

Traceback (most recent call last):
  File "C:\Users\Usuario\Desktop\Inserir Chave.py", line 16, in <module>
    inserir1(nome,path)
  File "C:\Users\Usuario\Desktop\Inserir Chave.py", line 8, in inserir1
    winreg.SetValueEx(key,nome,0,winreg.REG_SZ,path)
PermissionError: [WinError 5] Acesso negado

So I tried to run the script with administrator privileges, but without success, as the same error occurred even with such privileges. I tried to do manually by regedit and there was no problem at all. How can I get permission to run this script?

  • How did you perform the process in Adm mode? You opened the CMD with the right and chose "Run as Administrator"?

  • I did it in two ways: I opened cmd as administrator by right-clicking mouse and typed python inserirchave.py; the other way was by opening python itself as administrator, also by right-clicking (in this case, I typed line by line)

1 answer

1

Try this way:

def inserir1(nome,path):
  key = OpenKey(HKEY_CURRENT_USER, 'Software\Microsoft\Windows\CurrentVersion\Run', 0, KEY_ALL_ACCESS)
  key = CreateKey(HKEY_CURRENT_USER, keyVal)
  SetValueEx(key, nome, 0, REG_SZ, path)
  CloseKey(key)

inserir1('teste','C:\Users\Usuario\Desktop\teste.txt')
  • 1

    Edit: Remove the line key = CreateKey(HKEY_CURRENT_USER, keyVal)

  • I tried to do what you proposed, and it initially went wrong. However, I tried to run as an administrator and apparently it had worked, as no errors appeared. However, the test.txt value did not show up in the Run key, which means it didn’t work but it didn’t. If you have any more ideas, thank you.

  • I’ll try to work on one you suggested, meanwhile, @carlos.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.