0

I have the following nmap output as xml format:

<ports><extraports state="closed" count="991">
<extrareasons reason="conn-refused" count="991"/>
</extraports>
<port protocol="tcp" portid="22"><state state="open" reason="syn-ack" reason_ttl="0"/><service name="ssh" method="table" conf="3"/></port>
<port protocol="tcp" portid="25"><state state="open" reason="syn-ack" reason_ttl="0"/><service name="smtp" method="table" conf="3"/></port>
<port protocol="tcp" portid="139"><state state="open" reason="syn-ack" reason_ttl="0"/><service name="netbios-ssn" method="table" conf="3"/></port>
<port protocol="tcp" portid="443"><state state="open" reason="syn-ack" reason_ttl="0"/><service name="https" method="table" conf="3"/></port>

I want to get port numbers that are open:

print 'Port Number: '+host.find('ports').find('port').get('portid')

But the result is just 22.

How can I have the results:

22
25
139
443

1 Answer 1

1

Find all port elements, and get portid attributes.

Using Element.findall and list comprehension:

>>> import xml.etree.ElementTree as ET
>>> root = ET.fromstring('''
<ports><extraports state="closed" count="991">
<extrareasons reason="conn-refused" count="991"/>
</extraports>
<port protocol="tcp" portid="22"><state state="open" reason="syn-ack" reason_ttl="0"/><service name="ssh" method="table" conf="3"/></port>
<port protocol="tcp" portid="25"><state state="open" reason="syn-ack" reason_ttl="0"/><service name="smtp" method="table" conf="3"/></port>
<port protocol="tcp" portid="139"><state state="open" reason="syn-ack" reason_ttl="0"/><service name="netbios-ssn" method="table" conf="3"/></port>
<port protocol="tcp" portid="443"><state state="open" reason="syn-ack" reason_ttl="0"/><service name="https" method="table" conf="3"/></port>
</ports>
''')
>>> [port.get('portid') for port in root.findall('.//port')]
['22', '25', '139', '443']
Sign up to request clarification or add additional context in comments.

3 Comments

@MortezaLSC, Iterate the port elements: for port in root.findall('.//port'): print('port: {}'.format(port.get('portid')))
I am really sorry...but I do state=[port.get('state') for state in root.findall('.//port')] for checking states and then it doesn't return me open and say none
@MortezaLSC, state attribute is not an attribute of port element, but an attribute of state. You need to use this: [port.get('state') for port in root.findall('.//port/state')]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.