119   Python

一,背景:

1,python 的 subprocess.Popen 可创建子进程来执行 shell 命令
2,有时候执行 shell 要指定用户,可通过 Popen 的参数来控制

 

 

二,实例代码:

import os
import pwd
import subprocess
import sys

def exe_cmd(USER,SHELL):

    try:
        pw_record = pwd.getpwnam(USER)
    except Exception, e:
        print 'user is not exist'
        return False
    user_name      = pw_record.pw_name
    user_home_dir  = pw_record.pw_dir
    user_uid       = pw_record.pw_uid
    user_gid       = pw_record.pw_gid
    env = os.environ.copy()
    env[ 'HOME'     ]  = user_home_dir
    env[ 'LOGNAME'  ]  = user_name
    env[ 'PWD'      ]  = user_home_dir
    env[ 'USER'     ]  = user_name
    cwd = user_home_dir

    cmd = SHELL
    p = subprocess.Popen(cmd,preexec_fn=demote(user_uid, user_gid), cwd=cwd, env=env)


def demote(user_uid, user_gid):
    def result():
        os.setgid(user_gid)
        os.setuid(user_uid)
    return result


if __name__ == '__main__':
    user = 'test_user'
    cmd = 'whoami'
    exe_cmd(user,cmd)



Leave a Reply

Your email address will not be published. Required fields are marked *