Hi all,
I have a very weird problem, which seems to have to do with the interaction between the os module and serial module.
So, I was programming a daemon to log a serial port device, but I can't let it run as root because of some shared filesystem properties, so I made a user and ran the thing as this user, works fine. Next step was to use os.setgid and os.setuid to switch from root to this particular user, and voila, I can't open the serial port anymore, but the files I log to are opened from the right user.
OK, I attach some sample code showing the behaviour using the daemon module from:
http://hathawaymix.org/Software/Sketches/daemon.py
(and no it's not this module, also my own crappy code did the same thing and gives the same erroneous behaviour)
---------------------
#!/usr/bin/python
"""Test daemon"""
import daemon
import logging
import time
import serial
import os
class HelloDaemon(daemon.Daemon):
default_conf = 'test.conf'
section = 'test'
def setup_user(self):
print os.getuid(), os.getgid()
ser=serial.Serial(0)
print ser.portstr
ser.close()
def run(self):
while True:
logging.info('The daemon says hello')
time.sleep(1)
if __name__ == '__main__':
HelloDaemon().main()
-----------------------------------------
now make the config file:
--------------------------------
[test]
uid =
gid =
pidfile = ./hellodaemon.pid
logfile = ./hellodaemon.log
loglevel = info
----------------------
when I run it as my own user it works fine, e.g.:
tjp@machine$ ./test.py
1000 1000
/dev/ttyS0
it nicely opens the port.
if I fill in tjp for uid and gid in the configfile and run it as:
tjp@machine$ sudo ./test.py
1000 1000
Traceback (most recent call last):
File "./test.py", line 26, in <module>
HelloDaemon().main()
File "/home/tjp/tmp/pydaemon/daemon.py", line 121, in main
self.start()
File "/home/tjp/tmp/pydaemon/daemon.py", line 196, in start
self.setup_user()
File "./test.py", line 17, in setup_user
ser=serial.Serial(0)
File "/usr/lib/python2.6/dist-packages/serial/serialutil.py", line 166, in __init__
self.open()
File "/usr/lib/python2.6/dist-packages/serial/serialposix.py", line 175, in open
raise SerialException("could not open port %s: %s" % (self._port, msg))
serial.serialutil.SerialException: could not open port 0: [Errno 13] Permission denied: '/dev/ttyS0'
Either I am not smart enough to do things right, or something is wrong. Then the quenstion is, is it the serial module? or is it the os module?
I hope someone can help me out.
Yours, Tjeerd
So it was me not doing the right thing. The group list is not populated with all the member groups on os.setuid. Setting the grouplist with os.setgroups (adding the groups for file and serial port access) before calling os.setuid solved the problem.