OSError: [Error 1] Operation not permitted - python

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.

Related

Getting an output from Python that gets executed by PHP

So my issue is that I have an AWS EC2 instance running Ubuntu server 18.04 and Apache2, when a button is pressed it posts some variables which are passed to a function which then uses shell_exec() to execute a Python script. The Python script then takes these variables (direction and angle) as command line arguments, it will then attempt to write then to a file called cmds.txt. When doing this however I get this error reported back to me:
Traceback (most recent call last):
File "/home/server/cmdWriter.py", line 45, in
main()
File "/home/server/cmdWriter.py", line 41, in main
servoCmds(direction, angle)
File "/home/server/cmdWriter.py", line 28, in servoCmds
cmdFile = open("cmds.txt", "a")
PermissionError: [Errno 13] Permission denied: 'cmds.txt'
After some looking I think this is because PHP executes as user "www-data" which doesn't have write privileges, so after looking at other questions I tried settung up permissions so that www-data has read and write privilages to the folder and the python file. For whatever reason this does not work! I've been pulling my hair out trying to get this to work, trying suggestions from several other questions, can anyone help me here?
You are getting the error with respect to 'opening' the file. You have to make sure that the permissions on the .txt file are at 755 or higher. If the server you are using is Linux, then you have two alternatives to modify the permissions:
If you have cPanel, you can use the cPanel interface and just change permissions by going to the file, click on Change Permissions and then set the permissions to 777.
or
From the linux command line, use chmod command - like this:
chmod 777 cmds.txt
I can't speak to the security issues associated with same without knowing more.
The other possibility is that you are using the 'a' mode, but the file does not already exist. If you are not certain the file exists when the command is executed, you may try 'a+' as that will create the file if one does not already exist.
Does that work?

File paths within my Python script fail when launching via double-click (Windows 10)

