How can I import file as normal user in python?

I have a python app that run bash shell commands that require root priviledges. In terminal I type “sudo python3 main.py” then load python app file. Python app run mostly sudo commands so I always have to run it with sudo python3 main.py. In the main.py file in the beginning I have import settings.py file that save some important settings. settings.py file read and write INI File in home folder /home/username/.config/myapp/config.ini. So when I run the main.py app the settings.py create a folder myapp inside /home/username/.config/ and then create the config.ini filename.

The problem is tha because I run the main.py app with sudo the folder myapp and config.ini file created with root owner. How can I avoid that?

I would like to import whole file settings.py as normal user.

main.py

#!/usr/bin/python3
import os
import sys
import subprocess
import settings

....
....

settings.py

import configparser

# Create directory
dirName = '/home/username/.config/myapp'

# Create target directory & all intermediate directories if don't exists
try:
    os.makedirs(dirName)
    print("Directory ", dirName, " Created ")
except FileExistsError:
    print("Directory ", dirName, " already exists")

filename = "/home/username/.config/myapp/config.ini"

# Writing Data
config = configparser.ConfigParser()
config.read(filename)

try:
    config.add_section("ethernet")
except configparser.DuplicateSectionError:
    pass

config.set("ethernet", "wired", "")
config.set("ethernet", "wired_mac_address", "")

try:
    config.add_section("wifi")
except configparser.DuplicateSectionError:
    pass

config.set("wifi", "wireless", "")
config.set("wifi", "wireless_mac_address", "")

with open(filename, "w") as config_file:
    config.write(config_file)

# Reading Data
config.read(filename)
keys = [
    "wired",
    "wired_mac_address"
]
for key in keys:
    try:
        value = config.get("ethernet", key)
        print(f"{key}:", value)
    except configparser.NoOptionError:
        print(f"No option '{key}' in section 'ethernet'")

# Reading Data
config.read(filename)
keys = [
    "wireless",
    "wireless_mac_address"
]

for key in keys:
    try:
        value = config.get("wifi", key)
        print(f"{key}:", value)
    except configparser.NoOptionError:
        print(f"No option '{key}' in section 'wifi'")

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

One approach is to use os.chown() method in the built-in os module. Using this method you can save, create, and edit files and directories as the root user and then change the ownership immediately afterwards to whatever user you want.

import os  #  <---  import the module
import configparser

# change this to the UID of the user you
# want owning the files/directories
uid = 1000 # non-privileged user
ugid = 1000  # non-priveleged user's group


# Create directory
dirName = '/home/username/.config/myapp'

# Create target directory & all intermediate directories if don't exists
try:
    os.makedirs(dirName)
    os.chown(dirName, uid, ugid)
    print("Directory ", dirName, " Created ")
except FileExistsError:
    os.chown(dirName, uid, ugid)
    print("Directory ", dirName, " already exists")

filename = "/home/username/.config/myapp/config.ini"

if os.path.exists(filename):
    os.chown(filename, uid, ugid)  

# Writing Data
config = configparser.ConfigParser()
config.read(filename)

try:
    config.add_section("ethernet")
except configparser.DuplicateSectionError:
    pass

config.set("ethernet", "wired", "")
config.set("ethernet", "wired_mac_address", "")

try:
    config.add_section("wifi")
except configparser.DuplicateSectionError:
    pass

config.set("wifi", "wireless", "")
config.set("wifi", "wireless_mac_address", "")

with open(filename, "w") as config_file:
    config.write(config_file)  # <--- write the file as root
os.chown(filename, uid, ugid)  # <--- change ownership 

# Reading Data
config.read(filename)
keys = [
    "wired",
    "wired_mac_address"
]
for key in keys:
    try:
        value = config.get("ethernet", key)
        print(f"{key}:", value)
    except configparser.NoOptionError:
        print(f"No option '{key}' in section 'ethernet'")

# Reading Data
config.read(filename)
keys = [
    "wireless",
    "wireless_mac_address"
]

for key in keys:
    try:
        value = config.get("wifi", key)
        print(f"{key}:", value)
    except configparser.NoOptionError:
        print(f"No option '{key}' in section 'wifi'")

Just run that same method os.chown(path, uid, gid) anytime you create a new file or folder as root, and it will change the ownership to a non-privileged user of your choice.

Hopefully this helps.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x