1

file = open('/etc/shadow', 'r') print(file)

getting error like this file = open('/etc/shadow', 'r') IOError: [Errno 13] Permission denied: '/etc/shadow'

Poke
  • 11
  • 1
  • 2
  • 6

2 Answers2

1

On most systems /etc/shadow is owned by root with rw permissions.

$ ls -la /etc/shadow

-rw------- 1 root root 692 Jun 10 19:24 /etc/shadow You need to either:

  1. Change the permissons (don't do this it is not safe) but you could this by running 'chmod o+r /etc/shadow' as root. This will give the 'other' users read rights to
  2. Run your program as root. Either by a. Starting it as root su -c 'python myPython.py' //you will be asked to provide the root password.

    b. Starting it with sudo [1] sudo python myPython.py this all depends on you sudo configuration but is your best bet other then just starting python as root.

Also an example to call sudo from within python[5].

c. Set setuid bit on the program [2] This will most likely not work as Python is an interpreted language and most modern Unix systems will disallow (exception being Perl) setuid on interpreted programs as opposed to compiled/binaries.

chown root programName # Set owner to be root

chmod +s programName # This gives the program itself the right to run as root.

Regardless of whom starts it.

[1]http://en.wikipedia.org/wiki/Sudo

[2]http://en.wikipedia.org/wiki/Setuid

[3]Open a file as superuser in python

[4]Setuid bit on python script : Linux vs Solaris

[5]Using sudo with Python script

The problem is not with the source code or python. But with not having the correct file system rights to the '/etc/shadow' file.

Community
  • 1
  • 1
1

In python 3 you can do:

import spwd
spwd.getspnam('username')

More information about the spwd module can be found here: https://docs.python.org/3/library/spwd.html#module-spwd

Bill DeRose
  • 2,330
  • 3
  • 25
  • 36
Andreas
  • 85
  • 1
  • 13