python3 filter out certain text from server output to a variable

Viewed 68

I am trying to filter out the response from a server.

Example:

b'RTSP/1.0 401 Unauthorized\r\nCSeq: 2\r\nWWW-Authenticate: Digest realm="Login to YR3EI16746R4O", nonce="8986086a1fv82683a0898142be7ze74"\r\n\r\n'

CSeq: 2 and nonce="8986086a1fv82683a0898142be7ze74f" are important to me. I should be able to read these answers to a variable. For Cseq could i do the following

if 'CSeq: 1' in data:
   cseq = "CSeq: 1"
elif 'CSeq: 2' in data:
   cseq = "CSeq: 1"
elif....

But this is not a proper way and does not solve the nonce= problem. How can I read the response from the server Ex: Read 2 chars after CSeq: or read 30 chars after nonce=" to a variable?

Thanks.

3 Answers

I would extract nonce value following way

message = b'RTSP/1.0 401 Unauthorized\r\nCSeq: 2\r\nWWW-Authenticate: Digest realm="Login to YR3EI16746R4O", nonce="8986086a1fv82683a0898142be7ze74"\r\n\r\n'
nonce_pos = message.find(b'nonce')
quote_1_pos = message.find(b'"',nonce_pos)
quote_2_pos = message.find(b'"',quote_1_pos+1)
nonce = message[quote_1_pos+1:quote_2_pos]
print(nonce)

output

b'8986086a1fv82683a0898142be7ze74'

Explanation: bytes.find method is similar to (probably more often used) str.find method, it has 1 compulsory argument: substring to look for and 2 optional arguments: start and end. It does return position of start of substring. Firstly I find position of nonce, then position of first " after that, then position of following ", after that I slice message to get nonce value (note +1 as slicing is inclusive-exclusive)

Disclaimer: this solution assumes nonce is present in message

For tasks like this you should use a regular expression

import re

resp = b'RTSP/1.0 401 Unauthorized\r\nCSeq: 2\r\nWWW-Authenticate: Digest realm="Login to YR3EI16746R4O", nonce="8986086a1fv82683a0898142be7ze74"\r\n\r\n'

pattern_CSeq = re.compile(b'CSeq: ([0-9]*)')
pattern_nonce = re.compile(b'nonce="(.*?)"')

match1 = pattern_CSeq.search(resp)
CSeq = match1.group(1)

print(CSeq)
# b'2'

match2 = pattern_nonce.search(resp)
nounce = match2.group(1)

print(nounce)
# b'8986086a1fv82683a0898142be7ze74'

I've made a python function for it

import re

text = b'RTSP/1.0 401 Unauthorized\r\nCSeq: 2\r\nWWW-Authenticate: Digest realm="Login to YR3EI16746R4O", nonce="8986086a1fv82683a0898142be7ze74"\r\n\r\n'

new_text = text.decode()

elements = new_text.split('\r\n')
def find_elements(ele1):
    for element in elements:
        if ele1 in element:
            index = element.find(ele1)
            value = element[index+len(ele1):]
            print(re.sub('\W+','', value))
            
find_elements("nonce")

output

8986086a1fv82683a0898142be7ze74
Related