Restore executable permission of chmod command using Python

Default permission of chmod command provided below

[root@localhost ~]# ls -l /bin/chmod
-rwxr-xr-x 1 root root 58656 /bin/chmod

chmod has executable permission by default, hence chmod can be executed to change permission of other files in Linux system

Assume a scenario where chmod command lost its executable permission, like the below

[root@localhost ~]# chmod -x /bin/chmod

[root@localhost ~]# ls -l /bin/chmod
-rw-r--r-- 1 root root 58656 Oct 30  2018 /bin/chmod
[root@localhost ~]#

The command available for changing file permission in linux system is chmod, now it has lost its executable permission

Since chmod command become non executable, then think about the way to provide or restore executable permission for chmod command.

[root@localhost ~]# chmod +x /bin/chmod
-bash: /usr/bin/chmod: Permission denied 

[root@localhost ~]# touch /tmp/testfile
[root@localhost ~]# chmod +x /tmp/testfile
-bash: /usr/bin/chmod: Permission denied

Solution:

Python is famous for containing rich standard libraries, which can be used for several operating system level functionalities along with programming and scripting.

Let us use python for providing executable permission for chmod command

[root@localhost ~]# python -c "import os; os.chmod('/bin/chmod', 0755)"
[root@localhost ~]# ls -l /bin/chmod
-rwxr-xr-x 1 root root 58656 /bin/chmod

Now the chmod command has got executable permission with the help of python os library.
As chmod command became executable, now it can be used for changing file permissions

[root@localhost ~]# chmod +x /tmp/testfile
[root@localhost ~]# ls -l /tmp/testfile
-rwxr-xr-x 1 root root 0 Jun  3 10:32 /tmp/testfile

Python uses Linux Posix interface, hence it is independently works with out any support needed from Linux commands like chmod.

Post a Comment

1 Comments