Skip to content

Instantly share code, notes, and snippets.

@hnakamur
Last active June 10, 2020 13:39
Show Gist options
  • Save hnakamur/09c3040a5f773b542490423d17abf87a to your computer and use it in GitHub Desktop.
Save hnakamur/09c3040a5f773b542490423d17abf87a to your computer and use it in GitHub Desktop.
LXD REST API example via unix socket using python3 socket
#!/usr/bin/env python3
import socket
target_host = "localhost"
socket_path = "/var/snap/lxd/common/lxd/unix.socket"
client = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
client.connect(socket_path)
# send some data
request = "GET /1.0/instances HTTP/1.1\r\nHost:%s\r\n\r\n" % target_host
client.send(request.encode())
# receive some data
response = client.recv(4096)
http_response = repr(response)
http_response_len = len(http_response)
#display the response
print("[RECV] - length: %d" % http_response_len)
print(http_response)
#!/usr/bin/env python3
import socket
from ansible.module_utils.six.moves import http_client
HTTPConnection = http_client.HTTPConnection
class UnixHTTPConnection(HTTPConnection):
def __init__(self, path):
HTTPConnection.__init__(self, 'localhost')
self.path = path
def connect(self):
sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
sock.connect(self.path)
self.sock = sock
target_host = 'localhost'
socket_path = "/var/snap/lxd/common/lxd/unix.socket"
connection = UnixHTTPConnection(socket_path)
connection.request('GET', '/1.0/containers')
response = connection.getresponse()
# receive some data
http_response = response.read()
http_response_len = len(http_response)
#display the response
print("[RECV] - length: %d" % http_response_len)
print(http_response)
@hnakamur
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment