Demoting a Python Subprocess - python

Is it possible to have a main Python process run as root, but then start a Python subprocess (multiprocessing) run as a different user? I also want that user's home directory and shell settings to apply just like if the Python interpreter had been started by that user.
Right now, when using os.setuid and gid, the permissions are correct, but the home directory is still incorrect as you'd expect:
>>> import os
>>> os.setgid(1000)
>>> os.setuid(1000)
>>> print os.getuid()
1000
>>> print os.getgid()
1000
>>> f = open('/etc/shadow')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IOError: [Errno 13] Permission denied: '/etc/shadow'
>>> os.system('echo $HOME')
/root
0
Any ideas?

Try:
os.environ['HOME'] = '/home/blah'
os.system("ls ~")
AFAIK, this is as good as you are likely to get, because installations with network home directories, or users with bash profiles that set HOME to wacky values aren't going to be replicable in pure Python, and could have side effects.

Related

Permissions denied using i for i in open

Here is the code I've got:
filename = 'C:\\Users\chnyr\Desktop\Python Programs'
var = [i for i in open(filename, 'r+')]
['1\n', '2\n', '3\n', '\n']
I keep getting an error message below. I am using pyCharm v3.8.
C:\Users\chnyr\anaconda3\envs\untitled3\python.exe "C:/Users/chnyr/PycharmProjects/untitled3/translate test.py"
Traceback (most recent call last):
File "C:/Users/chnyr/PycharmProjects/untitled3/translate test.py", line 9, in <module>
var = [i for i in open('C:\\Users\chnyr\Desktop\Python Programs', 'r+')]
PermissionError: [Errno 13] Permission denied: 'C:\\Users\\chnyr\\Desktop\\Python Programs'
Process finished with exit code 1
You get the error is you are trying to open a folder using the open() method. You can only open files with the method.
In python (and a lot of other languages) \ is the escape character.This makes coding with windows filesystems rather tricky. You have to escape each escape, by doing \\ instead of\. Aside from this, like Ann zen said, open only works with files. What you probably want is glob.glob, from the glob module.
import glob
var = [i for i in glob.glob('C:\\Users\\chnyr\\Desktop\\Python Programs\\*.py')]
print(var)
a = []
for i in var:
a.append(open(i,'r+'))

Python desktop Cleaner - Access Deined

Recently I found a program that cleans your folders. This is the coding.
import os
import shutil
lis=[]
destinationDir='C:\Users\Owner\All in two'
os.makedirs(destinationDir)
lis=os.listdir('C:\Users\Owner\My Documents')
for x in lis:
if x==__file__:
continue
shutil.move(x,destinationDir)
When I try to run it though, it gives an error saying:
Traceback (most recent call last):
File "C:\Users\Owner\Desktop\Cleaner.py", line 6, in <module>
lis=os.listdir('C:\Users\Owner\My Documents')
WindowsError: [Error 5] Access is denied: 'C:\\Users\\Owner\\My Documents/*.*'
I tried using cmd in admin but it failed.
All advice is appreciated.
Make sure you have the appropriate permissions on your computer!
Right click on the folder (My documents or a folder inside) and look in security, if you have all the permissions with a tick box in, then this error shouldn't occur!
Basically, if you're not admin or can't access my documents, then you can't run it!
Hope this helps XD

python3 error when passing variable into os.chdir

I am trying to find a specific pathname and pass this into os.chdir so I can run a command in that directory. I won't know the exact pathname hence why I have to run the find command. I have tried several ways to do this and each comes with a new error. The code below is one of the ways I have tried, can anyone suggest the best way to do this? Or how to fix this error?
Source Code:
import os
import subprocess
os.system('find ~ -path "*MyDir" > MyDir.txt')
output = subprocess.check_output("cat MyDir.txt", shell=True)
os.chdir(output)
os.system("file * > MyDir/File.txt")
The error:
Traceback (most recent call last):
File "sub1.py", line 8, in <module>
os.chdir(output)
FileNotFoundError: [Errno 2] No such file or directory: b'/Users/MyhomeDir/Desktop/MyDir\n'
I know that directory exists and presume it has something to do with the b' and \n'. I just don't know what the problem is.
Get rid of the \n with strip:
output = subprocess.check_output("cat MyDir.txt", shell=True).strip()
os.chdir(output)

libtorrent-python problems, "no such file or directory" when there clearly is

First of all, here's the code
#!/usr/bin/env python3.4
import libtorrent as lt
import os
fs = lt.file_storage()
lt.add_files(fs, "/var/mirror/packages/") # There are two files in this directory
t = lt.create_torrent(fs, flags = 1&8&16) # 1 = Optimization, 8 = Symbolic links, 16 = calculate file hashes.
t.add_tracker("udp://tracker.[private].com:80")
print(os.path.isdir("/var/mirror/packages/"))
lt.set_piece_hashes(t,"/var/mirror/packages/")
print(t.generate())
And here's what happens when I run it
True
Traceback (most recent call last):
File "./test.py", line 9, in <module>
lt.set_piece_hashes(t,"/var/mirror/packages/")
RuntimeError: No such file or directory
This is the page I got this from
I have browsed around the bindings, but I can't find the set_piece_hashes sources. It returns the same error code when I change the path to "." or "/" (keeping the add_files path the same)
Anyone know what I'm doing wrong? I can't find any sort of documentation other than the site I linked above
Turns out set_piece_hashes wants the parent directory of the directory you created the filestore with. After I fixed that, I now get another error, which is a known bug in libtorrent here

Python: Run Script Under Same Window

I am trying to setup a program where when someone enters a command it will run that command which is a script in a sub folder called "lib".
Here is my code:
import os
while 1:
cmd = input(' >: ')
for file in os.listdir('lib'):
if file.endswith('.py'):
try:
os.system(str(cmd + '.py'))
except FileNotFoundError:
print('Command Not Found.')
I have a file: lib/new_user.py But when I try to run it I get this error:
Traceback (most recent call last):
File "C:/Users/Daniel/Desktop/Wasm/Exec.py", line 8, in <module>
exec(str(cmd + '.py'))
File "<string>", line 1, in <module>
NameError: name 'new_user' is not defined
Does anyone know a way around this? I would prefer if the script would be able to be executed under the same window so it doesn't open a completely new one up to run the code there. This may be a really Noob question but I have not been able to find anything on this.
Thanks,
Daniel Alexander
os.system(os.path.join('lib', cmd + '.py'))
You're invoking new_user.py but it is not in the current directory. You need to construct lib/new_user.py.
(I'm not sure what any of this has to do with windows.)
However, a better approach for executing Python code from Python is making them into modules and using import:
import importlib
cmd_module = importlib.import_module(cmd, 'lib')
cmd_module.execute()
(Assuming you have a function execute defined in lib/new_user.py)

Categories