Allow non-root user to read/write /dev files

devicespermissionsudev

In my /dev folder, I would like the following files to be user readable and writable:

/dev/ttyUSB0
/dev/gpib0

How do I do this without using chgrp? I can edit /etc/udev/rules.d but I do not know the syntax.

Best Answer

How udev rules are structured

For devices falling into subsystem tty, you can set their group as follows:

SUBSYSTEM=="tty", GROUP="dialout"

Note that, just like in common programming, == is a test for equality while = is an assignment. So, the above statement translates to "if SUBSYSTEM=="tty" then assign GROUP="dialout". A statement may have multiple tests, which are and-ed together, and multiple assignments.

If you wanted to change the read-write-execute permissions, then assign MODE instead of GROUP where MODE follows the usual Unix octal notation, e.g. MODE="0660" gives the owner and the group read-write permissions. man udev has all the details.

You can find many examples of such rules in /lib/udev/rules.d/91-permissions.rules

How to add a udev rule to your system

Once you have settled on what you want your rule to be, it is simple enough to add it. On a debian-derived system, go to the directory /etc/udev/rules.d and create a file. Files are run in sort-order. So, to make your rules file the last to be read, overriding earlier ones, try a name like 99-instruments.rules. Then put your rules in that file, one per line. (If need by, lines can be extended by putting a backslash at the end of the line, just like in shell.)

So, if you want to change group and permissions on tty devices, your file /etc/udev/rules.d/99-instruments.rules could consist of the single line:

SUBSYSTEM=="tty", GROUP="dialout", MODE="0660"

To assure that your new file itself has the usual permissions:

sudo chown root:root /etc/udev/rules.d/99-instruments.rules
sudo chmod 0644 /etc/udev/rules.d/99-instruments.rules

After you have created your file, udevd may automatically read it. If not, you can force it re-read its files with:

udevadm control --reload-rules

More on how udev classifies devices

If you want to get finer control over which devices respond to which rules, you can learn more about how udev sees your devices by perusing /sys/. At this moment, I don't have access to a machine with a ttyUSB or an HPIB, so let's make an example of disk sda. Run:

udevadm info --attribute-walk --path=/sys/block/sda

This gives a lot of information that looks like:

. . . .
KERNEL=="sda"
SUBSYSTEM=="block"
DRIVER==""
ATTR{range}=="16"
ATTR{ext_range}=="256"
ATTR{removable}=="0"
. . . .

These lines are all in the form suitable for using as if clauses in rules. So, for example, to change the ownership on all block devices that are marked as non-removable, we would use the rule:

SUBSYSTEM=="block", ATTR{removable}=="0", OWNER=john1024

With information from udevadm, one can develop rules that can target specifically the devices of interest.

Related Question