Skip to content

Instantly share code, notes, and snippets.

@zhanglongqi
Last active December 23, 2024 03:31
Show Gist options
  • Save zhanglongqi/de6e41bce762d4810914ef8035c92bae to your computer and use it in GitHub Desktop.
Save zhanglongqi/de6e41bce762d4810914ef8035c92bae to your computer and use it in GitHub Desktop.
Prevent Linux from going to suspend/sleep when ssh connections are on.
#!/bin/sh
#
# Put this file to /etc/pm/sleep.d/
# chmod +x /etc/pm/sleep.d/99_ssh_keep_awake.sh
#
#
# Thanks to https://askubuntu.com/questions/521620/prevent-machine-from-sleeping-when-ssh-connections-are-on
#
ip=`w -h | awk '{print $1,$2,$3}' | grep -oE '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}'`
if [ -z $ip ]; then
exit 0
else
echo User is still logged from $ip
exit 1
fi
@bitwombat
Copy link

Seems that $3 is the correct field, in Ubuntu 22.04's version of 'w' at least.

@zhanglongqi
Copy link
Author

Seems that $3 is the correct field, in Ubuntu 22.04's version of 'w' at least.

for my ubuntu 22.04.3 LTS, $4 is the correct one.

@ooge0
Copy link

ooge0 commented Dec 19, 2024

@zhanglongqi , thanks for script.
I found that your regepx
ip=w -h | awk -F' ' '{print $4}' | grep -oE '[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}'``
is not working on 24.04.1 LTS (Noble Numbat)

I used
ip=$(echo "$w_output" | grep -oP '(\d{1,3}\.){3}\d{1,3}')
and ip address was discovered.

@zhanglongqi
Copy link
Author

@zhanglongqi , thanks for script. I found that your regepx ip=w -h | awk -F' ' '{print $4}' | grep -oE '[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}'`` is not working on 24.04.1 LTS (Noble Numbat)

I used ip=$(echo "$w_output" | grep -oP '(\d{1,3}\.){3}\d{1,3}') and ip address was discovered.

Thanks. I have updated it and tested on both of ubuntu 24.04 and 22.04 😄

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment