hikvision


Automating Video Retrieval from HIKVision NVR using Python Scripts

In today’s surveillance-driven world, managing and retrieving recorded videos from Network Video Recorders (NVRs) is crucial for security professionals. This blog post will introduce a set of Python scripts that automate the process of searching for and downloading recorded videos from a HIKVision NVR. The scripts enable users to specify a date range and camera track, making it easier to access and manage video footage efficiently.

The Python Scripts:

generate.py

#!/usr/bin/env python

# This scripts calls search.py to search in the HIKVision NVR for recorded videos and the uses download.py to download those videos.
# The script loops over the camera tracks and the last 120 days.

import sys
import os
import datetime

base = datetime.datetime.today().replace(hour=0, minute=0, second=0, microsecond=0);
numdays = 120;
dateList = [base - datetime.timedelta(days=x) for x in range(numdays)];

tracks = ["101", "201", "301", "401", "501", "601", "701", "801"];

for trackID in tracks:
  for dateItem in dateList:
    os.system("python search.py " + trackID + " " + dateItem.strftime('%Y-%m-%dT%H:%M:%SZ') + " " + (dateItem + datetime.timedelta(days=1)).strftime('%Y-%m-%dT%H:%M:%SZ'));

for trackID in tracks:
  for dateItem in dateList:
    os.system("python download.py " + trackID + " " + dateItem.strftime('%Y-%m-%dT%H:%M:%SZ') + " " + (dateItem + datetime.timedelta(days=1)).strftime('%Y-%m-%dT%H:%M:%SZ'));

  • This script acts as the orchestrator, controlling the entire process.
  • It generates a list of dates, spanning the last 120 days, and a list of camera tracks to search for video recordings.
  • It then iterates through each camera track and date, calling two other Python scripts: search.py and download.py.

search.py

#!/usr/bin/env python

# This script makes an API call to the HIKVision NVR with a Track ID and a datetime range and retrieves an XML list with all videos with their download links that were recorded on that camera during that time period.

import sys
import os

trackID = sys.argv[1];
startTime = sys.argv[2];
endTime = sys.argv[3];
xmlFilename = "results/" + trackID + "." + startTime + "." + endTime + ".xml";

os.system("curl 'http://username:[email protected]/ISAPI/ContentMgmt/search' --data-raw $'<?xml version='1.0' encoding='UTF-8'?>\n<CMSearchDescription><searchID>CA77BA52-0780-0001-34B2-6120F2501D36</searchID><trackList><trackID>" + trackID + "</trackID></trackList><timeSpanList><timeSpan><startTime>" + startTime + "</startTime><endTime>" + endTime + "</endTime></timeSpan></timeSpanList><maxResults>100</maxResults><searchResultPostion>0</searchResultPostion><metadataList><metadataDescriptor>//recordType.meta.std-cgi.com</metadataDescriptor></metadataList></CMSearchDescription>' -o "+ xmlFilename);

  • This script is responsible for making an API call to the HIKVision NVR to search for recorded videos.
  • It takes three command-line arguments: track ID, start time, and end time.
  • It constructs a search request in XML format and uses curl to send the request to the NVR.
  • The search results are saved as an XML file for later processing.

download.py

#!/usr/bin/env python

# This script reads an XML file that was retrieved from the HIKVision NVR which containes videos with their download links. For each link, it appends the credentials for login and uses ffmpeg to download the video.

from xml.dom import minidom
import os
import sys

trackID = sys.argv[1];
startTime = sys.argv[2];
endTime = sys.argv[3];
xmlFilename = "results/" + trackID + "." + startTime + "." + endTime + ".xml";
dom = minidom.parse(xmlFilename)
elements = dom.getElementsByTagName('playbackURI')

i = 0
for element in elements:
    video = element.firstChild.data
    video = video.replace("rtsp://10.20.30.1", "rtsp://username:[email protected]")
    video = video.replace("\n", "")
    size = video.rsplit('=', 1)[1]
    os.system("ffmpeg -i '" + video + "' -max_muxing_queue_size " + size + "0 videos/" + trackID + "." + startTime + "." + endTime + "." + str(i+1) + ".mp4;")
    i += 1
exit

  • After the search has been performed and results stored in an XML file, this script is called to download the videos.
  • It reads the XML file and extracts the video playback URLs.
  • For each video, it appends the required credentials for login and uses ffmpeg to download the video.
  • Downloaded videos are saved with a filename indicating track ID, start time, end time, and a unique index.

