擅长:python、mysql、java
<p>在尝试了模块<code>os</code>、<code>subprocess</code>、<code>getpass</code>之后,我意识到问题不在于是否设置了用户。使用<code>os.setuid</code>设置或更改用户,但是,模块中获取用户名的方法(如<code>os.getlogin()</code>,<code>getpass.getuser()</code>)实际上无法正确获取用户名。如果使用<code>subprocess.Popen()</code>或<code>os.system()</code>运行shell命令<code>whoami</code>或<code>id</code>,则将获得更改的用户。这些对我来说是一个小小的困惑。下面的脚本显示了所有这些奇怪的行为。</p>
<pre><code>import os
import subprocess
import pwd
import getpass
#os.chdir("/tmp")
#uid = pwd.getpwnam('newuser').pw_uid
os.setuid(500) # newuser's id found from shell cmd line
print os.getuid()
p = subprocess.Popen(['id'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out, err = p.communicate()
# print os.system('useradd newuser1') # Try this commenting, it will not create, and then try commenting above line of setuid. i.e. it will become root, and then see the change.
# print os.getcwd()
print out,err
p = subprocess.Popen(['whoami'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out, err = p.communicate()
print out,err
print getpass.getuser()
print os.getlogin()
print os.system('whoami')
</code></pre>