A
A
ARHPOMOR2021-10-05 10:44:57
Python
ARHPOMOR, 2021-10-05 10:44:57

Python nmap module problem with the script, I can not display the necessary parameters, how to solve?

You need to write a Python script with the nmap module and scan the VM. It is necessary that the script displays the port, service and its version in a column. Example of a valid output: 21 ftp 2.0. And so they go to the column.

My script is the following:

import nmap3
nmap = nmap3.Nmap()
result = nmap.nmap_version_detection("10.0.0.3")
for i in result["10.0.0.3"]["ports"]:
    print(i["portid"], i["service"])

It outputs this:

21 {'name': 'ftp', 'product': 'vsftpd', 'version': '2.3.4', 'ostype': 'Unix', 'method': 'probed', 'conf': '10'}
22 {'name': 'ssh', 'product': 'OpenSSH', 'version': '4.7p1 Debian 8ubuntu1', 'extrainfo': 'protocol 2.0', 'ostype': 'Linux', 'method': 'probed', 'conf': '10'}
23 {'name': 'telnet', 'product': 'Linux telnetd', 'ostype': 'Linux', 'method': 'probed', 'conf': '10'}
25 {'name': 'smtp', 'product': 'Postfix smtpd', 'hostname': ' metasploitable.localdomain', 'method': 'probed', 'conf': '10'}

etc.

I want it to output the following options: However, when it prints, it outputs this error:

print(i["portid"], i["name"], i["version"])


Traceback (most recent call last):
  File "/home/PycharmProjects/nets/./net.py", line 7, in <module>
    print(i["portid"], i["name"], i["version"])
KeyError: 'name'

I don’t understand what the problem is, because every service seems to have a name parameter, but not every service has version.

Is it possible to make the script check if the service has a name and version, and if not, it continues execution and writes just an empty value to the output?
I was told to use try and except, but I don't know how to use them here to achieve the desired goal.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
soremix, 2021-10-05
@ARHPOMOR

like the name parameter is

And if you do not guess, but check?
In general, you i["service"]output , and here is its output as follows:
{'name': 'telnet', 'product': 'Linux telnetd', 'ostype': 'Linux', 'method': 'probed', 'conf': '10'}

The key nameis not in the dictionary i, but in the i['service']. So it will be righti['service']['name']

J
JohnDoe88, 2021-10-05
@JohnDoe88

Hello. Is it possible to contact you? Regarding the previous question on the Netology course, I would like to know

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question