Usage:

To use these scripts, you’ll need to modify the following parts:

  • Update the base variable in generate.py to set the desired starting date.
  • Adjust the tracks list in generate.py to specify the camera tracks you want to search.
  • Replace username, password, and the IP address in the curl command in search.py with your NVR’s credentials and address.
  • Ensure you have ffmpeg installed on your system for video downloading.

With these Python scripts, you can automate the process of searching for and downloading recorded videos from a HIKVision NVR. This can significantly simplify video retrieval tasks for security professionals, saving time and effort in managing surveillance footage. By customizing and expanding upon these scripts, you can further enhance your video management capabilities and streamline your security operations.


Upgrading Your HIKVision DVR Firmware using the API: A Step-by-Step Guide

Regularly updating the firmware of your HIKVision DVR (Digital Video Recorder) is crucial to ensure optimal performance and security. In this blog post, we will walk you through the process of upgrading your HIKVision DVR firmware using simple command-line tools like curl. We will also show you how to check the upgrade status to ensure a smooth and successful update.

Step 1: Preparing for the Upgrade

Before you begin, make sure you have the following information and files ready:

  • Your HIKVision DVR’s IP address (e.g., 10.20.30.1).
  • The username and password for accessing your DVR’s web interface.
  • The latest firmware file in DAV format (e.g., digicap.dav). Ensure you download this file from the official HIKVision website to guarantee its authenticity.

Step 2: Initiating the Firmware Upgrade

To start the firmware upgrade process, open your terminal or command prompt and use the curl command as follows:

curl -k --request PUT --data-binary "@digicap.dav" 'http://username:[email protected]/ISAPI/System/updateFirmware';

Explanation:

  • curl: This is a command-line tool for transferring data with URLs.
  • -k: This option tells curl to allow connections to SSL sites without certificates. It’s useful when connecting to devices with self-signed certificates.
  • --request PUT: This specifies the HTTP request method as PUT, which is used for updating the firmware.
  • --data-binary "@digicap.dav": Here, we provide the firmware file in DAV format as binary data.
  • 'http://username:[email protected]/ISAPI/System/updateFirmware': Replace username and password with your DVR’s login credentials, and 10.20.30.1 with your DVR’s IP address. This URL is where the firmware update request is sent.

Step 3: Checking the Upgrade Status

To monitor the status of the firmware upgrade and ensure everything is proceeding as expected, use the following curl command:

curl -k 'http://username:[email protected]/ISAPI/System/upgradeStatus';

Explanation:

  • curl: As before, this is the command-line tool for making URL requests.
  • -k: Again, this option allows connections to SSL sites without certificates.
  • 'http://username:[email protected]/ISAPI/System/upgradeStatus': Replace the placeholders with your DVR’s login credentials and IP address. This URL is where you can check the upgrade status.

Conclusion: Updating your HIKVision DVR’s firmware is essential for keeping it secure and running smoothly. By following these simple steps and using the curl commands provided, you can ensure that your DVR is up to date with the latest firmware. Remember to download firmware updates only from trusted sources like the official HIKVision website to avoid any security risks.

Sample Outputs

$ curl  -k  --request PUT --data-binary "@digicap.dav" 'http://username:[email protected]/ISAPI/System/updateFirmware';
<?xml version="1.0" encoding="UTF-8" ?>
<ResponseStatus version="1.0" xmlns="urn:psialliance-org">
<requestURL>/ISAPI/System/updateFirmware</requestURL>
<statusCode>7</statusCode>
<statusString>Reboot Required</statusString>
<subStatusCode>rebootRequired</subStatusCode>
</ResponseStatus>

# In another terminal as the above command blocks.
#Execute the status command.
$ curl  -k  'http://username:[email protected]/ISAPI/System/upgradeStatus';
<?xml version="1.0" encoding="UTF-8" ?>
<upgradeStatus version="1.0" xmlns="http://www.hikvision.com/ver20/XMLSchema">
<upgrading>true</upgrading>
<percent>98</percent>
</upgradeStatus>

