在python中使用os.popen转换linux命令

我如何执行此命令:
ACTIVE_MGMT_1=`ssh -n ${MGMT_IP_1} ". .bash_profile; xms sho proc TRAF.*" 2>/dev/null |egrep " A " |awk '/TRAF/{print $1}' |cut -d "." -f2`;
通过python运行?
我正在尝试做:
active_mgmgt_1 = os.popen("""ssh -n MGMT_IP_1 ". .bash_profile; xms sho proc TRAF.*" 2>/dev/null |egrep " A " |awk '/TRAF/{print $1}' |cut -d "." -f2""")
SITE_NAME = site_name.read().replace('\n', '')
但这是行不通的.
解决方法:
将subprocess.check_output与shell = True一起使用:
cmd = r'''ssh -n ${MGMT_IP_1} ". .bash_profile; xms sho proc TRAF.*" 2>/dev/null |egrep " A " |awk '/TRAF/{print $1}' |cut -d "." -f2'''
output = subprocess.check_output(cmd, shell=True)
更新
subprocess.check_output已在Python 2.7中添加.如果您使用旧版本的Python,请改用subprocess.Popen.communicate.
proc = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
output, errmsg = proc.communicate()