Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/env python
- from os import kill
- from signal import SIGKILL
- from subprocess import Popen, PIPE, STDOUT
- from sys import argv, exit
- from time import sleep
- """
- Newton Smartt
- April 15, 2012
- Written for use on Arch Linux. It should be simple to modify it for your purposes.
- It's written for python 2.7. It must be run as root.
- I added the following to my sudoers file:
- %wheel ALL=NOPASSWD:/usr/bin/py-suspend
- In my case, wheel is the sudoers usergroup, and /usr/bin/py-suspend is the path to this script. In case it isn't clear, this allows any user in the wheel usergroup to run the script using sudo with no password.
- 1. Find and kill tty1-6
- 2. Execute slimlock (as a normal user (user's home must be in /home/)
- 3. Hibernate (pm-hibernate) (if argv[1] == 'hibernate') or Suspend (pm-suspend) (if argv[1] == 'suspend')
- """
- def slimlock():
- # Get all users with a home in /home/
- # Then make sure their shell is not /bin/false
- users = []
- lines = open('/etc/passwd', 'r').read().strip().split("\n");
- for line in lines:
- line = line.split(':')
- if line[5][0:6] == "/home/" and line[6] != "/bin/false":
- users.append(line[0])
- # Attempt to execute slimlock as each found user
- for user in users:
- cmd = 'sudo -u %s slimlock' % (user,)
- Popen(cmd, shell=True, stdout=PIPE, stderr=STDOUT)
- # Sleep for 5 seconds to give slimlock a chance to execute
- # Check running processes for slimlock
- # Join the last, second to last, and 4th to last strings after line.split()
- # "sudo -u slimlock" vs "sudo -u NAMEHERE slimlock"
- # If successful, return True, else False
- sleep(5)
- p = Popen('ps aux | grep slimlock', shell=True, stdout=PIPE, stderr=STDOUT)
- lines = p.stdout.readlines()
- for line in lines:
- split = line.split()
- end = " ".join([split[-4], split[-3], split[-1]])
- if end == "sudo -u slimlock":
- return True
- return False
- # Find tty1-6 and kill them
- p = Popen('ps aux | grep tty', shell=True, stdout=PIPE, stderr=STDOUT)
- for line in p.stdout.readlines():
- fields = line.split()
- owner, pid, tname = fields[0], fields[1], fields[6]
- if len(tname) == 4 and tname[0:3] == 'tty':
- if int(tname[3]) < 7:
- try:
- kill(int(pid), SIGKILL)
- except:
- print "Error: Could not kill %s {'pid': %s, 'user': %s}" % (tname, pid, owner)
- # Call the slimlock function, check for success, exit if no success.
- # We don't want to hibernate or any such thing if slimlock did not run.
- if not slimlock():
- print "Could not run slimlock"
- exit(1);
- # Any additional commands should be appended.
- # All will run and wait for the previous command to finish
- cmds = []
- if len(argv) == 2:
- if argv[1] == 'hibernate':
- cmds.append('pm-hibernate')
- elif argv[1] == 'suspend':
- cmds.append('pm-suspend')
- for cmd in cmds:
- p = Popen(cmd, shell=True, stdout=PIPE, stderr=STDOUT)
- p.stdout.readlines()
Advertisement
Add Comment
Please, Sign In to add comment