Skip to content

Commit db7059c

Browse files
Merge pull request tuomasjjrasanen#7 from goncalopp/master
Add option to create a device with an existing uinput file descriptor
2 parents 0313d09 + 47fd9b2 commit db7059c

2 files changed

Lines changed: 30 additions & 2 deletions

File tree

examples/drop_privileges.py

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
import uinput
2+
3+
def drop_privileges(uid_name='nobody', gid_name='nogroup'):
4+
#https://stackoverflow.com/questions/2699907/dropping-root-permissions-in-python
5+
import os, pwd, grp
6+
if os.getuid() != 0:
7+
return
8+
running_uid = pwd.getpwnam(uid_name).pw_uid
9+
running_gid = grp.getgrnam(gid_name).gr_gid
10+
os.setgroups([])
11+
os.setgid(running_gid)
12+
os.setuid(running_uid)
13+
old_umask = os.umask(077)
14+
15+
16+
def main():
17+
uinput_fd= uinput.Device.create_uinput_fd()
18+
drop_privileges() #no need to be root beyond this line
19+
20+
events = (uinput.KEY_A,)
21+
with uinput.Device(events, fd=uinput_fd) as device:
22+
device.emit_click(uinput.KEY_A)
23+
24+
if __name__ == "__main__":
25+
main()

src/__init__.py

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -80,6 +80,9 @@ def _error_handler(result, fn, args):
8080
raise RuntimeError("unexpected return value: %s" % result)
8181
return result
8282

83+
def fdopen():
84+
return _libsuinput.suinput_open()
85+
8386
_libsuinput_path = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "_libsuinput" + sysconfig.get_config_var("SO")))
8487
_libsuinput = ctypes.CDLL(_libsuinput_path, use_errno=True)
8588
_libsuinput.suinput_open.errcheck = _open_error_handler
@@ -162,7 +165,7 @@ class Device(object):
162165
"""
163166

164167
def __init__(self, events, name="python-uinput",
165-
bustype=0, vendor=0, product=0, version=0):
168+
bustype=0, vendor=0, product=0, version=0, fd=None):
166169
self.__events = events
167170
self.__uinput_fd = -1
168171
self.__name = name.encode()
@@ -172,7 +175,7 @@ def __init__(self, events, name="python-uinput",
172175
user_dev.id.vendor = vendor
173176
user_dev.id.product = product
174177
user_dev.id.version = version
175-
self.__uinput_fd = _libsuinput.suinput_open()
178+
self.__uinput_fd = fd or fdopen()
176179
for ev_spec in self.__events:
177180
ev_type, ev_code = ev_spec[:2]
178181
_libsuinput.suinput_enable_event(self.__uinput_fd, ev_type, ev_code)

0 commit comments

Comments
 (0)