Python Multiline String Find - python

I have an Cisco ASA with a VPN tunnel configured. I call the CLI command via API and it returns this multiline string:
\nSession Type: LAN-to-LAN\n\nConnection : 192.168.1.10\nIndex : 11701 IP Addr : 192.168.1.10\nProtocol : IKEv2 IPsecOverNatT\nEncryption : IKEv2: (1)AES256 IPsecOverNatT: (1)AES256\nHashing : IKEv2: (1)SHA256 IPsecOverNatT: (1)SHA256\nBytes Tx : 0 Bytes Rx : 0\nLogin Time : 23:14:43 EST Fri Dec 3 2021\nDuration : 0h:11m:50s\n\n
I can't figure out how to get only the "Bytes Rx" plus the number out beside it. I've tried searching it like this, but it returns "Bytes Tx":
import re
regex_parse = re.compile(r'[a-zA-Z]+\s[a-zA-Z][a-zA-Z]\s+:\s[0-9]+')
multilinestring = webhook_api_call()
for item in multilinestring:
a = regex_parse.search(item)
print(a.group(0))
Output:
Bytes Tx : 0
I want to only get Bytes Rx and the number out beside it

Looks like you are trying to parse the result of sh vpn-sessiondb l2l from a Cisco ASA. The output is pretty standard, so I would skip the regex and do the following:
multilinestring = webhook_api_call()
lines = multilinestring.split("\n")
for l in lines:
if l.find("Bytes Tx") != -1:
print("Bytes Rx" + l.partition("Bytes Rx")[2])
Output:
Bytes Rx : 0
Good luck with your code!

Related

How to convert python HEX ouput to ASCII?

I'd like to convert HEX output in python to ASCII when i'm using LiveCapture from pyshark.
My code:
capture = pyshark.LiveCapture(interface='en1',
bpf_filter='tcp port 5555 and len > 66',)
colored.OK("Interface bindée sur %s" % socket.gethostbyname(socket.gethostname()))
for packet in capture.sniff_continuously():
if packet.ip.src == socket.gethostbyname(socket.gethostname()):
colored.OK("Send packets")
else:
colored.OK("Receive packets")
print(''.join(packet.data.data.split(":")))
print("")
Output for receive packets:
66787874798582124495051
I'd like to convert this output to ASCII char directly in the python output
Is it possible?
Thanks
Yes, you can convert it directly.
def convert_HEX_to_ASCII(h):
chars_in_reverse = []
while h != 0x0:
chars_in_reverse.append(chr(h & 0xFF))
h = h >> 8
chars_in_reverse.reverse()
return ''.join(chars_in_reverse)
print (convert_HEX_to_ASCII(0x6176656e67657273))
print (convert_HEX_to_ASCII(0x636f6e766572745f4845585f746f5f4153434949))
Refer link, which convert HEX to ASCII online. https://www.rapidtables.com/convert/number/ascii-to-hex.html
You can verify the output manually and confirm the result.
Similar code is available on :
https://www.geeksforgeeks.org/convert-hexadecimal-value-string-ascii-value-string/

Last for iteration produce "None" output

I'm writing a script to test latency between output switches and public IP using Pexpect and regex.
Here is a sample:
# Connect to a cisco system just before and going enable
for key in nodes:
ipaddr_node = nodes[key]["IP Address"]
print ('[|] Ping de %s en cours ...' % ipaddr_node)
p.sendline("ping %s repeat 20" % ipaddr_node) #ping of the ip 20 times on cisco
p.expect('#')
ping = p.before #get the output before '#'
print ('[+] Ping de %s reussi' % ipaddr_node)
place = ping.find('min') #get the position of 'min' in output
regex = ping.replace(ping[:place],"")
output = re.search(r'\s=\s(?P<min>\d{1,4}.\d{0,3})\/(?P<avg>\d{1,4}.\d{0,3})\/(?P<max>\d{1,4}.\d{0,3})', regex) #regex to get min, avg and max
print(output) #Print regex object
avg = output.group('avg') #get value of group "avg" in regex
print('[+] Average time : ' + avg) #print it
Here is an output example:
('min/avg/max = 33/44/51 ms\r\nRTR-LAB-GRE', '<= string for regex to work on')
(<_sre.SRE_Match object at 0x7f2d68ea11f8>, '<= Regex object')
[+] Temps moyen : 44
('min/avg/max = 41/46/59 ms\r\nRTR-LAB-GRE', '<= string for regex to work on')
(<_sre.SRE_Match object at 0x7f2d68ea1290>, '<= Regex object')
[+] Temps moyen : 46
('min/avg/max = 41/41/42 ms\r\nRTR-LAB-GRE', '<= string for regex to work on')
(<_sre.SRE_Match object at 0x7f2d68ea11f8>, '<= Regex object')
[+] Temps moyen : 41
('min/avg/max = 1/3/9 ms\r\nRTR-LAB-GRE', '<= string for regex to work on')
(None, '<= Regex object')
Traceback (most recent call last):
File "EssaiPexpect.py", line 95, in <module>
avg = output.group('avg')
AttributeError: 'NoneType' object has no attribute 'group'
The dict containing IP to test contains 4 IPs.
My node is a dict containing IP and others informations, but this works for sure.
Also my regex variable looks like this every time (even in the last iteration): min/avg/max = 1/3/9 ms
I'm sure this is a simple thing, but I can't get my finger on it.
Solution found !
This was a simple mistake in my regex search.
This was the old one : Output of Regex101 of old regex
This is the new one : Ouput of Regex 101 of new regex
To simplify, my first request couldn't find the last line because my . wasn't escaped properly.
I just added a good escape plus a or between both possibilities.
Thank you for your help.

