Print numerical permissions of files

Today I needed a way to print the numerical permission of files (instead of rwx) and I found this solution:

For multiple files:

ls -l |awk ‘{k=0;for(i=0;i<=8;i++)k+=((substr($1,i+2,1)~/[rwx]/)*2^(8-i));if(k)printf(“%0o “,k);print}’

Which gives this result:

[root@OptimusPrime selinux]# ls -l |awk ‘{k=0;for(i=0;i<=8;i++)k+=((substr($1,i+2,1)~/[rwx]/)*2^(8-i));if(k)printf(“%0o “,k);print}’
total 32
644 -rw-r–r– 1 root root  511 Jan  7  2012 config
600 -rw——- 1 root root  234 Apr  2  2010 restorecond.conf
644 -rw-r–r– 1 root root 1752 Sep  3  2009 semanage.conf
755 drwxr-xr-x 5 root root 4096 Jan 26 17:51 targeted
[root@OptimusPrime selinux]#

For single file:

ls -l /etc/hosts |awk ‘{k=0;for(i=0;i<=8;i++)k+=((substr($1,i+2,1)~/[rwx]/)*2^(8-i));if(k)printf(“%0o “,k);print}’

Result:

[root@OptimusPrime ~]# ls -l /etc/hosts |awk ‘{k=0;for(i=0;i<=8;i++)k+=((substr($1,i+2,1)~/[rwx]/)*2^(8-i));if(k)printf(“%0o “,k);print}’
644 -rw-r–r– 2 root root 308 Feb 11 18:37 /etc/hosts
[root@OptimusPrime ~]#

You may wondering why I was searching for this? The reason was simple. This article is the solution if you need to modify a file on a list of servers, where this particular file has different permissions on each server (sometimes write permission is missing), you can easily save the old permissions, change them temporary, as you wish (like 777) and then change them back.

 

Let me give you an example. You need to modify file /etc/program.conf on 50 servers found in servers.txt. The scenario is the one described above and the solution would be this one:

for i in `cat servers.txt`
do
    #saving the old permissions
    OLDPERM=`ssh -i ~/.ssh/key user@$i sudo ls -l /etc/program.conf |awk ‘{k=0;for(i=0;i<=8;i++)k+=((substr($1,i+2,1)~/[rwx]/)*2^(8-i));if(k)printf(“%0o “,k);print}’ |awk ‘{print $1}’`
    #temporary change of permissions
    ssh -i ~/.ssh/key user@$i sudo chmod 777 /etc/hosts
    #make the change (in this case add new line to the conf file)
    ssh -i ~/.ssh/key user@$i “/bin/echo \”New test parameter\” >> /etc/program.conf”
    #set the permissions back as they were
    ssh -i ~/.ssh/key user@$i sudo chmod $OLDPERM /etc/hosts
done

That would be all.