如何从Python脚本中注销当前用户?

发布于 2025-01-10 19:51:56 字数 407 浏览 0 评论 0原文

我有一个 Python 脚本,它可以让用户注销当前的终端会话(除其他外)。

Python 脚本是从 Linux (Ubuntu) 上的 bash 启动的。

我尝试过:

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

和类似的。它们返回退出代码 0(成功),但没有终端会话注销,即使 Python 脚本仍在继续运行。

如何以编程方式从 Python 脚本中注销?

如果需要,当前用户可以访问 sudo,因此从 Python 运行 root 命令也可以。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

无所谓啦 2025-01-17 19:51:56

当您调用 os.system() 时,它会创建一个新进程,并且当您执行命令时,它将在这个新进程上运行,而不是在您第一次执行脚本的进程上运行。这就是为什么它们返回退出代码 0,因为它可以工作,但不适用于您期望的进程。

如果您只想停止脚本的执行,则可以使用 exit() 命令。像这样的事情:

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

if stop_code_execution == 'yes':
    exit()

否则,如果您想停止当前用户的所有会话,您可以执行以下操作:

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()

请注意,使用第二种方法,用户的所有进程将被停止,这将导致其返回到登录屏幕。

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.

丑丑阿 2025-01-17 19:51:56

我想通了。伊恩·纳西门托(Ian Nascimento)的回答是一个很好的领先,但使用了错误的命令。

这是工作解决方案:

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)

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)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文