184 lines
8.2 KiB
Python
184 lines
8.2 KiB
Python
"""Hikvision NVR WebSocket download tool (debug version with verbose logging)"""
|
|
import json,sys,time,os,hashlib,struct,socket,subprocess,shutil
|
|
from base64 import b64encode
|
|
from xml.etree import ElementTree as ET
|
|
import requests
|
|
|
|
def main():
|
|
# 支持命令行参数或写死的测试参数
|
|
if len(sys.argv) > 1:
|
|
cfg = json.loads(sys.argv[1])
|
|
else:
|
|
cfg = {
|
|
"ip": "192.168.8.241",
|
|
"port": 7681,
|
|
"httpPort": 80,
|
|
"user": "admin",
|
|
"pass": "ky666888",
|
|
"channel": 33,
|
|
"start": "2026-07-01T08:00:00",
|
|
"end": "2026-07-01T08:05:00",
|
|
"speed": 4,
|
|
"output": "G:/gameauto/recordings/output.ps"
|
|
}
|
|
IP=cfg.get("ip","192.168.8.241");PORT=cfg.get("port",7681);HTTP=cfg.get("httpPort",80)
|
|
USER=cfg["user"];PASS=cfg["pass"];CH=cfg.get("channel",33)
|
|
START=cfg["start"];END=cfg["end"];SPEED=cfg.get("speed",4);OUT=cfg["output"]
|
|
NS={'h':'http://www.hikvision.com/ver20/XMLSchema'}
|
|
|
|
print("="*60+"\n Hikvision NVR WS Download (Debug)\n"+"="*60)
|
|
print(f" Device:{IP}:{HTTP} Ch:{CH} Time:{START}->{END} Speed:{SPEED}x\n Output:{OUT}")
|
|
|
|
s=requests.Session()
|
|
# [1] caps
|
|
print("\n[1] Caps...")
|
|
rand=str(int(time.time()*1000))[-8:]
|
|
caps_url = f"http://{IP}:{HTTP}/ISAPI/Security/sessionLogin/capabilities?username={USER}&random:{rand}"
|
|
print(f" >>> GET {caps_url}")
|
|
r=s.get(caps_url, timeout=5)
|
|
print(f" <<< {r.status_code}")
|
|
print(f" <<< Headers: {dict(r.headers)}")
|
|
print(f" <<< Body: {r.text}")
|
|
rt=ET.fromstring(r.text)
|
|
sid=rt.findtext('.//h:sessionID','',NS);ch=rt.findtext('.//h:challenge','',NS)
|
|
itr=int(rt.findtext('.//h:iterations','1',NS));slt=rt.findtext('.//h:salt','',NS)
|
|
ver=rt.findtext('.//h:sessionIDVersion','1',NS);vl=rt.findtext('.//h:isSessionIDValidLongTerm','false',NS)
|
|
st=rt.findtext('.//h:isSupportSessionTag','false',NS);irr=rt.findtext('.//h:isIrreversible','false',NS)=='true'
|
|
print(f" v={ver} itr={itr} irrev={irr}")
|
|
|
|
# [2] pwd
|
|
print("[2] Calc password...")
|
|
if irr:
|
|
d=hashlib.sha256((USER+slt+PASS).encode()).hexdigest();d=hashlib.sha256((d+ch).encode()).hexdigest()
|
|
for _ in range(2,itr):d=hashlib.sha256(d.encode()).hexdigest()
|
|
else:
|
|
d=hashlib.sha256((PASS+ch).encode()).hexdigest()
|
|
for _ in range(1,itr):d=hashlib.sha256(d.encode()).hexdigest()
|
|
print(f" digest={d[:16]}...")
|
|
|
|
# [3] login
|
|
print("[3] Login...")
|
|
ts=str(int(time.time()*1000))
|
|
if ver=='2':
|
|
xml=f'<SessionLogin><userName>{USER}</userName><password>{d}</password><sessionID>{sid}</sessionID><isSessionIDValidLongTerm>{vl}</isSessionIDValidLongTerm><sessionIDVersion>2</sessionIDVersion><isNeedSessionTag>{st}</isNeedSessionTag></SessionLogin>'
|
|
else:
|
|
xml=f'<SessionLogin><userName>{USER}</userName><password>{d}</password><sessionID>{sid}</sessionID></SessionLogin>'
|
|
login_url = f"http://{IP}:{HTTP}/ISAPI/Security/sessionLogin?timeStamp={ts}"
|
|
print(f" >>> POST {login_url}")
|
|
print(f" >>> Headers: {{'Content-Type': 'text/plain;charset=UTF-8'}}")
|
|
print(f" >>> Body: {xml}")
|
|
r=s.post(login_url, data=xml.encode(), headers={"Content-Type":"text/plain;charset=UTF-8"}, timeout=5)
|
|
print(f" <<< {r.status_code}")
|
|
print(f" <<< Headers: {dict(r.headers)}")
|
|
print(f" <<< Body: {r.text}")
|
|
if r.status_code!=200:print(f" FAIL {r.status_code} {r.text[:200]}");sys.exit(1)
|
|
tag=ET.fromstring(r.text).findtext('.//h:sessionTag','',NS);s.headers["SessionTag"]=tag
|
|
print(f" OK tag={tag[:16]}...")
|
|
|
|
# [4] token
|
|
print("[4] Token...")
|
|
token_url = f"http://{IP}:{HTTP}/ISAPI/Security/token?format=json"
|
|
print(f" >>> GET {token_url}")
|
|
print(f" >>> Cookies: {dict(s.cookies)}")
|
|
print(f" >>> SessionTag header: {s.headers.get('SessionTag', 'N/A')[:16]}...")
|
|
r=s.get(token_url, timeout=5)
|
|
print(f" <<< {r.status_code}")
|
|
print(f" <<< Body: {r.text[:200]}")
|
|
if r.status_code!=200:
|
|
print(" SessionTag 方式失败, 尝试 Digest 认证...")
|
|
s2=requests.Session();s2.auth=requests.auth.HTTPDigestAuth(USER,PASS)
|
|
durl = f"http://{IP}:{HTTP}/ISAPI/System/deviceInfo"
|
|
print(f" >>> GET {durl} (Digest Auth)")
|
|
r2=s2.get(durl, timeout=5)
|
|
print(f" <<< {r2.status_code}")
|
|
print(f" >>> GET {token_url} (Digest Auth)")
|
|
r=s2.get(token_url, timeout=5)
|
|
print(f" <<< {r.status_code}")
|
|
print(f" <<< Body: {r.text[:200]}")
|
|
tok=r.json()["Token"]["value"]
|
|
print(f" token={tok[:40]}...")
|
|
|
|
# [5] WS
|
|
print("[5] WebSocket...")
|
|
key=b64encode(os.urandom(16)).decode()
|
|
ws_path = f"/?version=1.0&cipherSuites=1&token={tok}"
|
|
hs=(f"GET {ws_path} HTTP/1.1\r\n"
|
|
f"Host: {IP}:{PORT}\r\nUpgrade: websocket\r\nConnection: Upgrade\r\n"
|
|
f"Sec-WebSocket-Version: 13\r\nSec-WebSocket-Key: {key}\r\n"
|
|
f"Origin: http://127.0.0.1\r\nUser-Agent: Mozilla/5.0 Chrome/149.0\r\n\r\n")
|
|
print(f" >>> WS connect to {IP}:{PORT}")
|
|
print(f" >>> WS Handshake:")
|
|
for l in hs.split('\r\n'):
|
|
if l: print(f" {l}")
|
|
sk=socket.socket();sk.settimeout(10);sk.connect((IP,PORT));sk.send(hs.encode())
|
|
resp=b""
|
|
while b"\r\n\r\n" not in resp:resp+=sk.recv(4096)
|
|
print(f" <<< WS 握手响应:")
|
|
hdr = resp[:resp.find(b"\r\n\r\n")].decode()
|
|
for l in hdr.split('\r\n'):
|
|
if l: print(f" {l}")
|
|
rem=resp[resp.find(b"\r\n\r\n")+4:]
|
|
print(f" OK shake: {rem[2:].decode()}" if len(rem)>2 else " OK")
|
|
|
|
def ws_send(data):
|
|
p=data.encode() if isinstance(data,str) else data
|
|
f=bytearray([0x81 if isinstance(data,str) else 0x82]);l=len(p)
|
|
if l<126:f.append(l)
|
|
elif l<65536:f.extend([126,*struct.pack(">H",l)])
|
|
else:f.extend([127,*struct.pack(">Q",l)])
|
|
f.extend(p);sk.send(bytes(f))
|
|
def ws_recv():
|
|
h=sk.recv(2)
|
|
if len(h)<2:return None
|
|
op,l=h[0]&0xF,h[1]&0x7F
|
|
if l==126:l=struct.unpack(">H",sk.recv(2))[0]
|
|
elif l==127:l=struct.unpack(">Q",sk.recv(8))[0]
|
|
d=b""
|
|
while len(d)<l:d+=sk.recv(l-len(d))
|
|
if op==0x01:return d.decode()
|
|
if op==0x02:return d
|
|
return d
|
|
|
|
cmd={"sequence":0,"cmd":"playback","url":f"live://{IP}:{PORT}/{CH}/0","startTime":START,"endTime":END}
|
|
print(f" >>> WS Playback cmd: {json.dumps(cmd)}")
|
|
ws_send(json.dumps(cmd))
|
|
|
|
os.makedirs(os.path.dirname(OUT)or".",exist_ok=True)
|
|
f=open(OUT,"wb");total=0;chunks=0;ss=False;t0=time.time();lr=t0;sk.settimeout(120)
|
|
while True:
|
|
try:msg=ws_recv()
|
|
except socket.timeout:print(f"\n timeout");break
|
|
if msg is None:print(f"\n closed");break
|
|
if isinstance(msg,str):
|
|
d=json.loads(msg);sc=d.get("statusCode",0)
|
|
print(f"\n <- {sc} {d.get('statusString','')}")
|
|
if sc==1:continue
|
|
break
|
|
elif isinstance(msg,bytes):
|
|
chunks+=1;total+=len(msg);f.write(msg)
|
|
if not ss and chunks>=10:
|
|
spd_cmd = json.dumps({"sequence":0,"cmd":"speed","rate":SPEED})
|
|
print(f"\n -> speed x{SPEED} cmd: {spd_cmd}")
|
|
ws_send(spd_cmd);ss=True
|
|
if time.time()-lr>0.5:
|
|
el=time.time()-t0;print(f"\r [{chunks:5d}] {total/1048576:.2f}MB {total/el/1024:.0f}KB/s {el:.0f}s",end="");lr=time.time()
|
|
|
|
sk.close();f.close()
|
|
el=time.time()-t0;mb=total/1048576 if total else 0
|
|
print(f"\n[6] Done: {chunks}chunks {mb:.1f}MB {el:.1f}s {mb/el*8 if el>0 else 0:.1f}Mbps")
|
|
|
|
if mb==0:return print(json.dumps({"success":False,"output":OUT,"size":0}))
|
|
|
|
mp4=OUT.replace(".ps",".mp4")
|
|
print(f"[7] Transcode -> {mp4}")
|
|
ff=shutil.which("ffmpeg") or os.path.join(os.environ.get("APPDATA",""),"npm","node_modules","@ffmpeg-installer","ffmpeg","node_modules","@ffmpeg-installer","win32-x64","ffmpeg.exe")
|
|
if ff and os.path.exists(ff):
|
|
subprocess.run([ff,"-i",OUT,"-c","copy",mp4,"-y"],capture_output=True,timeout=60)
|
|
ms=os.path.getsize(mp4);os.remove(OUT)
|
|
print(f" OK: {ms/1048576:.1f}MB")
|
|
print("\n"+"="*60+"\n"+json.dumps({"success":True,"output":mp4,"size":ms,"duration":el,"speed":SPEED})+"\n"+"="*60)
|
|
else:
|
|
print(f" No ffmpeg, raw PS: {OUT}")
|
|
|
|
if __name__=="__main__":main()
|