python errno 23 - socket livestatus

2019-09-07 11:22发布

问题:

I'm trying to send two queries to the server with this script, to get the MK Livestatus:

live.py

#!/usr/bin/python
socket_path = "/tmp/run/live"
import socket
s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
s.connect(socket_path)

# Get Hosts
hosts = s.send("GET hosts\nColumns: name\n")
s.shutdown(socket.SHUT_WR)
hosts = s.recv(1024)
hosts = [ line.split(';') for line in hosts.split('\n')[:-1] ]

hostsB = s.send("GET hosts\nColumns: name\n")

s.close()

But I get this error:

Traceback (most recent call last): File "live.py", line 13, in hostsB = s.send("GET hosts\nColumns: name\n") socket.error: [Errno 32] Broken pipe

I think the error is related to the command "s.shutdown(socket.SHUT_WR)". But the author says, that this is required. You will get no answer (timeout?), if you remove this line.

How can I send two queries?


SOLUTION

so ... I've written a function that does the job :-)

Function

def sendQuery(query):
    s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
    s.connect(socket_path)
    s.send(query)
    s.shutdown(socket.SHUT_WR)

    answer = ''
    while True:
        data = s.recv(1024)
        answer += data
        if len(data) < 1024:
            break

    s.close()
    return answer

Usage

sendQuery("GET hosts\nColumns: name\n")

回答1:

so ... I've written a function that does the job :-)

Function

def sendQuery(query):
    s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
    s.connect(socket_path)
    s.send(query)
    s.shutdown(socket.SHUT_WR)

    answer = ''
    while True:
        data = s.recv(1024)
        answer += data
        if len(data) < 1024:
            break

    s.close()
    return answer

Usage

sendQuery("GET hosts\nColumns: name\n")