Skip to content

Instantly share code, notes, and snippets.

@vincenthsu
Created January 12, 2016 08:26
Show Gist options
  • Star 22 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save vincenthsu/6eb1f9b2c07d123c526b to your computer and use it in GitHub Desktop.
Save vincenthsu/6eb1f9b2c07d123c526b to your computer and use it in GitHub Desktop.
ONVIF http request example
#!/usr/bin/env python3
import hashlib
import os
import base64
from datetime import datetime
username = "admin"
password = "12345"
# created = datetime.now().strftime("%Y-%m-%dT%H:%M:%S.000Z")
created = datetime.utcnow().strftime("%Y-%m-%dT%H:%M:%S.000Z")
raw_nonce = os.urandom(20)
nonce = base64.b64encode(raw_nonce)
sha1 = hashlib.sha1()
sha1.update(raw_nonce + created.encode('utf8') + password.encode('utf8'))
raw_digest = sha1.digest()
digest = base64.b64encode(raw_digest)
template = """<s:Envelope xmlns:s="http://www.w3.org/2003/05/soap-envelope">
<s:Header>
<Security s:mustUnderstand="1" xmlns="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd">
<UsernameToken>
<Username>{username}</Username>
<Password Type="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordDigest">{digest}</Password>
<Nonce EncodingType="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0#Base64Binary">{nonce}</Nonce>
<Created xmlns="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd">{created}</Created>
</UsernameToken>
</Security>
</s:Header>
<s:Body xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<GetCapabilities xmlns="http://www.onvif.org/ver10/device/wsdl">
<Category>All</Category>
</GetCapabilities>
</s:Body>
</s:Envelope>"""
req_body = template.format(username=username, nonce=nonce.decode('utf8'), created=created, digest=digest.decode('utf8'))
print(req_body)
#!/bin/bash
python3 onvif_request.py > request.xml
curl --silent -X POST --header 'Content-Type: text/xml; charset=utf-8' -d @request.xml 'http://192.168.4.61/onvif/device_service' | xmllint --format -
@atika
Copy link

atika commented May 29, 2018

I played with your script and I had an error 417 - Expectation Failed, after adding --header 'Expect:' to the curl request, It worked.

@tomvanbraeckel
Copy link

Works great, thanks!

@remco-k
Copy link

remco-k commented Dec 26, 2023

Thank you. With this script you helped me onto the correct path onto finding my rtsp uri for my camera!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment