Python won't overwrite 777 file - python

I have a script that is outputting the pid. I change permissions to 777. Every subsequent instance will overwrite this file with the new pid. Despite the 777 permissions, python reports an OS Error that the operation is not permitted unless the user executing the script is the owner of the file. (I can delete/overwrite the file from the shell, of course).
#!/usr/bin/python
import os
import time
f = open("/tmp/test.txt", 'w')
f.write("Hello, file!\n")
os.chmod("/tmp/test.txt", 0777)
f.close()
$ /tmp/myscript.py # fine
$ sudo -u other_user /tmp/myscript.py #not fine -- gives error

In Linux, only the user who created the file or root can change its permissions. If the file doesn't exist when you call open, you are the owner of the new file and can change its permissions. When the file already exists, it's just truncated and the existing permissions are still in effect. It would be reasonable to just catch and ignore the error because it only happens after the permissions were setup correctly.
If you have the proper permissions in the parent directory, you can delete the file and create a new one each time. But that doesn't work for /tmp because the sticky bit is set and only owner can delete the file.

$ /tmp/myscript.py creates a file owned by you.
and $ sudo -u other_user /tmp/myscript.py means other_user is going to change the file permission owned by you.
same as the following situation:
account1$ touch /tmp/test.txt
account1$ chmod 777 /tmp/test.txt
su account2
account2$ chmod 777 /tmp/test.txt
#chmod: changing permissions of `test.txt': Operation not permitted

Related

Permission denied on shutil.move on image files

