将BASH脚本转换为Python问题

时间:2019-02-12 20:20:14

标签: python bash

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

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)

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

2 个答案:

答案 0 :(得分: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 :(得分:0)

尽管真正的编程语言的优点之一就是强大的库(用于解析XML的 eg )的可用性,但是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]
相关问题