简体   繁体   中英

Cannot send commands to Docker unix socket via Python

I have a script that send signals to containers using nc (specifically the openbsd version that supports -U for Unix domain sockets):

echo -e "POST /containers/$HAPROXY_CONTAINER/kill?signal=HUP HTTP/1.0\r\n" | \
nc -U /var/run/docker.sock

I wanted to see if I could avoid the openbsd nc dependency or a socat dependency, so I tried to do the same thing in Python 3 with the following:

import socket

sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
sock.connect('/var/run/docker.sock')
sock.sendall(str.encode('POST /containers/{}/kill?signal=HUP HTTP/1.0\r\n'.format(environ['HAPROXY_CONTAINER'])))

I don't get any errors raised from the Python version, however my container doesn't receive the signal I'm attempting to send.

In the bash version, echo provides an additional new line. HTTP requires two new lines after the headers, so the Python sendall needed a second \\n like so:

sock.sendall(str.encode('POST /containers/{}/kill?signal=HUP HTTP/1.0\r\n\n'.format(environ['HAPROXY_CONTAINER'])))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM