Home > Blockchain >  How to log out the current user from a Python script?
How to log out the current user from a Python script?

Time:03-02

I have a Python script which lets the user log out of the current terminal session (among other things).

The Python script is launched from bash on Linux (Ubuntu).

I tried:

os.system('exit')  # doesn't work
subprocess.run(['exit'])  # doesn't work

and similar. They return with exit code 0 (success) but there's no terminal session log out, even the Python script continues running.

How do I log out programmatically from a Python script?

The current user has access to sudo if necessary, so running root commands from Python would be OK too.

CodePudding user response:

When you call the os.system() it creates a new process and, when you execute a command, it will run on this new process and not on the one where you first execute the script. That's why they return with exit code 0, because it works, but not for the process that you expect.

If you want only to stop the execution of your script, you can just use the exit() command. Something like this:

stop_code_execution = input("Would you like to stop the code execution? (yes/no): ")
stop_code_execution.lower()

if stop_code_execution == 'yes':
    exit()

Otherwise, if you want to stop all sessions of the current user, you can do the following:

import os

command_output = os.popen("whoami")
current_user = command_output.read()

logout_user = input("Would you like to logout the user "   current_user   "? (yes/no): ")
logout_user.lower()

if logout_user == 'yes':
    os.system("loginctl terminate-user "   current_user)
else:
    exit()

Note that with the second approach, all the processes of the user will be stopped which will lead it back to the login screen.

CodePudding user response:

I figured it out. Ian Nascimento's answer was a great lead, but used the wrong command.

Here's the working solution:

import subprocess

def log_me_out():
    """Terminate the current login session, with all its processes, including this one."""
    session_id = subprocess.run(
        "cat /proc/self/sessionid",
        shell=True, capture_output=True, encoding='utf8',
    ).stdout
    print(f"terminating login session {session_id}")
    subprocess.run(f"loginctl terminate-session {session_id}", shell=True)
  • Related