简体   繁体   English

在python脚本中,更改用户,设置环境并运行几个命令

[英]From a python script, change user, set environment and run a couple of commands

I need to run a python script that changes user, sets a enviroment variable and executes a command and return the output. 我需要运行一个python脚本来更改用户,设置环境变量并执行命令并返回输出。

1.) The way I am currently doing this is I am creating a shell script that does this for me: 1.)我目前正在执行的方法是创建一个为我执行此操作的shell脚本:

tmpshell.sh tmpshell.sh

su - grid -c "echo +ASM1 | . oraenv; asmcmd volinfo -a"

The command fails because the environment is not being set. 该命令失败,因为未设置环境。

2.) The second way I tried was by changing user is python script itself and then creating the shell script. 2)我尝试的第二种方法是通过更改用户是python脚本本身,然后创建shell脚本。

tmp.py tmp.py

os.system('su - grid')
TMPFILE="/tmp/tmpfile.sh"
filehandle=open(TMPFILE,'w')
filehandle.write('+ASM1|. oraenv')
filehandle.write('asmcmd volinfo -a')
filehandle.close()
os.chmmod(TMPFILE,0755)

Here the problem is that the python script changes the user but the rest of the script doesn't run until I enter exit. 这里的问题是python脚本更改了用户,但是脚本的其余部分直到我输入exit才运行。

OUTPUT 输出值

[root@odadev1 oakvmclientlib]# python test.py
[grid@odadev1 ~]$ exit

[root@odadev1 oakvmclientlib]# 

Any suggestions/better ways to do this ?? 任何建议/更好的方式做到这一点?

ps(edit) ". oraenv" is for setting the environment and +ASM1 is the environment variable it expects. ps(edit)“。oraenv”用于设置环境,而+ ASM1是期望的环境变量。

Try something like this: 尝试这样的事情:

$ sudo -u grid sh -c ". oraenv; echo +ASM1|asmcmd volinfo -a"

This will launch a shell as user grid , set up the environment in it and execute the command. 这将启动一个shell作为用户grid ,在其中设置环境并执行命令。 I'm not sure what the second part of your command does, though - I suspect you want to pipe +ASM1 into the standard input of asmcmd , but you haven't given enough context to be sure. 不过,我不确定命令第二部分的作用是什么-我怀疑您要将管道+ASM1传递到asmcmd的标准输入中,但是您没有给出足够的上下文来确定。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM