将BASH脚本转换为Python的问题

3

我有以下的 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)

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


1
'https://',ip,'/goform/login' that is 3 arguments. You need format: "https://{}/goform/login".format(ip) - Jean-François Fabre
1
Stack Overflow的格式非常适合针对非常具体的问题提出狭窄的问题; 我们要求删除任何不必要的代码,以便其他人能够重现您正在询问的特定问题,如[mcve]定义和http://sscce.org/的“修剪技巧”部分所述。 - Charles Duffy
2个回答

1
如果您的请求返回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

1

虽然真正的编程语言之一的优点是具有强大的库(例如,用于解析XML),但在通配符的有限使用下,您可以直接使用Bash子字符串操作的类比特别简单:

${a#*foo} — a.partition("foo")[0]
${a%foo*} — a.rpartition("foo")[-1]
${a##*foo} — a.rpartition("foo")[0]
${a%%foo*} — a.partition("foo")[-1]

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接