当我插入外部硬盘时,我试图解密 LUKS 分区。因此,我使用以下内容配置了 udev 规则:
ACTION=="add", KERNEL=="sdb1", SUBSYSTEM=="block", ATTR{size}=="1048576000", RUN+="/home/user/myfile.sh
myfile.sh 脚本:
password=`su - user -c 'export DISPLAY=:0;kdialog --password "Decrypt HDD"'`
sleep 5
echo "$password" | cryptsetup luksOpen /dev/sdb1 backups
mount /dev/mapper/backups /media/backups/
脚本通过读取密码对话框,解密分区并挂载后。如果我手动运行它就可以了。问题是当我插入USB时,对话框已启动,但在脚本完成之前不会检测到 /dev/sdb1 加密分区。因此 cryptsetup luksOpen 和 mount 不会执行任何操作(因为在检测到加密分区之前启动)...
The file with the udev rules is 90-crypt.rules in /etc/udev/rules.d
答案1
Finally I found the problem. With RUN you can not execute long programs/scripts. And the solution is create a service that run your script and use the rule SYSTEMD_WANTS with your service.
From man udev:
RUN{type} Add a program to the list of programs to be executed after processing all the rules for a specific event, depending on "type":
"program"
Execute an external program specified as the assigned value. If no absolute path is given, the program is expected to live in /lib/udev; otherwise, the absolute path must be specified.
This is the default if no type is specified.
"builtin"
As program, but use one of the built-in programs rather than an external one.
The program name and following arguments are separated by spaces. Single quotes can be used to specify arguments with spaces.
This can only be used for very short-running foreground tasks. Running an event process for a long period of time may block all further events for this or a dependent device.
Starting daemons or other long-running processes is not appropriate for udev; the forked processes, detached or not, will be unconditionally killed after the event handling has finished.
Note that running programs that access the network or mount/unmount filesystems is not allowed inside of udev rules, due to the default sandbox that is enforced on systemd-udevd.service.
Solution:
Create a service in /etc/systemd/system/myservice.service>
[Unit]
Description=Auto backup
[Service]
ExecStart=/home/manu/Sysadmin/auto-backup.sh
And change the udev rule:
ACTION=="add", KERNEL=="sdb1", SUBSYSTEM=="block", ATTR{size}=="1048576000", ENV{SYSTEMD_WANTS}="myservice.service"