Tag Archives: snippet

WordPress xmlrpc with a different Host header in Python

If you are ever in a situation where you need to run an xmlrpc request against a specific WordPress server using the python xmlrpc library, it can be somewhat difficult. The Python xmlrpc library doesn’t give you an easy way to override the Host header in the request, so you can only pick the server or the Host, but not both. Luckily, the library allows you to override the HTTP transport class it uses, so you can provide your own. Here’s a transport that seems to work for connecting locally with any given host. It would be fairly easy to modify to connect to any server.

class LocalTransport(xmlrpclib.Transport):
def make_connection(self, host):
self.real_host = host
return xmlrpclib.Transport.make_connection(self, '127.0.0.1')

def send_request(self, connection, handler, request_body):
try:
import gzip
except ImportError:
gzip = None #python can be built without zlib/gzip support
if (self.accept_gzip_encoding and gzip):
connection.putrequest("POST", handler, skip_host=True, skip_accept_encoding=True)
connection.putheader("Accept-Encoding", "gzip")
else:
connection.putrequest("POST", handler, skip_host=True)
connection.putheader("Host", self.real_host)

Testing links to see if they work

The input is a csv where the first column is the URL you want to test. The curl line spits out the response code. -f means curl will return an exit code if the fetch fails.


# test URLs
for x in $(cat "$file" | grep -v URL | cut -d, -f1) ; do code=$(curl -s -w %{response_code} -f "$x" -o /dev/null) && echo "URL OK $code: $x";  done

# convert URLs to nginx redirects
sed -e 's#^http://[^/]*\(/[^,]*\),\(.*\)$#rewrite ^\1$ \2 permanent;#' < "$file" > /tmp/output_redirects

Good times.