I have a python script that reads and writes to files that are located relative to it, in directories above and beside it. When I run my script via Cygwin using
python script.py
The program works perfectly. However, when I run it by navigating through the windows GUI to my file and double clicking, I get a blank cmd prompt and then my program runs fine until I reach the point where I need to access the other files, at which point it fails and gives me this message in the cmd prompt that opens itself:
../FFPRM.TXT
../2025510296/FFPRM_000.TXT
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\rbanks\AppData\Local\Programs\Python\Python35-32\lib\tkinter\__init__.py", line 1549, in __call__
return self.func(*args)
File "C:\Users\rbanks\Desktop\TSAC\EXECUTABLE\T-SAC_GUI.py", line 705, in run_exe
invalid_entry, output_text = self.apply()
File "C:\Users\rbanks\Desktop\TSAC\EXECUTABLE\T-SAC_GUI.py", line 694, in apply
p = subprocess.Popen(['cp', output_file_path, output_file_path_id])
File "C:\Users\rbanks\AppData\Local\Programs\Python\Python35-32\lib\subprocess.py", line 950, in __init__
restore_signals, start_new_session)
File "C:\Users\rbanks\AppData\Local\Programs\Python\Python35-32\lib\subprocess.py", line 1220, in _execute_child startupinfo)
FileNotFoundError: [WinError 2] The system cannot find the file specified
I am deploying this script as well as the directory structure as a zip for users to be able to unzip and use anywhere on their PC, so it is important for me to be able to run it with a simple double click and my relative file paths.
My first thought was the cmd prompt that was opening and executing my script was in a different environment, but when I run:
cd
pause
in a .cmd script, I get:
C:\Users\rbanks\Desktop\TSAC\EXECUTABLE>pause
Which is the correct location.
I am not having any luck with Google, I assume because I can't seem to construct a sufficient search query. Could someone point me in the right direction please?
[edit] the other answer is correct(at least i suspect) but i will leave this here in the hopes that it helps the op in the future with path problems ... and doing something like this is just generally good practice
use
BASEPATH = os.path.abspath(os.path.dirname(__file__))
at the top of your script
the later
txt_file = os.path.join(BASEPATH,"my_file.txt")
or even
txt_file = os.path.join(BASEPATH,"..","my_file.txt")
this gives you the benefit of being able to do things like
if not os.path.exists(txt_file):
print "Cannot find file: %r"%txt_file
which will likely give you a better idea about what your problem might actually be (if its simply path related at least)
The problem is not the current directory. It is correct when double clicking on the icon
The problem is: Cygwin commands are not in the windows path
You are using python, so don't run simple copy commands like this, which make your script non-portable and subject to variations, requiring installation of cygwin, etc...
p = subprocess.Popen(['cp', output_file_path, output_file_path_id])
can be replaced by
import shutil
shutil.copyfile(output_file_path, output_file_path_id)
shutil module complements os module for file manipulation functions that aren't native in the operating system.
now you have a 100% pythonic solution, native, which will throw exceptions if cannot read/write files, so fully integrated in the rest of your program.
Before running an external command from Python make sure that no python way exists. There are so many useful modules out there.
Other examples of how to avoid running basic commands from python (of course if you need to run a C compilation it's different!):
zipfile package: much better than running zip.exe
gzip package: can open gzipped files natively from python
os.listdir() instead of parsing the output of cmd /c dir /B
os.remove() instead of calling rm or del
etc... python rules!

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

No such file or directory - Python

ANSWERED! THANKS EVERYONE!
I'm trying to get my script to run, however I'm getting this error. I'm not brilliant with Python, so any form of basic explanation would be appreciated.
Microsoft Windows [Version 6.1.7601]
Copyright (c) 2009 Microsoft Corporation. All rights reserved.
C:\Users\Brad>c:\python27\python.exe c:\python27\vsauce.py
ERROR:root:Error opening settings.json.
Traceback (most recent call last):
File "c:\python27\vsauce.py", line 76, in loadSettings
settingsFile = open("settings.json", "r")
IOError: [Errno 2] No such file or directory: 'settings.json'
The line in question
settingsFile = open("settings.json", "r")
Yes, the file exists. Yes, it is named "settings.json" exactly. I can't for the life of me figure out what the hell I have done wrong. This is not my script by the way.
Thanks in advance for any help!
try
$ cd C:\Python27
$ python.exe vsauce.py
this will move you to Python27 directory. so it will look there for settings.json
since you ran it from C:\Users\Brad it was looking for C:\Users\Brad\settings.json
The reason your script isn't working is because you're running it from C:\Users\Brad, so when
settingsFile = open("settings.json", "r")
runs, it looks for settings.json in the directory the script was run from, not the directory the script is stored in. You either need to hardcode the path the settings.json in your .py file, or you need to run the script from the C:\Python27 directory. To do this, after starting cmd.exe, enter
cd c:\Python27
python vsauce.py
Try opening while writing out the full directory. It may be that your current working directory is not the same as where the file is. By default when you use "open" python looks for files wherever you ran the program from. Such as 'C:\Users\Brad... whatever'. You need to change the directory if the file is saved elsewhere
settingsFile = open('C:\\Users\\Brad\\Documents\\PythonFiles\\YourDirectory\\settings.json', 'r')

Cannot copy file from a remote machine using shutil

I need to copy a file from a remote machine.
The code is something like this
import shutil
shutil.copyfile('//XXX.XXX.XXX.XXX/home/Shares Folder/file.txt','/home/file.txt')
the location of the file is a shared folder but everytime I run this it gives me this error
File "", line 1, in ?
File "usr/lib/python2.4/shutil.py", line 47, in copyfile
frsc = open (src,'rb')
IOError: [Errno 2] No such file or directory :
'//XXX.XXX.XXX.XXX/home/Shares Folder/file.txt'
Please take note that I'm running this script in my current machine and the the file that I want to copy is in the remote machine. I am not sure if this detail's relevant, I'm saying anyway.
Im 100% sure that the file is there so I was wondering why it's giving me such error message.
Im using CentOS and python 2.4.3
any ideas?
shutil doesn't support remote file copies. It's for local copies only.
If both of your machines are UNIX-based, you can try and employ some modules for a transport that you have available (SSH/SFTP, rsync, whanot)
You've also tagged with samba and shared-folders - if you're trying to copy via samba, you might want to look into pysmbc or a similar python samba library. http://pypi.python.org/pypi/pysmbc/ even has an example of opening and reading a file over samba - it's a short step to writing the contents out locally.

Categories