Last active
June 10, 2020 13:39
-
-
Save hnakamur/09c3040a5f773b542490423d17abf87a to your computer and use it in GitHub Desktop.
LXD REST API example via unix socket using python3 socket
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This script is based on https://www.geeks3d.com/hacklab/20190110/python-3-simple-http-request-with-the-socket-module/
Thanks!