Skip to content

Instantly share code, notes, and snippets.

@sandromello
Created February 22, 2017 11:37
Show Gist options
  • Save sandromello/b2bb3b05edc13d637e79dfae12e2b817 to your computer and use it in GitHub Desktop.
Save sandromello/b2bb3b05edc13d637e79dfae12e2b817 to your computer and use it in GitHub Desktop.
Example requesting Zimbra SOAP API
#!/usr/bin/env python
import xml.etree.ElementTree as ET
import requests
url = 'https://<ZIMBRA_SERVER_URL>:7071/service/admin/soap'
headers = { 'Content-Type': 'application/soap+xml' }
# Get the credentials through zmlocalconfig
# zmlocalconfig zimbra_user
# zmlocalconfig -s zimbra_ldap_password
zimbra_user = 'zimbra'
zimbra_password = '<ZIMBRA_LDAP_PASSWORD>'
token_xml = '<?xml version="1.0" ?><soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope">\
<soap:Header><context xmlns="urn:zimbra"><format type="xml"/></context></soap:Header><soap:Body><AuthRequest xmlns="urn:zimbraAdmin">\
<name>%s</name><password>%s</password></AuthRequest></soap:Body></soap:Envelope>' % (zimbra_user, zimbra_password)
r = requests.post(url, data=token_xml, headers=headers)
# Got the admin token, now you can get the delegated token to act on behalf a specific account
admin_token = ET.fromstring(r.content).find('.//{urn:zimbraAdmin}authToken').text
username_to_act_on_behalf = '[email protected]'
delegated_token_xml = '<?xml version="1.0" ?><soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope"><soap:Header><context xmlns="urn:zimbra">\
<authToken>%s</authToken></context></soap:Header><soap:Body><DelegateAuthRequest duration="86400" xmlns="urn:zimbraAdmin">\
<account by="name">%s</account></DelegateAuthRequest></soap:Body></soap:Envelope>' % (admin_token, username_to_act_on_behalf)
r = requests.post(url, data=delegated_token_xml, headers=headers)
delegated_token = ET.fromstring(r.content).find('.//{urn:zimbraAdmin}authToken').text
info_request_xml = '<?xml version="1.0" ?><soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope">\
<soap:Header><context xmlns="urn:zimbra"><authToken>%s</authToken><session/><account by="name">%s</account><userAgent name="zclient" version="8.0.7_GA_6020"/></context></soap:Header>\
<soap:Body><GetInfoRequest sections="mbox" rights="" xmlns="urn:zimbraAccount"/>\
</soap:Body></soap:Envelope>' % (delegated_token, username_to_act_on_behalf)
# Now you can start using the main url
main_url = 'https://<ZIMBRA_SERVER_URL>/service/soap'
r = requests.post(main_url, data=info_request_xml, headers=headers)
print(r.content)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment