Skip to content

Instantly share code, notes, and snippets.

@netcreatoreu
Forked from sandromello/zimbra_soap_request.py
Created January 27, 2021 13:56
Show Gist options
  • Select an option

  • Save netcreatoreu/d5911e0781faa99b4f97865a08c76934 to your computer and use it in GitHub Desktop.

Select an option

Save netcreatoreu/d5911e0781faa99b4f97865a08c76934 to your computer and use it in GitHub Desktop.

Revisions

  1. @sandromello sandromello created this gist Feb 22, 2017.
    42 changes: 42 additions & 0 deletions zimbra_soap_request.py
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,42 @@
    #!/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)