Skip to content

Instantly share code, notes, and snippets.

@klynton
Forked from k4ml/docs.txt
Created February 7, 2014 00:21
Show Gist options
  • Save klynton/8855236 to your computer and use it in GitHub Desktop.
Save klynton/8855236 to your computer and use it in GitHub Desktop.
"""
CLI tools for webfaction API. The project seem abandoned already
so I've just fork it to my github account and start adding few
unimplemented command.
https://pypi.python.org/pypi/webf
https://github.com/k4ml/webf
After playing around with the API for a while, I realized
that we don't really need fancy library to access the API.
It pretty straightforward, the API only accept either plain
string, boolean or list as parameters and return either a dict
or list of dicts. So here a client to the whole APIs in just
106 lines of code:
Ping me @k4ml (twitter/github) if you need any help.
TODO:-
* Pull list of commands from http://docs.webfaction.com/xmlrpc-api/apiref.html
for easy reference.
"""
import re
import sys
import xmlrpclib
import logging
import os.path
import ConfigParser
API_URL = 'https://api.webfaction.com/'
CONF = os.path.expanduser('~/.webfrc')
class WebFactionXmlRpc(object):
'''WebFaction XML-RPC server proxy class'''
def __init__(self, login=True):
self.log = logging.getLogger('webf')
self.log.addHandler(logging.StreamHandler())
self.session_id = None
self.server = None
if login:
self.login()
def get_config(self):
'''Get configuration file from user's directory'''
if not os.path.exists(CONF):
self.log.error("Set your username/password in %s" % CONF)
self.log.error("The format is:")
self.log.error(" [main]")
self.log.error(" username=<username>")
self.log.error(" password=<password>")
sys.exit(1)
config = ConfigParser.ConfigParser()
config.readfp(open(CONF))
username = config.get('main', 'username')
password = config.get('main', 'password')
return (username, password)
def login(self):
'''Login to WebFaction and get a session_id'''
try:
http_proxy = os.environ['http_proxy']
except KeyError:
http_proxy = None
username, password = self.get_config()
self.server = xmlrpclib.Server(API_URL, transport=http_proxy)
self.session_id, account = self.server.login(username, password)
self.log.debug("self.session_id %s account %s" % (self.session_id,
account))
def _show(self, result, id_field='name', pattern=None):
for item in result:
if pattern and pattern != 'None':
to_match = item[id_field] + ' ' + item.get('description', '')
if not re.search(pattern, to_match):
continue
for key, value in item.items():
if key == id_field:
print value
else:
print "\t", "%s: " % key, value
def _call(self, command, *args):
'''Generic command'''
func = getattr(self.server, command)
try:
result = func(self.session_id, *args)
self.log.debug(result)
except xmlrpclib.Fault, errmsg:
self.log.error(errmsg)
return 1
return result
def main():
if len(sys.argv) < 2:
print 'Need command'
print 'Example: python webf.py list_ips'
print 'Example: python webf.py create_website web1 "216.185.102.19" true "web1.biz,store1" "store1:/,django:/admin"'
sys.exit(1)
command = sys.argv[1]
args = sys.argv[2:]
new_args = []
for argument in args:
if argument in ('true', 'false'):
argument = True if argument == 'true' else False
new_args.append(argument)
continue
if ':' in argument:
mapping_list = argument.split(',')
argument = [(key, val) for key, val in [mapping.split(':') for mapping in mapping_list]]
new_args += argument
continue
if ',' in argument:
argument = argument.split(',')
new_args.append(argument)
continue
new_args.append(argument)
print command, new_args
wf = WebFactionXmlRpc()
result = wf._call(command, *new_args)
wf._show(result)
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment