如何使用 python 子进程模块将 sqlplus 作为 sudo 连接到 oracle 用户?
Posted
技术标签:
【中文标题】如何使用 python 子进程模块将 sqlplus 作为 sudo 连接到 oracle 用户?【英文标题】:how do i connect sqlplus as sudo to oracle user using python subprocess module? 【发布时间】:2019-01-23 11:08:43 【问题描述】:我有一个 root 用户拥有的 python 脚本,我正在尝试将 sqlplus 命令作为 sudo 运行给 oracle 用户。但是遇到诸如 oracle_home 之类的问题没有设置
import os,subprocess
query = '''
WHENEVER SQLERROR EXIT FAILURE
SET FEEDBACK OFF
SET HEAD OFF
SET EMB ON PAGES 0 NEWP
SET LINE 10000
SELECT * from dual;
EXIT;
'''
dbsession = subprocess.Popen(["/usr/bin/sudo","-u","oracle","/orahome/Database/db12c/bin/sqlplus", "-S", "/ as sysdba"], stdin=subprocess.PIPE,stdout=subprocess.PIPE, stderr=subprocess.PIPE,env="ORACLE_SID": "EMREP", "ORACLE_HOME": "/orahome/Database/db12c")
dbsession.stdin.write(query)
query_result = dbsession.communicate()
print(query_result, dbsession.returncode
输出
(('', 'Error 6 initializing SQL*Plus\nSP2-0667: Message file sp1<lang>.msb not found\nSP2-0750: You may need to set ORACLE_HOME to your Oracle software directory\n'), 1)
【问题讨论】:
【参考方案1】:以下代码有效
import os,subprocess
query = '''
WHENEVER SQLERROR EXIT FAILURE
SET FEEDBACK OFF
SET HEAD OFF
SET EMB ON PAGES 0 NEWP
SET LINE 10000
SELECT * from dual;
EXIT;
'''
db_home=/orahome/Database/db12c
dbsession = subprocess.Popen(["/usr/bin/sudo","su","-","oracle","-c",""""""""+db_home+"""/bin/sqlplus -S / as sysdba"""""], stdin=subprocess.PIPE,stdout=subprocess.PIPE, stderr=subprocess.PIPE,env="ORACLE_SID": "EMREP", "ORACLE_HOME": "+db_home+")
dbsession.stdin.write(query)
query_result = dbsession.communicate()
print(query_result, dbsession.returncode)
【讨论】:
以上是关于如何使用 python 子进程模块将 sqlplus 作为 sudo 连接到 oracle 用户?的主要内容,如果未能解决你的问题,请参考以下文章
如何在asyncio python中使用子进程模块限制并发进程数