Is the output of scapy.sprintf a raw string?why the length is wrong?

I want to analyze TCP packets by scapy. And I use pkt.sprintf('%Raw.load%') to extract tcp data. But the output string has something wrong with length. but the '\' is deemed to be a str instead of a Escaped character.so '\x11' is considered as 4 different strings instead of a ASCII character.
Here are my codes:
from scapy.all import *
def findTCPdata(pkt):
raw = pkt.sprintf("%Raw.load%")
print raw
print 'length of TCP data: '+ str(len(raw))
def main():
pkts = rdpcap('XXX.pcap')
for pkt in pkts:
findTCPdata(pkt)
if __name__ == '__main__':
main()
enter image description here
The length of each tcp data should be 17 instead of the value in screen(53,52,46,52).
4 tcp data are:
'U\x11\x04\x92\x02\x03\x1e\x03#\x03\xf8q=e\xcb\x15\r'
'U\x11\x04\x92\x02\x03.\x03#\x03\xf8q=e\xcb\xb8\x05'
'U\x11\x04\x92\x02\x03X\x03#\x03\xf8q=e\xcbiO'
'U\x11\x04\x92\x02\x03n\x03#\x03\xf8q=e\xcb\xdb\xe3'
Please help me solve the problem.Thank you!
i see. i need a function to transform rawstring to string.
so i add codes after line 3(raw = pkt.sprintf("%Raw.load%")) like:
raw = raw.replace('\'','')
string = raw.decode('string_escape')
then the output is right

issue with formatting characters

having a bit of an issue displaying characters
i have a payload recieved from a protocol request :
538cb9350404521a6c44020404563b152606102001085800020002aabb0000563b1526000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
the length of that is 509
what i want to display is the first 4 bytes, then 1 byte, then 1 byte
538cb935
04
04
currently to view the payload i am doing the following :
tm = struct.unpack(">L", payload[0:4])
print "Time : ", tm
ouroripv = struct.unpack(">b", payload[5])
print "Our onion address : "
print "Ip version : ", ouroripv
ouroraddrlen = struct.unpack(">b", payload[6]) # Giving a length of 82 etc atm
print "Ip length : ", ouroraddrlen
i get the result :
Time : (1401731381,)
Our onion address :
Ip version : (4,)
Ip length : (82,)
as you can see the Ip length, the 6th byte in on the payload is displaying 82 rather than the 4 it should be, what is the correct struct.unpack command that is needed to display this ?
how can i do this ?
Thanks guys
in python, the slicing doesn't include the last value, so payload[0:4] takes the first 4 bytes, from 0 to 3.
payload[3] is the fourth byte
payload[4] is the fifth byte

Dhcpd lease matching by using regex in python?

I want to match all dhcp leases that have given mac address.
I wrote this code
fh = open(leaseFile)
lines = fh.read()
fh.close()
regex = r"lease\s*[0-9\.]+\s*\{[^\{\}]*%s[^\{\}]*?\}" % mac #mac comes as parameter
m = re.findall(regex,lines,re.DOTALL)
This worked well if a lease don't contain '}' character. But if it does, my regex failed.
For example:
lease 10.14.53.253 {
starts 3 2012/10/17 09:27:20;
ends 4 2012/10/18 09:27:20;
tstp 4 2012/10/18 09:27:20;
binding state free;
hardware ethernet 00:23:18:62:31:5b;
uid "\001\000\013OW}k";
}
I couldn't figure out how I handle this exception. Thanks for any advice...
EDIT
After research, I decided to use this regex with MULTILINE mode. It worked for all leases that I tried.
fh = open(leaseFile)
lines = fh.read()
fh.close()
regex = r"lease\s*[0-9\.]+\s*\{[^\{\}]*%s[\s\S]*?^\}" % mac #mac comes as parameter
m = re.findall(regex,lines,re.MULTILINE)
regex = r'(lease\s*[0-9\.]+\s*\{[^\{\}]*%s[^\{\}]*(.*"[^\{\}]*\}|\}))' % mac #mac comes as parameter
m = re.findall(regex,lines)
This should do the trick.

Categories