使用subprocess注销没有sudo

我希望我的脚本在脚本完成时自动将当前用户注销。 它将在基于Linux的服务器(Ubuntu)上运行。 我已经尝试了这一行代码,但它不会工作。

subprocess.call(['logout']) 

发生以下错误:

 Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/lib/python2.7/subprocess.py", line 493, in call return Popen(*popenargs, **kwargs).wait() File "/usr/lib/python2.7/subprocess.py", line 679, in __init__ errread, errwrite) File "/usr/lib/python2.7/subprocess.py", line 1249, in _execute_child raise child_exception OSError: [Errno 2] No such file or directory 

我也试过:

 subprocess.Popen(['sudo', 'logout']) 

但是那么用户将不得不input他的密码才能被注销。 没有sudo在这一个我得到:

 Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/lib/python2.7/subprocess.py", line 679, in __init__ errread, errwrite) File "/usr/lib/python2.7/subprocess.py", line 1249, in _execute_child raise child_exception OSError: [Errno 2] No such file or directory 

我不想以root身份运行脚本本身。

我希望能够直接login一个用户,而不必input密码。 当你在普通的terminal使用注销时,你通常不需要input密码,所以我不明白为什么这是一个问题。

所有的帮助,非常感谢。

编辑:我已经find了解决我的问题,通过添加一些额外的代码〜/ .bash_login(请参阅我的答案),但为什么我在上面尝试没有得到答案。

用你正在做的事情,最好的办法就是把你的python命令包装在运行python命令的Bash脚本中,然后以注销结束。

注销是Bash内建函数。 它不作为可以通过Python使用的可调用命令存在。

一些事情的影响:

 #!/bin/bash cd /path/to/script ./scriptname.py logout 

我可以理解想要在Python中实现它。 但是,如果您使用任何简单地通过PID kill来终止会话的过程,您将遇到问题。

这可能会有所帮助,不确定它是否完全符合您的需求,但会注销当前用户(而不是像您所希望的那样干净利落)

 import os os.system("pkill -KILL -u " + os.getlogin()) 

我只测试了这个很快,但似乎做的伎俩。

你可以尝试杀死你的父PID,这很可能是启动你的shell – 但是如果你是由脚本启动的话,

 os.kill(os.getppid(),signal.SIGTERM) 

但是,如果要更换shell,要充当登录程序,可以更改登录设置以运行程序,或者从父shell运行exec来替换它。 因此,除了你自己,你不需要杀死任何东西。

可能为你工作?

 cmd = 'logout' p = subprocess.Popen(cmd, shell=True) 

(我没有试过,只是猜测!!)

我找到了解决我的问题。 我补充说

 sys.exit(1) 

我的脚本。

然后我将以下代码添加到〜/ .bash_login中

 if [ "$?" == "0" ]; then logout fi 

所以logout-command在Python脚本完成时运行。