run linux grep command from python subprocess

后端 未结 2 1326
孤独总比滥情好
孤独总比滥情好 2021-01-21 06:14

I know there are posts already on how to use subprocess in python to run linux commands but I just cant get the syntax correct for this one. please help. This is the command I n

2条回答
  •  盖世英雄少女心
    2021-01-21 06:46

    Here's how to construct the pipe in Python (rather than reverting to Shell=True, which is more difficult to secure).

    from subprocess import PIPE, Popen
    
    # Do `which` to get correct paths
    GREP_PATH = '/usr/bin/grep'
    IFCONFIG_PATH = '/usr/bin/ifconfig'
    AWK_PATH = '/usr/bin/awk'
    
    awk2 = Popen([AWK_PATH, '{print $1}'], stdin=PIPE)
    awk1 = Popen([AWK_PATH, '-F:', '{print $2}'], stdin=PIPE, stdout=awk2.stdin)
    grep = Popen([GREP_PATH, 'inet addr'], stdin=PIPE, stdout=awk1.stdin)
    ifconfig = Popen([IFCONFIG_PATH, 'eth1'], stdout=grep.stdin)
    
    procs = [ifconfig, grep, awk1, awk2]
    
    for proc in procs:
        print(proc)
        proc.wait()
    

    It'd be better to do the string processing in Python using re. Do this to get the stdout of ifconfig.

    from subprocess import check_output
    
    stdout = check_output(['/usr/bin/ifconfig', 'eth1'])
    print(stdout)
    

提交回复
热议问题