bash中的命令在转换为Python时不起作用

2024-04-18 14:58:09 发布

您现在位置:Python中文网/ 问答频道 /正文

我在bash中有以下命令:

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""") ACTIVE_MGMT_1 = active_mgmgt_1.read().replace('\n', '')

不行,有什么建议吗?你知道吗


Tags: devipbashprocprofilenullsshactive
1条回答
网友
1楼 · 发布于 2024-04-18 14:58:09

您的popen呼叫需要设置为通过管道进行通信。你知道吗

也不要试图把所有的东西都放在一行上—python不需要它,并且在可读的代码上放置了大量的扩展。你知道吗

我强烈建议用python而不是egrep(在python中使用find或re)、awk(find或egrep)和cut(string split)来处理字符串。你知道吗

也建议使用子流程.Popen而不是欧斯波本功能。有一个建议可以使用施莱克斯。斯皮尔特来解决这类问题。你知道吗

未测试代码

import subprocess
import re
import os

MGMT_IP_1 = os.getenv('MGMT_IP_1')
sp = subprocess.Popen(
    ['ssh', '-n', MGMT_IP_1, '. .bash_profile; xms sho proc TRAF.*'],
    stdout=PIPE, stderr=None)
(result, outtext) = sp.communicate()
# Proceed to process outtext from here using re, find and split
# to the equivalent of egrep " A " |awk '/TRAF/{print $1}' |cut -d "." -f2;

相关问题 更多 >