Linux / Python如何以非root用户的身份导入根访问py模块?

Linux/Python How do I import a root access py module as a non-root user?

I'm trying to keep passwords that are usually written in a py file separated from the script and make it so that those passwords are only accessible by root and python whenever a script needs it. I got the idea reading this: https://stackoverflow.com/a/158248/3892678

To do this, I'm trying to hide passwords to be used in a_script in another passwords py file. passwords can only be read, written, and executed (-rwxrwx---)by root:root. As another user tomato, I want to run a_script, which imports the password from passwords to be used in the file. To make it so that this user can run the file as root, I've elevated the file's setuid and setgid withchmod 6777 a_script.py so that the file has -rwsrwsrwx permissions. Now, as user tomato, I run python a_script.py, but I get back ImportError: No module named passwords. I thought that setting the uid and groupid as s would run the file as root, which should have permissions to read passwords. What am I doing wrong?

Here's a_script.py

import os
print "uid: %s" % os.getuid()
print "euid: %s" % os.getgid()
print "gid: %s" % os.geteuid()
print "egid: %s" % os.getegid()
from passwords import MYPASS

print MYPASS

All the print statements before I get the ImportError are 1001 which is tomato. Thanks for your help. Might there be a better way to "hide" passwords in another file so that only root and programs that need it are the only ones that have access to it?

how bout

os.popen("echo ROOT_PASSWORD | sudo -s -p '' cat /path/to/secure/file.txt").read()

(note its probably better to use the subprocess module ... but it requires more typing)

Didn't really work. It got hung up trying to run that command as my tomato user, but with my other user thats listed in sudoers it worked okay. Not quite what I want though, but thanks.