I am trying to move some files around. I can move any extension type except .png, .jpg, or .gif. When I try to move those types of files I get "IOError: [Errno 13] Permission denied" even though I am the admin. Code below
import os, glob, shutil
dir = r'C:\\Users\\jcan4\\Desktop\\testmove\\*'
print(dir)
files = glob.glob(dir)
files.sort(key=os.path.getmtime)
for i, file in enumerate(files, start=1):
print(file)
oldext = os.path.splitext(file)[1]
shutil.move(file, 'Attachment-%s' % (i) + oldext)
First things first, you're double escaping your dir variable:
print(r'C:\\Users\\jcan4\\Desktop\\testmove\\*')
# Yields 'C:\\\\Users\\\\jcan4\\\\Desktop\\\\testmove\\\\*' !!
# What you really meant was either one of the following:
dir_harderToRead = 'C:\\Users\\jcan4\\Desktop\\testmove\\*'
dir_easyToRead = r'C:\Users\jcan4\Desktop\testmove\*'
If you are still experiencing the error, it's because you are not giving the python script permissions to move the file. There are a couple ways to get around this:
Windows
(This applies to the asked question)
Open command prompt (I see your file path and am assuming you're on windows) with administrative rights. (see here)
Change ownership of the images to you. (see here for windows 10 or here for windows 7)
Linux (MacOS)
(This applies to people on Linux that may have the same problem)
Run the python script with root privileges:
# At command line
sudo python your_script_name.py
Change ownership of file to yourself:
# At command line
# Changes ownership of entire directory (CAREFUL):
chmod 755 /absolute/path/to/dir
chmod 755 relative/path/to/dir
# Or you can change file by file:
chmod 755 /absolute/path/to/file
chmod 755 relative/path/to/file
For more info, I used this site on permissions. (If someone has a numerical value than 755 for chmod please say so.)

how to read binary file with administrator privileges using strictly python in linux

So I'm trying to read a config file which needs to be "sudo'd" into but I'm trying to read its contents using python only without using terminal. when I use the code below I get the error as shown:
with open('/etc/motion/motion.conf','rb') as file:
data = file.readlines()
IOError: [Errno 13] Permission denied: '/etc/motion/motion.conf'
Is there anything I could try to read the contents of the file strictly with python?
You should call your python file from a shell script, change the owner of this script to be root and then set the SUID bit of this script. The user will be able to run the script but the owner of the script will be root:
http://www.codecoffee.com/tipsforlinux/articles/028.html
http://www.linuxnix.com/2011/12/suid-set-suid-linuxunix.html
etc.
Of course you must be aware of security issues that may be involved by such a thing but for local use with a simple script doing one thing, it's OK.
Permission denied means that you have no permission to read that file.
If you're on Linux, you should change the file's permission use chmod command. Or you can use sudo comand run python like this:
sudo python filename.py
or login as root then run python:
su - root
python filename.py
And if you want run the program as root every times, you can use os.execlpe() function like this:
import os
import sys
euid = os.geteuid()
if euid != 0:
args = ['sudo', sys.executable] + sys.argv + [os.environ]
os.execlpe('sudo',*args)
with open('/etc/motion/motion.conf','rb') as file:
data = file.readlines()
print data
This solution is from here:
authentication in python script to run as root
and is courtesy of #samplebias

OSError: [Error 1] Operation not permitted

I am trying to run a python script which uses a binary file (xFiles.bin.addr_patched) created by a postlinker. However, I am getting this error.
File "abc.py", line 74, in ParseCmd
shutil.copy(gOptions.inputX, gWorkingXFile)
File "/usr/lib/python2.6/shutil.py", line 89, in copy
copymode(src, dst)
File "/usr/lib/python2.6/shutil.py", line 66, in copymode
os.chmod(dst, mode)
OSError: [Errno 1] Operation not permitted: 'myPath/xFiles.bin.addr_patched'
When I checked the permissions of this xFiles.bin, by ls-l, it shows that
-rwxrwxrwx 1 nobody nogroup
I presume the error is because this file was created by some other application, the python script I am running does not have access to it. Since I am beginner wrt ubuntu, I don't really know how to fix it. Any suggestions on how to fix this?
SOLVED:
As one of the answers Suggested : chown username:groupname file name fixes this issue
You could try (from the command line, but I'm sure there's a syntax in python):
sudo chown your_username:your_groupname filename
Note: The group is usually just your username.
I feel like there's something wrong with those permissions though. Read Write Execute for everyone seems to be off. How was this file created? How did it get to be created by the user nobody?
Python code to change the permission:
from getpwnam import pwd
from getgrnam import grp
import os
uid = getpwnam("YOUR_USERNAME")[2]
gid = grp.getgrnam("YOUR_GROUPNAME")[2]
os.chown("myPath/xFiles.bin.addr_patched", uid, gid)
Run the script with sudo and you're done.
I had this problem when running a python script on my mac (10.14 Mojave) trying to access /Users/xxx/Pictures/Photos Library.photoslibrary.
The full solution can be found in http://osxdaily.com/2018/10/09/fix-operation-not-permitted-terminal-error-macos/
Summary:
Go to System Preferences > Security & Privacy > Privacy > Full Disk Access and add your IDE or python interpreter to the list.
My guess is that you should be looking at the permissions for myPath folder instead. Seems like you can't write to it, hence the problem. Try ls -l myPath/.. and see the permissions for myPath. If that's the problem, change the permissions on the folder with chmod.
P.S. Also, see Google top result on Linux file permissions.

Python CGI permissions error

I can't seem to open and write to a text file from my CGI script.. I keep getting permissions errors (which I see from CGITb)
Whenever I try to do this:
f = open("/Users/varatis/Documents/data.txt","a+")
I get this:
<type 'exceptions.IOError'>: [Errno 13] Permission denied: '/Users/varatis/Documents/data.txt'
args = (13, 'Permission denied')
errno = 13
filename = '/Users/varatis/Documents/data.txt'
message = ''
strerror = 'Permission denied'
Ideally, I'd want to create the text file. But to make things easier for the server, I've tried making things easier by making a premade data.txt, and running the usual:
chmod a+x data.txt
chmod a+w data.txt
chown 70 data.txt (70 is the uid the server runs on, obtained by os.getuid from the os module)
however, these don't even seem to work. Does anyone have experience with this and can help me? Again, ideally I'm appending to the text file from the CGI script and creating it if it doesn't exist.
Also, maybe of use will be the ls -la for the data.txt:
-rwxrwxrwx# 1 _www staff 0 Mar 12 16:18 data.txt
Very likely your webserver doesn't have permissions to write to that specific directory.
If it's an apache then you might want to fiddle around with 'Directory' directive.
update:
What are the permissions on the Documents directory?

Running Python script as root (with sudo) - what is the username of the effective user?

I've recently began using ConfigParser() for my python scripts to add some functionality to them for config files. I know how to use it but I have a problem. My script needs to run as the root user, using sudo. The config files are in ~/.config/scriptconfig/ but when you run a script as sudo it temporarily changes users to root, so it doesn't find the config files. What I want to do is get the config file of the effective user so it grabs /home/myuser/.config/scriptconfig/config.cfg instead of /root/.config/scriptconfig/config.cfg, which doesn't exist.
I need the script to be able to run on different machines, not just mine. So I need to get the home directory of the effective user
Here is an example of the code I'm trying to use:
import os, ConfigParser
config = ConfigParser.RawConfigParser()
homepath = os.path.expanduser("~/")
configpath = homepath + ".config/scriptconfig/config.cfg"
config.read(configpath)
get = config.get('Config', 'Example')
print get
It should print the value of example from the config file but when ran as sudo, the path is /home/root so it doesn't find the config file.
If you run your script with sudo (sudo myscript.py) then the environment variable $USER will be root and the environment variable $SUDO_USER will be the name of the user who executed the command sudo myscript.py. This following is simply a clarification of the previous post by Cédric Julien. Consider the following scenario:
A linux user bob is logged into the system and possesses sudo privileges. He writes the following python script named myscript.py:
#!/usr/bin/python
import os
print os.getenv("USER")
print os.getenv("SUDO_USER")
He then makes the script executable with chmod +x myscript.py and then executes his script with sudo privileges with the command:
sudo ./myscript.py
The output of that program will be (using python 2.x.x):
root
bob
If bob runs the program sans sudo privileges with
./myscript.py
he will get the following output:
bob
None
if you want to get the user that was logged in before launching the sudo command, it is stored in the SUDO_USER environment variable.
import os
sudo_username = os.getenv("SUDO_USER")
home_dir = "/home/" + sudo_username
You also have the SUDO_UID and SUDO_GID for the user id and group id.
This doesn't work.
homepath = os.path.expanduser("~/")
So don't use it.
You want this.
username= os.environ["LOGNAME"]
homepath = os.path.expanduser("~"+username+"/")
http://docs.python.org/library/os.html#os.getlogin
Or perhaps this.
username= pwd.getpwuid(os.getuid())[0]
homepath = os.path.expanduser("~"+username+"/")

Categories