监控-海康威视摄像头更改OSD通道,一键更改,批量更改
监控-海康威视摄像头更改OSD通道,一键更改,只能一次更改一个,支持循环
# coding=utf-8
#监控-海康威视摄像头更改OSD通道,一键更改,批量更改
import os
import time
import requests
from requests.auth import HTTPBasicAuth, HTTPDigestAuth
import xml.etree.ElementTree as ET
#和监控摄像头通讯需要一个双方认可的密钥,可以随机生成
def generate_key():
# 生成一个16字节的随机字节数组,16字节对应128位
random_bytes = os.urandom(16)
# 将字节数组转换成十六进制字符串
hex_key = random_bytes.hex()
return hex_key
#格式数据,给摄像头输出
xml_data1 ="""
<?xml version: "1.0" encoding="utf-8"?>
<VideoOverlay>
<normalizedScreenSize>
<normalizedScreenWidth>704</normalizedScreenWidth>
<normalizedScreenHeight>576</normalizedScreenHeight>
</normalizedScreenSize>
<attribute>
<transparent>false</transparent>
<flashing>false</flashing></attribute>
<fontSize>adaptive</fontSize>
<frontColorMode>auto</frontColorMode>
<alignment>customize</alignment>
<TextOverlayList>
<TextOverlay>
<id>1</id><enabled>false</enabled><alignment>0</alignment><positionX>0</positionX><positionY>576</positionY><displayText>111</displayText></TextOverlay><TextOverlay>
<id>2</id><enabled>false</enabled><alignment>0</alignment><positionX>0</positionX><positionY>576</positionY><displayText>11</displayText></TextOverlay><TextOverlay>
<id>3</id><enabled>false</enabled><alignment>0</alignment><positionX>0</positionX><positionY>576</positionY><displayText/></TextOverlay><TextOverlay>
<id>4</id><enabled>false</enabled><alignment>0</alignment><positionX>0</positionX><positionY>576</positionY><displayText/></TextOverlay></TextOverlayList>
<DateTimeOverlay><enabled>true</enabled>
<positionY>544</positionY><positionX>0</positionX>
<dateStyle>CHR-YYYY-MM-DD</dateStyle>
<timeStyle>12hour</timeStyle>
<displayWeek>true</displayWeek></DateTimeOverlay>
<channelNameOverlay>
<enabled>true</enabled>
<positionY>48</positionY>
<positionX>336</positionX>
<videoFormat>PAL</videoFormat>
</channelNameOverlay>
</VideoOverlay>
"""
def fun_GetOSD_Name(url):
# 尝试使用Basic Auth登录
session = requests.Session()
session.auth = HTTPBasicAuth(USERNAME, PASSWORD)
try:
# 发送GET请求
response = session.get(url)
# 检查状态码,如果为401则尝试Digest Auth
#print(f'response.status_code:{response.status_code}')
if response.status_code == 401:
session.auth = HTTPDigestAuth(USERNAME, PASSWORD)
response = session.get(url,timeout=5)
#print(response.text)
# 解析XML
osd_config = ET.fromstring(response.text)
elif response.status_code == 200:
# 解析XML响应以获取OSD通道名称
osd_config = ET.fromstring(response.text)
#print("OSD Configuration:", osd_config)
else:
print("Failed to retrieve OSD configuration. Status code:", response.status_code)
# 找到并打印摄像头的OSD-name元素的文本
name_element = osd_config.find('{http://www.hikvision.com/ver20/XMLSchema}name')
if name_element is not None:
osd_name = name_element.text
return osd_name
else:
print("Name element not found")
return '没找到通道名称'
except Exception as e:
print("An error occurred:", e)
def fun_New_OSD_Name(url,xml_data):
# 尝试使用Basic Auth登录
session = requests.Session()
session.auth = HTTPBasicAuth(USERNAME, PASSWORD)
try:
# 发送GET请求
response = session.get(url,timeout=5)
# 检查状态码,如果为401则尝试Digest Auth
if response.status_code == 401:
session.auth = HTTPDigestAuth(USERNAME, PASSWORD)
# 发送PUT请求,更新OSD名称
time.sleep(2)
headers = {'Content-Type': 'application/xml'}
response = session.put(url, data=xml_data2, headers=headers)
# 检查响应状态码,确认更新是否成功
if response.status_code == 200:
print("\n OSD 通道名称更改成功!.")
else:
print(f"Failed to update OSD name. Status code: {response.status_code}")
# 检查响应状态
if response.status_code == 200:
# 解析XML响应以获取OSD通道名称
osd_config = response.text
#print("OSD Configuration:", osd_config)
else:
print("Failed to retrieve OSD configuration. Status code:", response.status_code)
except Exception as e:
print("An error occurred:", e)
if __name__=='__main__':
#207辅楼楼顶设备间2(外)
# 摄像头的IP地址、用户名和密码
HOST1=input('请输入ip地址前3位不要少写最后的【点】:默认:10.25.27.')
if not HOST1:
HOST1='10.25.27.'
USERNAME = 'admin'
PASSWORD = 'qlyy1234'
#跳转1:
while 1:
HOST2 = input('\n请输入ip地址最后三位:\n\n')
HOST=HOST1+HOST2
asekey=generate_key()
#url1:输出格式的地址;url2:输出OSD名字的地址,后边的密钥可以是任意值
url1=f'http://{HOST}/ISAPI/System/Video/inputs/channels/1/overlays'
url2=f'http://{HOST}/ISAPI/System/Video/inputs/channels/1/?security=1&iv={asekey}'
#获取通道名称
OldName=fun_GetOSD_Name(url2)
print(f'{HOST:}当前通道名称:{OldName}')
New_OSD_Name=input('\n请输入新的通道名称:\n\n')
if not New_OSD_Name:
New_OSD_Name=OldName
# 构建XML数据,注意这里的XML数据格式应该符合Hikvision API的要求
#OSD通道数据,给设想头设置
xml_data2 = f"""
<?xml version: "1.0" encoding="UTF-8"?><VideoInputChannel xmlns="http://www.hikvision.com/ver20/XMLSchema" version="2.0">
<id>1</id>
<inputPort>1</inputPort>
<name>{New_OSD_Name}</name>
<videoFormat>PAL</videoFormat>
</VideoInputChannel>
"""
#执行摄像头通道名称更改
fun_New_OSD_Name(url2,xml_data2)
#获取修改后的通道名称
NewName=fun_GetOSD_Name(url2)
print(f'{HOST:}当前通道名称:{NewName}')
海康威视更改摄像头IP地址,更改后重启,可以两台互换ip不冲突。
# coding=utf-8
#海康威视更改摄像头IP地址,更改后重启,可以两台互换ip不冲突。
import os
import time
import requests
from requests.auth import HTTPBasicAuth, HTTPDigestAuth
import xml.etree.ElementTree as ET
#和监控摄像头通讯需要一个双方认可的密钥,可以随机生成
def generate_key():
# 生成一个16字节的随机字节数组,16字节对应128位
random_bytes = os.urandom(16)
# 将字节数组转换成十六进制字符串
hex_key = random_bytes.hex()
return hex_key
#格式数据,给摄像头输出
def fun_GetIP(url):
# 尝试使用Digest Auth登录,不是Basic Auth
session = requests.Session()
session.auth = HTTPDigestAuth(USERNAME, PASSWORD) # 确保USERNAME和PASSWORD已经被定义
while True:
try:
# 发送GET请求
response = session.get(url,timeout=5)
# 检查响应状态码
if response.status_code == 200:
# 将HTML转化为ElementTree对象
ip_config = ET.fromstring(response.text) # 使用response.text
# 将Element转换为字符串并打印
#xml_str = ET.tostring(ip_config, encoding='unicode')
#print(xml_str)
# 提取命名空间
# 注意:命名空间的格式应该是这样的:'{http://www.hikvision.com/ver20/XMLSchema}'
ns = {'ns': 'http://www.hikvision.com/ver20/XMLSchema'} # 注意这里命名空间的格式
# 查找ipv4的ipaddress
# 根据返回的XML结构,可能需要使用ip_config
# 并且命名空间需要正确添加到'ipAddress'前面
ip_address = ip_config.find('.//ns:ipAddress', ns).text
return ip_address
else:
print("Request failed with status code:", response.status_code)
return None
except requests.exceptions.Timeout:
print("Connection timed out. Do you want to retry?")
choice = input("输入1重连,输入2退出: ")
if choice != '1':
print("Returning to main program.")
return None
except Exception as e:
print("An error occurred:", e)
return None
def fun_New_IPAddress(url,xml_data,rebootUrl):
# 尝试使用Basic Auth登录
session = requests.Session()
session.auth = HTTPDigestAuth(USERNAME, PASSWORD)
try:
# 发送GET请求
response = session.get(url)
# 发送PUT请求,更新IP地址
time.sleep(2)
headers = {'Content-Type': 'application/xml'}
response = session.put(url, data=xml_data, headers=headers)
# 检查响应状态码,确认更新是否成功
if response.status_code == 200:
print("\n IP更改成功!")
response1=session.put(rebootUrl,data='', headers=headers)#重启设备
print('重启设备------------------------------------------------')
else:
print(f"Failed to update OSD name. Status code: {response.status_code}")
# 检查响应状态
if response.status_code == 200:
print('建立连接成功!')
else:
print("建立连接失败:", response.status_code)
except Exception as e:
print("An error occurred:", e)
if __name__=='__main__':
#207辅楼楼顶设备间2(外)
# 摄像头的IP地址、用户名和密码
HOST1=input('请输入ip地址前6位不要少写最后的【点】:默认:10.25.')
if not HOST1:
HOST1='10.25.'
USERNAME = 'admin'
PASSWORD = 'qlyy1234'
#跳转1:
while 1:
HOST2 = input('\n请输入原始ip地址最后6位(例如:27.21):\n\n')
HOST=HOST1+HOST2
asekey=generate_key()
#url1:输出格式的地址;url2:输出OSD名字的地址,后边的密钥可以是任意值
url1=f'http://{HOST}/ISAPI/System/Video/inputs/channels/1/overlays'
url2=f'http://{HOST}/ISAPI/System/Video/inputs/channels/1/?security=1&iv={asekey}'
url3=f'http://{HOST}/ISAPI/System/Network/interfaces/1'#更改ip地址
url4=f'http://{HOST}/ISAPI/System/Network/interfaces?security=1&iv={asekey}'#获取ip地址
rebootUrl=f'http://{HOST}/ISAPI/System/reboot'
#获取通道名称
OldIPAddress=fun_GetIP(url4)
print(f'当前IP地址:{OldIPAddress}')
HOST2=input('\n请输入新的地址后6位(例如:31.21)【q:退出】:\n\n')
if not HOST2:
New_IPAddress=OldIPAddress
elif HOST2 == 'q':
exit
else:
New_IPAddress=HOST1+HOST2
xml_data3 = f"""
<?xml version: "1.0" encoding="UTF-8"?>
<NetworkInterface>
<id>1</id>
<IPAddress>
<ipVersion>dual</ipVersion>
<addressingType>static</addressingType>
<ipAddress>{New_IPAddress}</ipAddress>
<subnetMask>255.255.224.0</subnetMask>
<ipV6AddressingType>ra</ipV6AddressingType>
<DefaultGateway>
<ipAddress>10.25.27.254</ipAddress>
</DefaultGateway>
<PrimaryDNS>
<ipAddress>114.114.114.114</ipAddress>
</PrimaryDNS>
<SecondaryDNS>
<ipAddress>8.8.8.8</ipAddress>
</SecondaryDNS></IPAddress>
</NetworkInterface>
"""
#执行摄像头通道名称更改
fun_New_IPAddress(url3,xml_data3,rebootUrl)
监控-获取所有摄像头的OSD通道名称[ip.txt]
# coding=utf-8
#监控-获取所有摄像头的OSD通道名称[ip.txt]
import os
import time
import requests
from requests.auth import HTTPBasicAuth, HTTPDigestAuth
import xml.etree.ElementTree as ET
#注意:和ip.txt放在一个文件夹,会生成ip_name.txt文件
#根据ip地址清单,获取摄像头的信息
#和监控摄像头通讯需要一个双方认可的密钥,可以随机生成
def generate_key():
# 生成一个16字节的随机字节数组,16字节对应128位
random_bytes = os.urandom(16)
# 将字节数组转换成十六进制字符串
hex_key = random_bytes.hex()
return hex_key
def fun_GetOSD_Name(url):
# 尝试使用Basic Auth登录
session = requests.Session()
session.auth = HTTPDigestAuth(USERNAME, PASSWORD)
try:
# 发送GET请求
response = session.get(url,timeout=5)
if response.status_code == 200:
# 解析XML响应以获取OSD通道名称
osd_config = ET.fromstring(response.text)
#print("OSD Configuration:", osd_config)
else:
print("Failed to retrieve OSD configuration. Status code:", response.status_code)
# 找到并打印摄像头的OSD-name元素的文本
name_element = osd_config.find('{http://www.hikvision.com/ver20/XMLSchema}name')
if name_element is not None:
osd_name = name_element.text
return osd_name
else:
print("Name element not found")
return '没找到通道名称'
except Exception as e:
print("An error occurred:", e)
def get_ip_list():
#从txt中获得ip列表,根据列表获得摄像头信息并,存入txt中
# 文件路径
file_path =f'{os.getcwd()}/ip.txt'
# 创建一个空列表来存储每一行的数据
data_list = []
try:
# 打开文件
with open(file_path, 'r', encoding='utf-8') as file:
# 逐行读取文件内容
for line in file:
# 去除行尾的换行符(\n 或 \r\n),然后添加到列表中
data_list.append(line.strip())
except FileNotFoundError:
print(f"Error: The file {file_path} does not exist.")
except Exception as e:
print(f"An error occurred: {e}")
# 打印列表,验证是否正确读取了文件内容
print(data_list)
return data_list
if __name__=='__main__':
USERNAME = 'admin'
PASSWORD = 'qlyy1234'
ip_list=[]
ip_list=get_ip_list()
#跳转1:
ip_name_list=[]
for ip in ip_list:
HOST=ip
asekey=generate_key()
#url1:输出格式的地址;url2:输出OSD名字的地址,后边的密钥可以是任意值
url1=f'http://{HOST}/ISAPI/System/Video/inputs/channels/1/overlays'
url2=f'http://{HOST}/ISAPI/System/Video/inputs/channels/1/?security=1&iv={asekey}'
#获取通道名称
Name=fun_GetOSD_Name(url2)
ip_name=f'{ip}\t{Name}'
ip_name_list.append(ip_name)
print(ip_name)
time.sleep(0.2)
#写入文本
# 文件路径
file_path =f'{os.getcwd()}/ip_osd.txt'
# 如果文件存在,则先重命名
if os.path.exists(file_path):
new_file_path = file_path + '.bak'
os.rename(file_path, new_file_path)
try:
# 打开文件,如果不存在则会被创建
with open(file_path, 'a', encoding='utf-8') as file:
# 写入列表中的每个元素,每行一个
for ip_name in ip_name_list:
file.write(ip_name + '\n')
except IOError as e:
print(f"An error occurred while writing to the file: {e}")
else:
print(f"Successfully wrote data to {file_path}")
# 如果之前重命名了文件,可以在这里做进一步处理,例如删除旧文件或记录日志
监控-海康威视摄像头批量更改OSD通道[ip_osd.txt]
# coding=utf-8
#监控-海康威视摄像头批量更改OSD通道[ip_osd.txt]
import os
import time
import requests
from requests.auth import HTTPBasicAuth, HTTPDigestAuth
import xml.etree.ElementTree as ET
"""
需要在同一个文件夹创建ip_osd.txt,每行一个数据例如:
ip_osd.txt的内容(用tab分割)
10.25.25.10 控制室监控
10.25.25.11 UPS监控
"""
#和监控摄像头通讯需要一个双方认可的密钥,可以随机生成
def generate_key():
# 生成一个16字节的随机字节数组,16字节对应128位
random_bytes = os.urandom(16)
# 将字节数组转换成十六进制字符串
hex_key = random_bytes.hex()
return hex_key
def get_ip_osd_list():
#从txt中获得ip列表,根据列表获得摄像头信息并,存入txt中
# 文件路径
file_path =f'{os.getcwd()}/ip_osd.txt'
# 创建一个空列表来存储每一行的数据
data_list = []
try:
# 打开文件
with open(file_path, 'r', encoding='utf-8') as file:
# 逐行读取文件内容
for line in file:
# 去除行尾的换行符(\n 或 \r\n),然后添加到列表中
data_list.append(line.strip())
except FileNotFoundError:
print(f"Error: The file {file_path} does not exist.")
except Exception as e:
print(f"An error occurred: {e}")
# 打印列表,验证是否正确读取了文件内容
print(data_list)
return data_list
def fun_GetOSD_Name(url):
# 尝试使用Basic Auth登录
session = requests.Session()
session.auth = HTTPBasicAuth(USERNAME, PASSWORD)
try:
# 发送GET请求
response = session.get(url)
# 检查状态码,如果为401则尝试Digest Auth
#print(f'response.status_code:{response.status_code}')
if response.status_code == 401:
session.auth = HTTPDigestAuth(USERNAME, PASSWORD)
response = session.get(url,timeout=5)
#print(response.text)
# 解析XML
osd_config = ET.fromstring(response.text)
elif response.status_code == 200:
# 解析XML响应以获取OSD通道名称
osd_config = ET.fromstring(response.text)
#print("OSD Configuration:", osd_config)
else:
print("Failed to retrieve OSD configuration. Status code:", response.status_code)
# 找到并打印摄像头的OSD-name元素的文本
name_element = osd_config.find('{http://www.hikvision.com/ver20/XMLSchema}name')
if name_element is not None:
osd_name = name_element.text
return osd_name
else:
print("Name element not found")
return '没找到通道名称'
except Exception as e:
print("An error occurred:", e)
def fun_New_OSD_Name(HOST,url,xml_data):
# 尝试使用Basic Auth登录
session = requests.Session()
session.auth = HTTPBasicAuth(USERNAME, PASSWORD)
try:
# 发送GET请求
response = session.get(url,timeout=5)
# 检查状态码,如果为401则尝试Digest Auth
if response.status_code == 401:
session.auth = HTTPDigestAuth(USERNAME, PASSWORD)
# 发送PUT请求,更新OSD名称
time.sleep(2)
headers = {'Content-Type': 'application/xml'}
response = session.put(url, data=xml_data2, headers=headers)
# 检查响应状态码,确认更新是否成功
if response.status_code == 200:
print(f"\n {HOST}:OSD 通道名称更改成功!")
else:
print(f"Failed to update OSD name. Status code: {response.status_code}")
# 检查响应状态
if response.status_code == 200:
# 解析XML响应以获取OSD通道名称
osd_config = response.text
#print("OSD Configuration:", osd_config)
else:
print("Failed to retrieve OSD configuration. Status code:", response.status_code)
except Exception as e:
print("An error occurred:", e)
if __name__=='__main__':
#207辅楼楼顶设备间2(外)
# 摄像头的IP地址、用户名和密码
USERNAME = 'admin'
PASSWORD = 'qlyy1234'
#获得ip_osd_list列表:
ip_osd_list=[]
ip_osd_list=get_ip_osd_list()
for ip_osd in ip_osd_list:
asekey=generate_key()
HOST, New_OSD_Name = ip_osd.split('\t')
#url1:输出格式的地址;url2:输出OSD名字的地址,后边的密钥可以是任意值
url1=f'http://{HOST}/ISAPI/System/Video/inputs/channels/1/overlays'
url2=f'http://{HOST}/ISAPI/System/Video/inputs/channels/1/?security=1&iv={asekey}'
#OSD通道数据,给设想头设置
xml_data2 = f"""
<?xml version: "1.0" encoding="UTF-8"?><VideoInputChannel xmlns="http://www.hikvision.com/ver20/XMLSchema" version="2.0">
<id>1</id>
<inputPort>1</inputPort>
<name>{New_OSD_Name}</name>
<videoFormat>PAL</videoFormat>
</VideoInputChannel>
"""
#执行摄像头通道名称更改
fun_New_OSD_Name(HOST,url2,xml_data2)
time.sleep(0.5)