如何从Python脚本中注销当前用户?
我有一个 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
当您调用 os.system() 时,它会创建一个新进程,并且当您执行命令时,它将在这个新进程上运行,而不是在您第一次执行脚本的进程上运行。这就是为什么它们返回退出代码 0,因为它可以工作,但不适用于您期望的进程。
如果您只想停止脚本的执行,则可以使用 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:
Otherwise, if you want to stop all sessions of the current user, you can do the following:
Note that with the second approach, all the processes of the user will be stopped which will lead it back to the login screen.
我想通了。伊恩·纳西门托(Ian Nascimento)的回答是一个很好的领先,但使用了错误的命令。
这是工作解决方案:
I figured it out. Ian Nascimento's answer was a great lead, but used the wrong command.
Here's the working solution: