【问题标题】:Trying to get value of a subprocess试图获得子流程的价值
【发布时间】:2021-09-25 06:32:22
【问题描述】:

我正在创建一个函数来测试连接并获取价值,但它不起作用。 我正在使用 grep 来获取仅收到的值。

def testConnection(ip):
    
    TIMEOUT = 10
    args = ('sudo', 'ping', '-c', '1', '-q', ip, '|', 'grep -E -o', '"[0-9]+ received"', '|', 'cut', '-f1', '-d') 
    
    try:
        popen = subprocess.Popen(args, stdout=subprocess.PIPE)
        popen.wait(timeout=TIMEOUT)
        
                   
        if (popen == 1):
            print(ip + " is up")
        else:
            print(ip + " is down")
            
                
    except subprocess.TimeoutExpired as e:
        print(e)
        return False
        
    if(popen.returncode != 0):
        raise ServiceException()

【问题讨论】:

    标签: python python-3.x django subprocess ip


    【解决方案1】:

    当我使用带有 ping 的 popen 之类的东西时,我更喜欢计算消息中“ttl”的数量,因为在成功建立连接时只显示一个。然后你只需要检查回读值是否等于 -c 中给出的参数:

    ping -c 1 {ip} | grep -c ttl
    

    shell 中的输出示例:

    $ ping -c 1 192.168.1.120 | grep -c ttl
    1
    
    $ ping -c 1 192.168.1.254 | grep -c ttl
    0
    

    注意读取 stdout 而不是 popen 的返回值,以确保 ping 没有超时。

    例子:

    p = subprocess.Popen("ping -c 1 {} | grep -c ttl".format(ip), stdout=subprocess.PIPE)
    

    仅 args 作为序列

    args = ('ping','-c','1',ip)
    p = subprocess.Popen(args, stdout=subprocess.PIPE)
    
    if "ttl" in p.stdout.readlines()[1]:
        # ping ok
    else :
        # ping ko
    

    【讨论】:

    • 当我使用:grep -c ttl 时,出现错误:ping: invalid argument: 'ttl' 我的代码:args = ('ping', '-c', '1', ip , '|', 'grep', '-c', 'ttl')
    • 尝试在一个字符串中传递所有命令,因为 popen 将您的其他参数解释为 ping 的参数。像我编辑过的东西。
    • 是否如library 文档中所述避免shell注入?如果是,那么您可能只需要调用 ping,因为仅当您使用程序参数时才将 args 作为序列传递。请参阅我答案中唯一的 args 部分以获取解决方法。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-01-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-20
    • 2013-02-19
    • 2016-03-18
    相关资源
    最近更新 更多