9

Trying to translate linux cmd to python script

Linux cmds:

chmod 777 file1 file1/tmp file2 file2/tmp file3 file3/tmp

I know of os.chmod(file, 0777) but I'm not sure how to use it for the above line.

heemayl
  • 39,294
  • 7
  • 70
  • 76
Xandy
  • 155
  • 2
  • 2
  • 9
  • Whatever you are hoping to accomplish, **`chmod 777` is *wrong* and *dangerous.*** You absolutely do not want to grant write access to executable or system files to all users under any circumstances. You will want to revert to sane permissions ASAP (for your use case, probably `chmod 755`) and learn about the Unix permissions model before you try to use it again. If this happened on a system with Internet access, check whether an intruder could have exploited this to escalate their privileges. – tripleee Nov 29 '21 at 11:44

3 Answers3

17

os.chmod takes a single filename as argument, so you need to loop over the filenames and apply chmod:

files = ['file1', 'file1/tmp', 'file2', 'file2/tmp', 'file3', 'file3/tmp']
for file in files:
    os.chmod(file, 0o0777)

BTW i'm not sure why are you setting the permission bits to 777 -- this is asking for trouble. You should pick the permission bits as restrictive as possible.

heemayl
  • 39,294
  • 7
  • 70
  • 76
  • Ahh, thank you. I was thinking there was some hidden level to chmod. I'm just translating a process already in place. Thanks!! – Xandy Mar 15 '18 at 20:24
0

If you want to use pathlib, you can use .chmod() from that library

from pathlib import Path

files = ['file1', 'file1/tmp', 'file2', 'file2/tmp', 'file3', 'file3/tmp']
for file in files:
    Path(file).chmod(0o0777)
edesz
  • 11,756
  • 22
  • 75
  • 123
-1

chmod 777 will get the job done, but it's more permissions than you likely want to give that script.

It's better to limit the privileges to execution.

I suggest: chmod +x myPthonFile.py

benhorgen
  • 1,928
  • 1
  • 33
  • 38
  • 1
    It is slightly hard to parse, but the question is asking how to do it within Python. – otocan May 26 '22 at 15:40
  • Good point. `chmod` is generally executed pre-script from a command-line/console. In retrospective, my answer is not helpful in regards to straight python code. But you can execute console commands from python to get the job done. But of course that script would need to be executed with root/admin privileges in order to execute the `chmod` – benhorgen May 26 '22 at 19:14