$ curl  -k  'http://username:[email protected]/ISAPI/System/upgradeStatus';
<?xml version="1.0" encoding="UTF-8" ?>
<upgradeStatus version="1.0" xmlns="http://www.hikvision.com/ver20/XMLSchema">
<upgrading>false</upgrading>
<percent>0</percent>
</upgradeStatus>

Hikvision web UI cannot change admin password

Note / Disclaimer / Caution / Warning:
We are not sure if the same commands will work on your device!
Following these instructions has some risk as not everything is well documented and could damage your device and make it unable to be repaired or used!
We are posting about our experiences as it might help someone else but we cannot guarantee positive results to other people.
We got lucky, we cannot be sure if this works for everyone...

Recently, we were performing maintenance on a Hikvision DS-KB8112-IM Vandal-Resistant Door Station. When we tried to change the password for the default administrator (called admin) we noticed that we could not edit the user. There was a bug in the list of users which was not showing the username of the admin.

That bug caused the Modify functionality to fail as well. It would leave the User Name field as blank which would trigger an error after pressing the OK button. The system complained that the User Name field is empty while it is required making the change of password to fail.

We could not figure out a way to fix it through the menus of Hikvision nor could we flash or update the device firmware, so after some search, we found the documentation of some API (which we are not sure if is actively maintained) that allowed us to get the settings of the device and update them.

Specifically, using the following command, we got the list of users on the Hikvision device:

curl -k 'https://admin:[email protected]/ISAPI/Security/users';

The GET of ISAPI/Security/users gave us the list of all users like so:

<?xml version="1.0" encoding="UTF-8" ?>
<UserList version="2.0" xmlns="http://www.isapi.org/ver20/XMLSchema">
<User version="2.0" xmlns="http://www.isapi.org/ver20/XMLSchema">
<id>1</id>
<userName>admin</userName>
<bondIpAddressList>
<bondIpAddress>
<id>1</id>
<ipAddress>0.0.0.0</ipAddress>
</bondIpAddress>
</bondIpAddressList>
<bondMacAddressList>
<bondMacAddress>
<id>1</id>
<macAddress>00:00:00:00:00:00</macAddress>
</bondMacAddress>
</bondMacAddressList>
<userLevel>Administrator</userLevel>
<attribute>
<inherent>true</inherent>
</attribute>
</User>
</UserList>

Then, for fun, we issued the command that returns the information for the admin user (that has the ID = 1):

curl -k 'https://admin:[email protected]/ISAPI/Security/users/1';
<?xml version="1.0" encoding="UTF-8" ?>
<User version="2.0" xmlns="http://www.isapi.org/ver20/XMLSchema">
<id>1</id>
<userName>admin</userName>
<userLevel>Administrator</userLevel>
<attribute>
<inherent>true</inherent>
</attribute>
</User>

Then we went for the risky part, to issue a command that would edit the settings of the device with great risk!

curl -k 'https://admin:[email protected]/ISAPI/Security/users/1' -X PUT --data-raw $'<User version="2.0" xmlns="http://www.isapi.org/ver20/XMLSchema">\n<id>1</id><userName>admin</userName><password>4321</password></User>';

The PUT command for ISAPI/Security/users/1 loaded the following XML to the device:

<User version="2.0" xmlns="http://www.isapi.org/ver20/XMLSchema">
<id>1</id>
<userName>admin</userName>
<password>4321</password>
</User>

To our pleasant surprise, it worked! After executing the above command, we were able to log in to the device using the new password. To an even more pleasant surprise, the list of users bug disappeared and we were able to use the web GUI to make changes to the administrator user!


ffmpeg: Convert HikVision H.265+ videos to MKV

The following command will find all mp4 files that are in the current directory and in all sub-folders and convert them to mkv.

Recently we needed to share some footage from a HikVision NVR which was recording to H.265+ which was a proprietary format of the company. To do so, we converted them in another format that more players could recognize the videos.

for FILE in *.mp4; do
  echo -e "Processing video '\e[32m$FILE\e[0m'";
  ffmpeg -i "${FILE}" -analyzeduration 2147483647 -probesize 2147483647 -c:v libx265 -an -x265-params crf=0 "${FILE%.mp4}.mkv";
done;

The filename of the mkv file will be the same as the mp4 video with the correct extension. The mp4 extension will be removed and replaced by the mkv extension e.g hi.mp4 will become hi.mkv

A few notes, the compression they use seems really good, the size of the original video is very small in comparison to the generated result.