shell脚本与Python的交互

一、Python针对shell获取传入,输出参数html

传入:"$num"python

例如: $0表示文件名,$1表示shell获取的第一个参数mysql

输出:经过打印shell结果的方式,输出参数给Python。sql

例如: echo "{$iplist}",Python调用执行shell的方法便可获取结果。shell

二、获取切换用户后加载shell环境执行Python命令的结果。数据库

好比我登陆号是root权限,如今加载的shell环境须要ossadm权限执行,而后进入Python进行解密操做则可使用EOF命令:json

例如:orm

#! /bin/shhtm

su ossadm <<EOFblog

. /bin/test.sh

python

import json

from util import ossext

password = "$1"

result = ossext.Cipher.decrypt(password)

print result

EOF

三、shell的归shell,Python的归Python。

Python调用shell命令以前须要加载认证信息,变量信息等。能够直接在shell文件或命令头部设置。

例如:

#! /bin/sh

export var;

alias variable;

variable $1

 

四、Python链接数据库执行命令:

要求:不能使用第三方库,只能经过shell方式执行。(mysql -uuser -ppassword)

a.执行一条SQL命令,对返回值进行操做。我经过subprocess.Popen()获得返回值。

b.链接数据库打开SQL环境,正常执行多条命令。我经过os.system()得到数据库环境。

参考: 

Python调用shell命令

subprocess的API手册

 

五、在shell脚本中指定角色加载环境变量,执行Python命令

import subprocess

decrypt_cmd = '''su - ossadm -c "source /opt/ossadm/manager/bin/engr_profile.sh; {Python_path} -c \\" from util import ossext; plainText= ossext.Cipher.decrypt('{encrypted Text}') ; print (plainText) \\" '''.format(Python_path= Python_path, encryptedText = data)

process = subprocess.Popen(decrypt_cmd, stdout=subprocess.PIPE, shell= True)

result= process.stdout.read()

return result

相关文章
相关标签/搜索