Creating read only text files with python - 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.

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.

Change file permanently to read-only using 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.

Python creating a text file that the user can't edit

On Python, I was wondering if there was a simple way to create a text file which can't be edited by the user and can only be edited once, by the computer.
I want to use this so that I can make a User ID for a user that cannot be changed. Does anyone have a solution?
If there is any security reason why the UserID shouldn't be changed then you need to store the information on your own server.
If you don't want it to be easy, but don't mind it being possible, then you could either change the file permission on the file, encrypt the file in some way so that it's not easy to edit by the user, or hide it by prefixing the name with a . so that it doesn't automatically appear in the explorer window.

Python: Code for program to add itself to start up (Windows)

I found that a program needs to add itself to %ALLUSERSPROFILE%\Start Menu\Programs\Startup for it to start up automatically. But how would I do this not knowing the person's user profile?
Also, I read something about the program being added to the system registry? How would I do that?
I found this code to copy the file
os.rename("path/to/current/myfile.exe", "path/to/new/desination/for/myfile.exe")
But I don't know the path to current file. Everyone has a different username so /Bob/Downloads will not be where the file is located and I don't know what %ALLUSERSPROFILE% name will be on their computer.
Caveat: I'm testing this on Windows 7; it should also work on other Windows but I can't promise.
The values for %ALLUSERSPROFILE% and %USERPROFILE% are in os.environ.
If your code is running as the user who downloaded it, you can therefore do something like:
import os
aup = os.environ.get("ALLUSERSPROFILE")
up = os.environ.get("USERPROFILE")
if aup and up:
os.rename(os.path.join(up,"Downloads","myfile.exe")),os.path.join(aup,"Start menu","Programs","startup","myfile.exe"))
else:
print("Oops, couldn't look up stuff in os.environ")
Note that I don't think there's an easy way to get another user's profile; if you're running on a desktop and are running as say alice but want to get bob's directory, you can presumably cheat and do
alt_user_profile = os.path.join(up,"..","bob")
(i.e. assume that the users are all in the same parent directory); if you're running somewhere in which user profiles are not all in the same parent, you might need to look into a Windows specific API. (And of course, there may be permissions issues with trying to reach into another user's stuff)

How to check if a file can be created inside given directory on MS XP/Vista?

I have a code that creates file(s) in user-specified directory. User can point to a directory in which he can't create files, but he can rename it.
I have created directory for test purposes, let's call it C:\foo.
I have following permissions to C:\foo:
Traversing directory/Execute file
Removing subfolders and files
Removing
Read permissions
Change permissions
Take ownership
I don't have any of the following permissions to C:\foo:
Full Control
File creation
Folder creation
I have tried following approaches, so far:
os.access('C:\foo', os.W_OK) == True
st = os.stat('C:\foo')
mode = st[stat.ST_MODE]
mode & stat.S_IWRITE == True
I believe that this is caused by the fact that I can rename folder, so it is changeable for me. But it's content - not.
Does anyone know how can I write code that will check for a given directory if current user has permissions to create file in that directory?
In brief - I want to check if current user has File creation and Folder creation permissions for given folder name.
EDIT: The need for such code arisen from the Test case no 3 from 'Certified for Windows Vista' program, which states:
The application must not allow the Least-Privileged user to save any files to Windows System directory in order to pass this test case.
Should this be understood as 'Application may try to save file in Windows System directory, but shouldn't crash on failure?' or rather 'Application has to perform security checks before trying to save file?'
Should I stop bothering just because Windows Vista itself won't allow the Least-Privileged user to save any files in %WINDIR%?
I recently wrote a App to pass a set of test to obtain the ISV status from Microsoft and I also add that condition.
The way I understood it was that if the user is Least Priveledge then he won't have permission to write in the system folders. So I approached the problem the the way Ishmaeel described. I try to create the file and catch the exception then inform the user that he doesn't have permission to write files to that directory.
In my understanding an Least-Priviledged user will not have the necessary permissions to write to those folders, if he has then he is not a Least-Priveledge user.
Should I stop bothering just because Windows Vista itself won't allow the Least-Privileged user to save any files in %WINDIR%?
In my opinion? Yes.
I wouldn't waste time and LOCs on checking for permissions. Ultimate test of file creation in Windows is the creation itself. Other factors may come into play (such as existing files (or worse, folders) with the same name, disk space, background processes. These conditions can even change between the time you make the initial check and the time you actually try to create your file.
So, if I had a scenario like that, I would just design my method to not lose any data in case of failure, to go ahead and try to create my file, and offer the user an option to change the selected directory and try again if creation fails.
I agree with the other answers that the way to do this is to try to create the file and catch the exception.
However, on Vista beware of UAC! See for example "Why does my application allow me to save files to the Windows and System32 folders in Vista?": To support old applications, Vista will "pretend" to create the file while in reality it creates it in the so-called Virtual Store under the current user's profile.
To avoid this you have to specifically tell Vista that you don't want administrative privileges, by including the appropriate commands in the .exe's manifest, see the question linked above.
import os
import tempfile
def can_create_file(folder_path):
try:
tempfile.TemporaryFile(dir=folder_path)
return True
except OSError:
return False
def can_create_folder(folder_path):
try:
name = tempfile.mkdtemp(dir=folder_path)
os.rmdir(name)
return True
except OSError:
return False

Categories