#! /usr/bin/env python import os import sys from subprocess import Popen, PIPE, call import time import signal def find_open_terminals(): """Search for open terminals with pattern /bin/login.""" open_terminals = [] process = Popen(["ps", "aux"], stdout=PIPE, stderr=PIPE) process.wait() process1 = Popen(["grep", "/bin/login"], stdin=process.stdout, stdout=PIPE, stderr=PIPE) process1.wait() stdout, stderr = process1.communicate() if len(stderr) > 0: return [] tmp = stdout.decode("utf-8") for i in tmp.split("\n"): pid = " ".join(i.split()).split() if len(pid) == 0: continue open_terminals.append(int(pid[1])) return open_terminals def lock_terminals(open_terminals): for pid in open_terminals: try: os.kill(pid, signal.SIGQUIT) except OSError as error: call(["logger", error]) def get_users(): """Search for users with a display.""" users = {} process = Popen(["pinky", "-fw"], stdout=PIPE, stderr=PIPE) process.wait() stdout, error = process.communicate() if len(error) != 0: call(["logger", "Could not found user logged in on X"]) return tmp = stdout.decode("utf-8").split("\n") for i in range(len(tmp)): if len(tmp[i]) == 0: continue tmp_users = " ".join(tmp[i].split()).split() if tmp_users[1].startswith("?"): users[i] = { "name": tmp_users[0], "display": tmp_users[1].replace("?", "") } return users def lock_screens(x_users): for user in x_users.values(): call(["logger", "Lock X screen for: %s" % user["name"]]) cmd = "export DISPLAY=%s; " % user["display"] if user["name"] == "root": cmd += 'mate-screensaver-command -l' else: cmd += 'su %s -c "mate-screensaver-command -l"' % (user["name"]) call(cmd, shell=True) time.sleep(1) def main(): lock_screens(get_users()) lock_terminals(find_open_terminals()) call("pm-suspend") if __name__ == '__main__': main()