OS = Ubuntu Server
I have no idea for the best way to do this and would appreciate any pointers.
I’m using an SBC (orange pi 5b) and PWM support is broken using wiringpi.
I can execute the following commands when logged in as root to create a 50Hz square wave on pin 2
echo 0 > /sys/class/pwm/pwmchip5/export
echo 20000000 > /sys/class/pwm/pwmchip5/pwm0/period
echo 1000000 > /sys/class/pwm/pwmchip5/pwm0/duty_cycle
echo 1 > /sys/class/pwm/pwmchip5/pwm0/enable
I cannot execute the same commands in a user account using sudo or change permissions for the pwmchip5 directory
What I would like to achieve is to create a daemon/service/api/rpc (preferably in Python but I have a little skill in c) that runs as root (using crontab on boot or as a service) and that any non-root user can send it commands like
pwmservice init pwmchip5
pwmservice period pwmchip5 20000000
pwmservice duty_cycle pwmchip5 1000000
pwmservice enable pwmchip5
without having to be root or using sudo. Note that these last 4 commands would get the service to execute the bash commands above as root
is this possible and could someone point me in the right direction. Also, would something like this work or is there a better way.
https://betterprogramming.pub/a-simple-way-to-make-rpcs-with-python-52ad8e9286c1
cheers
2
Answers
This worked
install the python rpc library
log in as root and create the following server.py file
This can be automatically started at boot and as root using crontab
Then use the following snippet as the regular non root user
This creates a 50Hz where the pwm arguments are (pin, period, duty_cycle)
I think this is more of a Linux permissions question than a programming question, but nevertheless:
You could use
ls -l
to determine the group-owner of the files in/sys/class/pwm/...
, for example, this might be groupgpio
. Then add all users who need to execute those commands to that group withadduser username gpio
. Maybe you need some udev rules to set up the group ownership first.Or you could write a small C program for this, compile it, and then put the compiled binary in
/usr/local/bin/pwmcontrol
with SETGID to thegpio
group, or whichever group owns the control files 1. Then it will always run with the rights of that group. Note that SETGID (and SETUID) only works with a compiled program, not with a script.Here’s some C code to get you started, including error handling.
1 Of course, you could also use SETUID root (
chown root
+chmod u+s
), but running something as root is dangerous. Especially if it is a C program that you wrote yourself without any idea of how C security exploits work.