Auto Screen Lock With Suspend and Resume in i3 With Systemd

Auto Screen Lock With Suspend and Resume in i3 With Systemd

After using i3-wm, formally known as i3-gaps, for several years on my personal workstation I have not really needed to use the i3lock features that often due to my workstation being in my office where no one else touches it. right They wouldn’t know how to use it in they did try and mess with my workstation. But now that I am using my same i3 config across more systems including my work computer where I now use it manage and maintain the network and servers of my work, I began looking for ways to make my computer more secure. 

This also was brought up by the fact that I had lost my Dell Latitude Rugged 5420 laptop in the area where I work. I had placed the laptop on a tow-behind manlift and forgot about and drove off. I believe someone had found it and picked it up as we have had more traffic in our area due to new wells being drilled. My laptop had the i3lock function enabled but the locking mechanism was random and would only truly work if the laptop was left with the lid open for 10 mins. Sometimes it would suspend via lid closing but that never was a guarantee.

Which brings me to needing a system that works correctly when the lid is opened and closed. And say what you will about systemd but in this case I have grown to like it more due to its simplicity and ability to work correctly. 

suspend@.service

First we need to edit the file in systemd to start suspend when lid is closed. Add the line that is in red. Change the directory to where your script resides.

$ sudo vim /etc/systemd/system/suspend@.service
[Unit]
Description=User suspend actions
Before=sleep.target
  
[Service]
User=%I
Type=forking
Environment=DISPLAY=:0
ExecStart=/home/wretchedghost/.config/i3/lock_and_blur.sh
[Install]
WantedBy=sleep.target

Let’s next enable now the suspend service.

$ sudo systemctl enable --now suspend@empty.service

resume@.service

Next, we need to edit the resume file when the lid is opened back up. Again add only the red line. Change the directory to where your script resides.

$ sudo vim /etc/systemd/system/resume@.service
[Unit]
Description=Lock the screen on resume from suspend
[Service]
User=%I
Environment=DISPLAY=:0
ExecStart=/home/wretchedghost/.config/i3/lock_and_blur.sh
[Install]
WantedBy=suspend.target

Again enable the resume service. Do not add the –now here but we will need to do a reboot before the service will take effect. Also don’t forget to change it to your username.

$ sudo systemctl enable resume@wretchedghost.service