Within a file (example data below) there are groups of similar output in which we search for specific text in a line. Within each group of text, if the issuerID and subjectID are both present, print those two items along with the sourceIP and destIP. If not, skip and move on to the next. The code below works, but I am looking to add logic to only print the desired information if the issuerID and subjectID are a match.
Here is the current iteration of the script.
#!/usr/bin/python
import re
sourceIP = 'Source IP:'
destIP = 'Destination IP:'
issuerID = 'Issuer ID:'
subjectID = 'Subject ID:'
for line in open('data.txt', 'r'):
line = line.strip()
if line.startswith(sourceIP):
sourceIPline = line
elif line.startswith(destIP):
destIPline = line
elif line and line.startswith(issuerID):
issuerDomain = re.search("www[\w.com]+", line)
elif line and line.startswith(subjectID):
subjectDomain = re.search("www[\w.net]+", line)
print (sourceIPline)
print (destIPline)
print issuerDomain.group()
print subjectDomain.group()
print
If I run the code with the data-set below which a value doesn't meet meet the criteria, I get an error. I would prefer this group is ignored and move on.
$ ./dparser.py
Source IP: 10.0.0.126
Destination IP: 8.8.8.8
www.domain.com
www.domain.net
Source IP: 10.0.0.126
Destination IP: 8.8.4.4
www.domain2.com
Traceback (most recent call last):
File "./dparser.py", line 22, in <module>
print subjectDomain.group()
AttributeError: 'NoneType' object has no attribute 'group'
Here is a sample data-set with two groups.
-------------------------------
Template ID is 45841
Application Label: 443
Source IP: 10.0.0.126
Destination IP: 8.8.8.8
Source Port: 38946
Dest Port: 443
flowStartTime: 2013-12-30 20:20:21
flowEndTime: 2013-12-30 20:21:37
flowEndReason: 3
Protocol: 6
Octet Total Count: 8497
Rev Octet count: 28802
Packet Total Count: 30
Rev Packet Total Count: 32
TCP Sequence Number: 561150853
Initial TCP Flags: S
Union TCP Flags: APF
Reverse TCP Sequence Number: 4118697381
Reverse Initial TCP Flags: AS
Reverse Union TCP Flags: APF
SSL Server Cipher: 49171
-- X.509 Cert 0 (v.2) ---
Issuer ID: 3 Val: www.domain.com
Subject ID: 3 Val: www.domain.net
Valid Not Before: 131015000000Z
Not Valid After: 140211235959Z
Public Key Length: 0
--- End of Cert 0 ---
-------------------------------
Template ID is 45841
Application Label: 443
Source IP: 10.0.0.126
Destination IP: 8.8.4.4
Source Port: 42529
Dest Port: 443
flowStartTime: 2013-12-30 20:20:22
flowEndTime: 2013-12-30 20:21:37
flowEndReason: 3
Protocol: 6
Octet Total Count: 8341
Rev Octet count: 26678
Packet Total Count: 27
Rev Packet Total Count: 30
TCP Sequence Number: 3052048930
Initial TCP Flags: S
Union TCP Flags: APF
Reverse TCP Sequence Number: 101975511
Reverse Initial TCP Flags: AS
Reverse Union TCP Flags: APF
SSL Server Cipher: 49171
-- X.509 Cert 0 (v.2) ---
Issuer ID: 3 Val: www.domain2.com
Subject ID: 3 Val: Some Subject
Valid Not Before: 130727000000Z
Not Valid After: 140118000000Z
Public Key Length: 0
--- End of Cert 0 ---
You need to validate your regex found something. In this case the second data set does not have a domain but instead says "Some Subject".
You want something like:
if subjectDomain:
print subjectDomain.group()
else:
print line # whatever you want here...
Also, your regex is not defined correctly anyways. The [] symbols make a group of things to check. You really want r'www.\w+.com' otherwise you are allowing 'wwwww' and 'www.w.w'.
Related
I am reading a Pcap file with Scapy. How can I recognize if, in this pcap file, there is a packet that uses the Telnet protocol?
I see that Scapy can write 'telnet' into dport/sport only if 1 of those ports is 23, but if I am using another port for Telnet, how do I recognize this with Scapy?
#TimRoberts stated in the comments that "Telnet is indistinguishable from other TCP protocols." This is true to some extent, because all TCP packets use the same structure, which is outlined in multiple Internet Engineering Task Force (IETF) Request for Comments (RFC) documents:
RFC 791 - Internet Protocol (IP)
RFC 793 - Transmission Control Protocol (TCP)
Here is the structure of a TCP packet.
Common application protocols such as Hypertext Transfer Protocol (HTTP), File Transfer Protocol (FTP) and Telnet all use this structure.
Concerning the application protocol Telnet. As you already know the official port assignment for the telnet protocol is port 23. Most vendors adhere to this port standard, which is why "Scapy can write 'telnet' into dport/sport only if 1 of those ports is 23."
This is the TCP layer from a Telnet session using port 23:
Layer TCP:
Source Port: 1254
Destination Port: 23
Stream index: 0
TCP Segment Len: 0
Sequence number: 0 (relative sequence number)
Sequence number (raw): 72603759
Next sequence number: 1 (relative sequence number)
Acknowledgment number: 0
Acknowledgment number (raw): 0
1010 .... = Header Length: 40 bytes (10)
Flags: 0x002 (SYN)
000. .... .... = Reserved: Not set
...0 .... .... = Nonce: Not set
.... 0... .... = Congestion Window Reduced (CWR): Not set
.... .0.. .... = ECN-Echo: Not set
.... ..0. .... = Urgent: Not set
.... ...0 .... = Acknowledgment: Not set
.... .... 0... = Push: Not set
.... .... .0.. = Reset: Not set
.... .... ..1. = Syn: Set
Expert Info (Chat/Sequence): Connection establish request (SYN): server port 23
Connection establish request (SYN): server port 23
Severity level: Chat
Group: Sequence
.... .... ...0 = Fin: Not set
TCP Flags: \xc2\xb7\xc2\xb7\xc2\xb7\xc2\xb7\xc2\xb7\xc2\xb7\xc2\xb7\xc2\xb7\xc2\xb7\xc2\xb7S\xc2\xb7
Window size value: 32120
Calculated window size: 32120
Checksum: 0x5d40 [unverified]
Checksum Status: Unverified
Urgent pointer: 0
Options: (20 bytes), Maximum segment size, SACK permitted, Timestamps, No-Operation (NOP), Window scale
TCP Option - Maximum segment size: 1460 bytes
Kind: Maximum Segment Size (2)
Length: 4
MSS Value: 1460
TCP Option - SACK permitted
TCP Option - Timestamps: TSval 1444389, TSecr 0
Timestamp value: 1444389
Timestamp echo reply: 0
TCP Option - No-Operation (NOP)
TCP Option - Window scale: 0 (multiply by 1)
Shift count: 0
Multiplier: 1
Timestamps
Time since first frame in this TCP stream: 0.000000000 seconds
Time since previous frame in this TCP stream: 0.000000000 seconds
Kind: SACK Permitted (4)
Kind: Time Stamp Option (8)
Kind: No-Operation (1)
Kind: Window Scale (3)
Length: 2
Length: 10
Length: 3
This is the TCP layer from a Telnet session using port 3005:
Layer TCP:
Source Port: 52187
Destination Port: 3005
Stream index: 0
TCP Segment Len: 0
Sequence number: 0 (relative sequence number)
Sequence number (raw): 1355255000
Next sequence number: 1 (relative sequence number)
Acknowledgment number: 0
Acknowledgment number (raw): 0
1011 .... = Header Length: 44 bytes (11)
Flags: 0x002 (SYN)
000. .... .... = Reserved: Not set
...0 .... .... = Nonce: Not set
.... 0... .... = Congestion Window Reduced (CWR): Not set
.... .0.. .... = ECN-Echo: Not set
.... ..0. .... = Urgent: Not set
.... ...0 .... = Acknowledgment: Not set
.... .... 0... = Push: Not set
.... .... .0.. = Reset: Not set
.... .... ..1. = Syn: Set
Expert Info (Chat/Sequence): Connection establish request (SYN): server port 3005
Connection establish request (SYN): server port 3005
Severity level: Chat
Group: Sequence
.... .... ...0 = Fin: Not set
TCP Flags: \xc2\xb7\xc2\xb7\xc2\xb7\xc2\xb7\xc2\xb7\xc2\xb7\xc2\xb7\xc2\xb7\xc2\xb7\xc2\xb7S\xc2\xb7
Window size value: 65535
Calculated window size: 65535
Checksum: 0x0afb [unverified]
Checksum Status: Unverified
Urgent pointer: 0
Options: (24 bytes), Maximum segment size, No-Operation (NOP), Window scale, No-Operation (NOP), No-Operation (NOP), Timestamps, SACK permitted, End of Option List (EOL)
TCP Option - Maximum segment size: 1460 bytes
Kind: Maximum Segment Size (2)
Length: 4
MSS Value: 1460
TCP Option - No-Operation (NOP)
TCP Option - Window scale: 6 (multiply by 64)
Shift count: 6
Multiplier: 64
TCP Option - Timestamps: TSval 3609205717, TSecr 0
Timestamp value: 3609205717
Timestamp echo reply: 0
TCP Option - SACK permitted
TCP Option - End of Option List (EOL)
Timestamps
Time since first frame in this TCP stream: 0.000000000 seconds
Time since previous frame in this TCP stream: 0.000000000 seconds
Kind: No-Operation (1)
Kind: Window Scale (3)
Kind: No-Operation (1)
Kind: No-Operation (1)
Kind: Time Stamp Option (8)
Kind: SACK Permitted (4)
Kind: End of Option List (0)
Length: 3
Length: 10
Length: 2
TCP Option - No-Operation (NOP)
TCP Option - No-Operation (NOP)
This is the TCP layer from a FTP session using port 21:
Layer TCP:
Source Port: 35974
Destination Port: 21
Stream index: 0
TCP Segment Len: 0
Sequence number: 0 (relative sequence number)
Sequence number (raw): 29473206
Next sequence number: 1 (relative sequence number)
Acknowledgment number: 0
Acknowledgment number (raw): 0
1010 .... = Header Length: 40 bytes (10)
Flags: 0x002 (SYN)
000. .... .... = Reserved: Not set
...0 .... .... = Nonce: Not set
.... 0... .... = Congestion Window Reduced (CWR): Not set
.... .0.. .... = ECN-Echo: Not set
.... ..0. .... = Urgent: Not set
.... ...0 .... = Acknowledgment: Not set
.... .... 0... = Push: Not set
.... .... .0.. = Reset: Not set
.... .... ..1. = Syn: Set
Expert Info (Chat/Sequence): Connection establish request (SYN): server port 21
Connection establish request (SYN): server port 21
Severity level: Chat
Group: Sequence
.... .... ...0 = Fin: Not set
TCP Flags: \xc2\xb7\xc2\xb7\xc2\xb7\xc2\xb7\xc2\xb7\xc2\xb7\xc2\xb7\xc2\xb7\xc2\xb7\xc2\xb7S\xc2\xb7
Window size value: 32648
Calculated window size: 32648
Checksum: 0x8fda [unverified]
Checksum Status: Unverified
Urgent pointer: 0
Options: (20 bytes), Maximum segment size, No-Operation (NOP), Window scale, No-Operation (NOP), No-Operation (NOP), Timestamps
TCP Option - Maximum segment size: 1380 bytes
Kind: Maximum Segment Size (2)
Length: 4
MSS Value: 1380
TCP Option - No-Operation (NOP)
TCP Option - Window scale: 0 (multiply by 1)
Shift count: 0
Multiplier: 1
TCP Option - Timestamps: TSval 1657560000, TSecr 0
Timestamp value: 1657560000
Timestamp echo reply: 0
Timestamps
Time since first frame in this TCP stream: 0.000000000 seconds
Time since previous frame in this TCP stream: 0.000000000 seconds
Kind: No-Operation (1)
Kind: Window Scale (3)
Kind: No-Operation (1)
Kind: No-Operation (1)
Kind: Time Stamp Option (8)
Length: 3
Length: 10
TCP Option - No-Operation (NOP)
TCP Option - No-Operation (NOP)
This is the TCP layer from a SSH session using port 22:
Layer TCP:
Source Port: 57732
Destination Port: 22
Stream index: 0
TCP Segment Len: 0
Sequence number: 0 (relative sequence number)
Sequence number (raw): 71043058
Next sequence number: 1 (relative sequence number)
Acknowledgment number: 0
Acknowledgment number (raw): 0
1011 .... = Header Length: 44 bytes (11)
Flags: 0x002 (SYN)
000. .... .... = Reserved: Not set
...0 .... .... = Nonce: Not set
.... 0... .... = Congestion Window Reduced (CWR): Not set
.... .0.. .... = ECN-Echo: Not set
.... ..0. .... = Urgent: Not set
.... ...0 .... = Acknowledgment: Not set
.... .... 0... = Push: Not set
.... .... .0.. = Reset: Not set
.... .... ..1. = Syn: Set
Expert Info (Chat/Sequence): Connection establish request (SYN): server port 22
Connection establish request (SYN): server port 22
Severity level: Chat
Group: Sequence
.... .... ...0 = Fin: Not set
TCP Flags: \xc2\xb7\xc2\xb7\xc2\xb7\xc2\xb7\xc2\xb7\xc2\xb7\xc2\xb7\xc2\xb7\xc2\xb7\xc2\xb7S\xc2\xb7
Window size value: 65535
Calculated window size: 65535
Checksum: 0xd079 [unverified]
Checksum Status: Unverified
Urgent pointer: 0
Options: (24 bytes), Maximum segment size, No-Operation (NOP), Window scale, No-Operation (NOP), No-Operation (NOP), Timestamps, SACK permitted, End of Option List (EOL)
TCP Option - Maximum segment size: 1460 bytes
Kind: Maximum Segment Size (2)
Length: 4
MSS Value: 1460
TCP Option - No-Operation (NOP)
TCP Option - Window scale: 6 (multiply by 64)
Shift count: 6
Multiplier: 64
TCP Option - Timestamps: TSval 1452973307, TSecr 0
Timestamp value: 1452973307
Timestamp echo reply: 0
TCP Option - SACK permitted
TCP Option - End of Option List (EOL)
Timestamps
Time since first frame in this TCP stream: 0.000000000 seconds
Time since previous frame in this TCP stream: 0.000000000 seconds
Kind: No-Operation (1)
Kind: Window Scale (3)
Kind: No-Operation (1)
Kind: No-Operation (1)
Kind: Time Stamp Option (8)
Kind: SACK Permitted (4)
Kind: End of Option List (0)
Length: 3
Length: 10
Length: 2
TCP Option - No-Operation (NOP)
TCP Option - No-Operation (NOP)
As previously stated these TCP layers are almost indistinguishable. So trying to use the TCP layer alone would be hard to determine a Telnet session over a port other than port 23. So trying to use Scapy to identify these sessions without doing a more in-depth packet analysis would be extremely hard.
You could potential analyze the data layer of a TCP packet to determine if a connection is or isn't a Telnet session. This again requires substantial effort unless you have done some level of traffic analysis.
Using the Python module pyshark you extract content from the Data layer.
Telnet session over port 23:
import pyshark
# the pcap is a Telnet session over port 23
capture = pyshark.FileCapture('telnet-raw.pcap')
for packet in capture:
if hasattr(packet, 'tcp'):
layers = packet.layers
# 0 1 2 3
# [<ETH Layer>, <IP Layer>, <TCP Layer>, <DATA Layer>]
if len(layers) > 3:
payload = packet.tcp.payload
The payload output is in hex
truncated...
ff:fb:01:ff:fa:21:02:ff:f0:ff:fc:01
ff:fd:01:ff:fe:01
ff:fa:22:03:05:80:00:11:80:00:12:80:00:ff:f0
0d:0a:4f:70:65:6e:42:53:44:2f:69:33:38:36:20:28:6f:6f:66:29:20:28:74:74:79:70:31:29:0d:0a:0d:0a
6c:6f:67:69:6e:3a:20
ff:fc:22:ff:fd:01
truncated...
The 4th and 5th hex strings in the output are an important piece to deciphering what type of TCP connection might be occurring.
import binascii
hex_data = '0d:0a:4f:70:65:6e:42:53:44:2f:69:33:38:36:20:28:6f:6f:66:29:20:28:74:74:79:70:31:29:0d:0a:0d:0a6c:6f:67:69:6e:3a:20 '
hex_string = ' '.join(hex_data.split('0d:0a')).replace(':', '')
hex_list = hex_string.split()
for item in hex_list:
decoded_string = binascii.unhexlify(item)
print(decoded_string)
# output
b'OpenBSD/i386 (oof) (ttyp1)'
b'login: '
After decoding the hex we can see that authentication is occurring over port 23.
Telnet session over port 3005:
import pyshark
# the pcap is a Telnet session over port 3005
capture = pyshark.FileCapture('telnet-pcap-1.pcapng')
for packet in capture:
if hasattr(packet, 'tcp'):
layers = packet.layers
# 0 1 2 3
# [<ETH Layer>, <IP Layer>, <TCP Layer>, <DATA Layer>]
if len(layers) > 3:
payload = packet.tcp.payload
The payload output is in hex
ff:fb:01:ff:fb:03:ff:fd:18:ff:fd:1f
ff:fd:01:ff:fd:03:ff:fb:18:ff:fb:1f:ff:fa:1f:00:97:00:2f:ff:f0
0d:0a:55:73:65:72:20:41:63:63:65:73:73:20:56:65:72:69:66:69:63:61:74:69:6f:6e:0d:0a:0d:0a:55:73:65:72:6e:61:6d:65:3a:20
ff:fa:18:01:ff:f0
ff:fa:18:00:58:54:45:52:4d:2d:32:35:36:43:4f:4c:4f:52:ff:f0
truncated...
The 3rd hex string in the output is an important piece to deciphering what type of TCP connection might be occurring.
import binascii
hex_data = '0d:0a:55:73:65:72:20:41:63:63:65:73:73:20:56:65:72:69:66:69:63:61:74:69:6f:6e:0d:0a:0d:0a:55:73:65:72:6e:61:6d:65:3a:20'
# removing line breaks from the hex string
hex_string = ' '.join(hex_data.split('0d:0a')).replace(':', '')
hex_list = hex_string.split()
for item in hex_list:
decoded_string = binascii.unhexlify(item)
print(decoded_string)
# output
b'User Access Verification'
b'Username: '
After decoding the hex we can see that some type of authentication is occurring over port 3005. Additional analysis would be required to determine if this session is a Telnet session or some other session.
Try doing
for pkt in PcapReader('your_file.pcap'):
# you can try printing summary to see the packet
print(pkt.summary())
# should print something like
# IP / TCP 10.1.99.25:ftp_data > 10.1.99.2:telnet S
pkt_src = pkt[IP].src
pky_type = pkt[IP].type
pkt_payload = pkt[TCP].payload
if [...]
you could print the pkt dictionary to see under which key the telnet string could be falling into and do some pattern matching
I saw the recommendation to do directly PcapReader as not to take memory with rdpcap in another stackoverflow answer but I lost the link
I have program for extract PCAP ARP src_ip and Dest_IP and save in CSV file. i need code how to count Number of Times Src_IP is request to dest_ip (Example 192.168.0.1 src_IP try to connected 10 times with Dest_ip). so how to count duplicates IP in a Column. or how to count src to dest IP or any other idea for count duplicate IP in a Column pls.
below code I need to count number of times src to target
for ts, buf in pcap:
eth = dpkt.ethernet.Ethernet(buf)
# If the packet is not arp
if eth.type != 2054:
continue
try:
arp = eth.arp
except Exception as e:
continue
packet_time = datetime.datetime.utcfromtimestamp(ts).strftime("%m/%d/%Y,%H:%M:%S")
src = dpkt.socket.inet_ntoa(arp.spa)
tgt = dpkt.socket.inet_ntoa(arp.tpa)
Use csv to load desired IPs into a list and then do something like:
from collections import Counter
Counter(ip_list)
Below is my nslookup result using subprocess module in Python.
b'Server: server.internal\r\nAddress: 192.168.0.2\r\n\r\nName:
www.google.com\r\nAddresses: 2404:6800:4007:800::2004\r\n\t
216.58.197.68\r\n\r\n'
Could someone please help me to format the result as below.
Server: server.internal
Name: www.google.com
DNS: 192.168.0.2
Addresses: 2404:6800:4007:800::2004 , 216.58.197.68
You can do it by parsing the lines of the nslookup result into a dictionary, and then using it to format the output.
nslookup = (b'Server: server.internal\r\nAddress: 192.168.0.2\r\n\r\n'
b'Name: www.google.com\r\nAddresses: 2404:6800:4007:800::2004\r\n'
b'\t216.58.197.68\r\n\r\n')
info = {}
for line in nslookup.decode().splitlines():
tokens = line.split()
if len(tokens) == 2:
if tokens[0] == 'Addresses:':
info.setdefault('Addresses', []).append(tokens[1]) # Without ":"
else:
info[tokens[0].rstrip(':')] = tokens[1]
elif len(tokens) == 1:
info['Addresses'].append(tokens[0])
info['Addresses'] = ', '.join(info['Addresses']) # Format and convert to string.
print('''\
Server: {Server}
Name: {Name}
DNS: {Address}
Addresses: {Addresses}'''.format(**info))
Output:
Server: server.internal
Name: www.google.com
DNS: 192.168.0.2
Addresses: 2404:6800:4007:800::2004, 216.58.197.68
You could use Python's unicode_escape to help convert it. The result could then be split into lines and reassembled as follows:
nslookup = b'Server: server.internal\r\nAddress: 192.168.0.2\r\n\r\nName: www.google.com\r\nAddresses: 2404:6800:4007:800::2004\r\n\t216.58.197.68\r\n\r\n'
lines = [line.strip('\t').replace(' ', ' ') for line in nslookup.decode('unicode_escape').splitlines()]
print('\n'.join([lines[0], lines[3], lines[1], '{} , {}'.format(lines[4], lines[5])]))
Giving you:
Server: server.internal
Name: www.google.com
Address: 192.168.0.2
Addresses: 2404:6800:4007:800::2004 , 216.58.197.68
Address: could be replaced by DNS: by a final .replace()
given a local side IP address(ip): u'1.1.1.1/32' #unicode format
how to get the remote side ip? (which will be 1.1.1.2)
logic:
if local ip is even, remote ip will be local ip + 1
else, local ip - 1
i was trying something like this:
ip_temp = int(ip.replace('/32','').split('.')[-1])
if ip_temp % 2 == 0:
remote = ip + 1
else:
remote = ip - 1
remote_ip = <replace last octet with remote>
I looked into ipaddress module but couldnt find anything useful
Most Python socket utilities require that the Remote IP Be a tuple with a string and port number (integer). For example:
import socket
address = ('127.0.0.1', 10000)
sock.connect(address)
For your case, you have most of the logic required. However you need to determine what to do with the cases of X.X.X.0 and X.X.X.255.
The full code to do what you want is:
ip = '1.1.1.1/32'
# Note Drop the cidr notation as it is not necessary for addressing in python
ip_temp = ip.split('/')[0]
ip_temp = ip_temp.split('.')
# Note this does not handle the edge conditions and only modifies the last octet
if int(ip_temp[-1]) % 2 == 0:
remote = int(ip_temp[-1]) + 1
else:
remote = int(ip_temp[-1]) -1
remote_ip = ".".join(ip_temp[:3]) + "." + str(remote)
Device ID: xyz
Entry address(es):
IP address: 10.3.10.46
Platform: WS-x, Capabilities: Switch IGMP
Interface: GigabitEthernet9/33, Port ID (outgoing port): GigabitEthernet0/2
Holdtime : 177 sec
Management address(es):
IP address: 10.3.10.46
above is a snipet from a file.From among the above i want to collect the ip address by matching only the 2 lines below.
Entry address(es):
IP address: 10.3.10.46
or
Management address(es):
IP address: 10.3.10.46
The regular expression i have written is as follows which does not work and i am not able to resolve how i can show the new line after "address(es):" in my regular expression.
f = open(fileName)
for line in f:
matchObj1 = re.match(r'Entry address\(es\):\s+IP address: ([0-9.]+)', line)
if matchObj1:
print "IP Address = ", matchObj1.group(1)
matchObj2 = re.match(r'Entry address\(es\):\s+IP address: ([0-9.]+)', line)
if matchObj2:
print "IP Address = ", matchObj2.group(1)
Please Help. Thank you.
You need to use re.search instead of re.match, re.match is used for matching from the start of string:
>>> s = 'Device ID: xyz\nEntry address(es): \n IP address: 10.3.10.46\n Platform: WS-x, Capabilities: Switch IGMP \n Interface: GigabitEthernet9/33, Port ID (outgoing port): GigabitEthernet0/2\n Holdtime : 177 sec'
>>> re.search(r'Entry address\(es\):\s+IP address: ([0-9.]+)', s).group(1)
'10.3.10.46'
search() vs. match():
re.match() checks for a match only at the beginning of the string,
while re.search() checks for a match anywhere in the string.
You don't need to use regular expressions for this. Your input looks like the output of a configuration file or a program, and easy to parse.
def get_addresses(fname):
addresses = {}
with open(fname) as f:
lines = [l.strip().lower() for l in f]
for i, line in enumerate(lines):
if line.startswith("ip address"):
ip = line.split(": ")[1]
address_type = lines[i-1]
if address_type == "entry address(es):":
addresses["entry"] = ip
elif address_type == "management address(es):":
addresses["management"] = ip
# Add additional address type handling here
return addresses