gpt4 book ai didi

python - 将 BASH 脚本转换为 Python 问题

转载 作者:行者123 更新时间:2023-11-28 18:03:53 26 4
gpt4 key购买 nike

我有以下 bash 脚本,我一直在尝试将其转换为 python。我有主要部分,但我在如何翻译这两行时遇到了一些问题 cut=${auth#*<ChallengeCode>}authStr=${cut%</ChallengeCode>*} .第一个请求返回包含 <ChallengeCode> 的 XML ,我需要能够提取该代码并将其存储以备将来使用。

BASH 代码:

#!/bin/bash
IP=IP_ADDR
USER=USERNAME
PASS=PASSWORD

auth=$(curl -ks -H "Content-Type: text/xml" -c "cookies.txt" "https://${IP}/goform/login?cmd=login&user=admin&type=1")
cut=${auth#*<ChallengeCode>}
authStr=${cut%</ChallengeCode>*}
hash=$(echo -n ${authStr}:GDS3710lZpRsFzCbM:${PASS} | md5sum | tr -d '/n')
hash=$(echo $hash | cut -d' ' -f1 | tr -d '/n')
curl -ks -H "Content-Type: text/xml" -c "cookies.txt" "https://${IP}/goform/login?cmd=login&user=admin&authcode=${hash}&type=1"
curl -ks -H "Content-Type: image/jpeg" --cookie "cookies.txt" "https://${IP}/snapshot/view0.jpg" >> snapshot.jpg

Python 代码:

import requests
import hashlib

hmd5 = hashlib.md5()

ip = "192.168.100.178"
user = "admin"
password = "Password1"

auth = requests.get('https://{0}/goform/login', headers=headers, params=params, verify=False).format(ip)

chcode = (This is where I want to put the challenge code i get back from the previous request)

hstring = "{0}:GDS3710lZpRsFzCbM:{1}".format(chcode,password).encode()
hmd5.update(hstring)

hashauth = hmd5.hexdigest()

response = requests.get('https://{0}/snapshot/view0.jpg', headers=headers, cookies=cookies, verify=False).format(ip)

任何关于如何更好地改进代码的建议也将不胜感激。

最佳答案

如果您的请求返回 XML,则适合使用 XML 解析器。假设您已经导入了 xml.etree.ElementTree 可能是:

import xml.etree.ElementTree as ET

您可以让它解析您的响应:

root_el = ET.fromstring(auth.text)

然后使用 XPath(根据您的 XML 结构可能有所不同)找到您的元素并获取它包含的文本的值:

chcode = root_el.find("./ChallengeCode").text

关于python - 将 BASH 脚本转换为 Python 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54658129/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com