Change file permanently to read-only using Python - python

I want to change a file to be permanently read-only and tried the solutions provided creating-read-only-pdf-file-using-python and change-file-to-read-only-mode-in-python.
However, in both cases it was still possible to edit the file and manually change it back to a read-only file.
Is there a way to prevent that, so that nobody could edit the properties or content of the file?
I thought about encrypting it, i.e. using SHA256 with a randomly created key, but that would render the file unreadable.

Is there a way to prevent that, so that nobody could edit the properties or content of the file?
No. As long as the file is on a writable device, it's always possible for a user to delete the file and replace it with a modified copy.
(And even if the file is on an immutable device, like a CD-ROM, the user can still create a modified copy of the entire device.)

If you are one a Unix-like system you can use the chmod command in the terminal.
The chmod command has an equivalent in python
You might have to run your script is super-user to change some permissions.

Related

Restrict the Python file to read and write

I'm trying to restrict write and read access to a Python file. Suppose I have the following code:
with open('test.py', 'w+') as file:
file.write('''
open("document.txt", "w+").write("Hello, World!")
open("document.txt", "r+").read()
''')
By executing this code, a new file is created that in the new file there are two lines of code to write and read a another file.
I want the file created by executing this code (test.py) to hit PermissionError while running and not be able to create a new file or read it; Also, this file is only executable and normal commands work in it, but it can not access other files.
If I read you correctly, this is not a python problem, but an environment problem. I understand the question as something like 'how do I prevent python code from executing arbitrary reads or writes?'. There would be a trivial solution (modifying the generated test.py so it throws an error) but presumably that's not what you want.
The easiest way to make python hit a PermissionError... is to make sure it doesn't have permissions. So run your code as a user with extremely limited permissions---specifically no write permissions anywhere---or perhaps no default permissions at all, and use something like facls to grant permission to read specific files explicitly from a more priveleged sentinel process. (This assumes you are running Linux, but there are likely other ways to do this in different OSs).
Alternatively, look into various sandboxing techniques to give you a python interpreter with the relavent modules replaced with modules which throw errors, or an environment where outside modification is impossible.
It would help if you made it clearer why this is important, and why you are writing a python script with another python script (is this just an example of malicious action?).
You could technically change the permission of the file itself on the filesystem your trying to access.
Check the previous thread about changing permissions
os.chmod(path, <permission value>)
Where 000 is to disable anyone other than root to edit on linux.

Python save file permissions & owner/group and restore later

I have the following problem.
I need to replace a file with another one. As far as the new is transfered over the network, owner and group bits are lost.
So I have the following idea. To save current permissions and file owner bits and than after replacing the file restore them.
Could you please suggest how to do this in Python or maybe you could propose a better way to achieve this.
You can use rsync facility to copy the file to remote location with same permissions. A simple os.system(rsync -av SRC <DEST_IP>:~/location/) call can do this. Another methods include using a subprocess.

Best way to accept permanent input from a user?

I have a script which has a global variable that must be set by the user once and for all, the variable is a string containing a pathname, and each time the script runs it needs it. I don't want to prompt the user each time for this pathname.
Currently, I am considering asking the user to a set an environment variable permanently, by adding it to his /etc/profile or .bash_profile, and access it with sys.environ dictionary. The other option would be to have a config file and ask the user to edit the relevant line, then use configparser to read it.
Is there a recommended method for doing this?
Use the Python ConfigParser module, or configparser in Python 3.
It follows the standard *.ini format and allows you to store information from one run to the next in an easily readable format. The format is essentially self-documenting because you can name your keys in the file, and you can add comments to the configuration file too.
It also provides more flexibility over the environment variable method because it is easier to modify a configuration file, and the file can easily be passed from one computer to the next along with your script regardless of platform or other environment settings.
Your use case is exactly what configuration files are intended for, and you could accomplish your task with only a handful of lines of code:
cfg_parser = ConfigParser.ConfigParser() # Python 2.x
if cfg_parser.read('config_file_name.ini'):
path = cfg_parser.get('SECTION_NAME', 'path')
else:
print("No config file found")
This gives you your path, and all you have to ask your user to do is edit one line of a text file instead of making any system changes.
Additionally, this gives you a lot of room to expand in the future. If you ever want more options added to your script, modifying a configuration file is a lot easier than coming up with new environment variables.
Lastly, the ConfigParser library allows you to edit configuration files programmatically as well. You could add a command line option (perhaps with argparse) that allows your user to specify a path, and have your script automagically write its own config file with the path. Now your user never has to touch the configuration file manually, and will never have to add the path on the command line again either. Even better, if the path ever changes, your user can just run it with the command line path option again and voila, the old path in the config file is overwritten and the new one is saved.
I would definitely recommend the configuration file approach due to its flexibility and user-friendliness.

How to write to a read-only file in Python

Is there a way to write to a read-only file in Python? I am trying to write a script which helps me add debug statements at the start of every function in a given file. But the issue I have is that before I run the script, I have to manually remove the read-only flag on the file. is there anyway I can write to read-only files without manually having to remove them? Any suggestions will be deeply appreciated. Thanks.
If the user that runs the script doesn't have permissions to write in a file, you can't edit it. Basically, you need to have the w permission to edit a file. See Linux file permissions for more information.
If you want to get rid of it, you should make the file writable directly, or try to change its chmod with the os module, if you have enough permission to do this:
>>> os.chmod('path_to/file', 0755)
Try os.chmod() before opening the file.

Creating read only text files with python

Is it possible to create read only files in python which can not be changed later and in which users can not change its attribute from read-only to normal file?
Please suggest.
Thanks in advance.
This is not python specific.
If the files are made by a different user that the one viewing it the script can make it read-only. As the file is owned by the python user, the viewing user cannot just change the attributes.
So it's very much an OS question, and not a Python question.
Oh, and there is no way to prevent an administrator changing the file, or for the file to be readable but not copyable.
This is just impossible.
Any user with administrative rights can remove readonly restrictions of any kind.
Another option might be "Write a python program to kill all users over the worls so that they would not be able to change file attributes or security settings" :-)
Take a look at os.chmod() function and execute it with appropriate parameters (filename, stat.S_IWUSR | stat.S_IRGRP | stat.S_IROTH) for your just created file.
On linux other users then you will not be able to change file or change attributes to writable.
Some root user or someone logged into you account will be able to change it though.

Categories