Search code examples
pythonpython-3.xvirtualboxprivileges

Access virtualbox VMs as root


I have VMs created as normal user. I can access them via the GUI and via python bindings (pyvbox). I have a python script that I need to run as root to access other ressources. I cannot access any VMs via the GUI nor python bindings as root. How can I access them from my script ?

Should I drop privileges from my script ran as root whenever I need to access vbox ? and then go back to root user when i need to access other resources ? How would you do this and is it a good idea ?


Solution

  • I found a solution that requires the name of the user for which you want to monitor VMs:

    import os, pwd, virtualbox
    
    vbox_user="my_user"
    pw=pwd.getpwnam(vbox_user)
    root_uid=os.getuid()
    
    # change location of vbox settings file
    os.environ["XDG_CONFIG_HOME"]="/home/{}/.config".format(vbox_user)
    
    # change uid to user's
    # setting euid alone does not work
    os.setresuid(pw.pw_uid, pw.pw_uid, uid)
    
    # create your vbox 
    vbox=virtualbox.VirtualBox()
    
    # change back to initial uid
    os.setresuid(uid, uid, uid)
    
    

    You can use vbox exactly like you would as vbox_user.