【问题标题】:Converting linux commands with os.popen in python在 python 中使用 os.popen 转换 linux 命令
【发布时间】:2023-03-20 05:42:02
【问题描述】:

我怎样才能做出这个命令:

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', '') 

但它不起作用。

【问题讨论】:

    标签: python linux popen


    【解决方案1】:

    subprocess.check_outputshell=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()
    

    【讨论】:

    • >>> 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) Traceback(最近一次调用最后):文件“”,第 1 行,在 属性错误:'module' 对象没有属性'check_output'
    • @user3013012,你用的是哪个版本的python?
    • @user3013012,我用替代解决方案更新了答案。看看吧。
    猜你喜欢
    • 2012-03-25
    • 1970-01-01
    • 2013-02-10
    • 2021-07-25
    • 2012-05-20
    • 2023-03-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多