Я попробовал ваш код на ноутбуке jupyter и всегда получаю один и тот же набор портов:
get_open_ports('127.0.0.1')
Выход:
[133, 200, 144...60700]
Возможно ли, что в определенное время для запрашиваемого хоста открыто другое количество портов?
Чтобы проверить небольшой набор портов, я уменьшил max_port
до 10000
и все равно каждый раз получаю один и тот же набор портов:
def get_open_ports(host, max_port=10000):
open_ports = []
def worker(port):
if check_open_port(host, port):
open_ports.append(port)
with ThreadPoolExecutor(max_workers=10000) as executor:
[executor.submit(worker, port) for port in range(1, max_port + 1)]
executor.shutdown(wait=True)
return open_ports
get_open_ports('127.0.0.1')
Выход: [150, 900, 1035, 7789]
Примечание. Я изменил номера портов в целях безопасности.
ИЗМЕНИТЬ:
def get_open_ports(host, max_port=65535):
open_ports = []
def worker(port):
if check_open_port(host, port):
open_ports.append(port)
# We can use a with statement to ensure threads are cleaned up promptly
with ThreadPoolExecutor(max_workers=100) as executor:
print('main:starting')
wait_for=[executor.submit(worker,port) for port in range(1, max_port + 1)]
for f in as_completed(wait_for):
print('main: result: {}'.format(f.result())) #check result on each thread execution
# executor.shutdown(wait=True) #not required when using the 'with' statement
return len(open_ports)
test = get_open_ports('45.60.112.163') #hostname for www.indracompany.com
#max_workers not defined & max_port=10000
# len(test) #test1: 148
# len(test) #test 2: 79
#max_workers = 10000 & max_port=65535
# len(test) #test1: 1
# len(test) #test2:1
# len(test) #test3:1
#max_workers = 20000 & max_port=65535
# len(test) #test1: 14
# len(test) #test2:1
# len(test) #test3: 1
# len(test) #test4:1
#max_workers not defined & max_port=65535 #quite time-consuming
# len(test) #test1: 63
РЕДАКТИРОВАТЬ 2: более надежное решение
Как предложил @Tarun, библиотека Python python-nmap лучше справляется со сканированием хосты.
Приведенное ниже решение дает точный результат, однако я заметил значительный компромисс в производительности по мере увеличения диапазона обнаружения портов. Возможно, в код можно было бы включить многопоточность для повышения производительности. Я также импортировал библиотеку времени, чтобы в итоге получить время выполнения программы. Это можно использовать для сравнения при тестировании производительности.
# The python-nmap library helps to programmatically manipulate scanned results of nmap to automate port scanning tasks.
# To use this library you must have the Nmap software installed. This can be installed from https://nmap.org/download.html.
# Network Mapper (Nmap) is a free and open-source tool used for network discovery and security auditing.
# It runs on all major computer operating systems, and official binary packages are available for Linux, Windows, and Mac OS X.
# For Windows 7 and later, you must also upgrade 'NCap' from https://nmap.org/npcap/
# For Windows, make sure nmap.exe is added to PATH.
# When you're ready, pip install python-nmap
import time
import nmap
nm = nmap.PortScanner() #initialize PortScanner object
host = '45.60.112.163' #specify host
nm.scan(host, '1-100') #run the scan, specify host and range of ports to scan
#Optional steps for verification:
#Output: nmap -oX - -p 1-100 -sV 45.60.112.163
print(nm.command_line()) #command_line command to execute on nmap command prompt
#Output: {'tcp': {'method': 'syn', 'services': '1-100'}}
print(nm.scaninfo()) #nmap scan information
#Now we can scan all hosts
#From Official documentation at https://xael.org/pages/python-nmap-en.html
start_time = time.time() #To get program execution time
for host in nm.all_hosts():
print('----------------------------------------------------')
print('Host : %s (%s)' % (host, nm[host].hostname()))
print('State : %s' % nm[host].state())
for proto in nm[host].all_protocols():
print('----------')
print('Protocol : %s' % proto)
lport = nm[host][proto].keys()
for key in sorted(lport):
for port in lport:
print ('port : %s\tstate : %s' % (port, nm[host][proto][port]['state']))
print('Execution time: %s seconds' % (time.time() - start_time))
#Output:
----------------------------------------------------
Host : 45.60.112.163 ()
State : up
----------
Protocol : tcp
port : 25 state : open
port : 51 state : open
port : 53 state : open
port : 80 state : open
port : 81 state : open
port : 85 state : open
port : 91 state : open
port : 25 state : open
port : 51 state : open
port : 53 state : open
port : 80 state : open
port : 81 state : open
port : 85 state : open
port : 91 state : open
port : 25 state : open
port : 51 state : open
port : 53 state : open
port : 80 state : open
port : 81 state : open
port : 85 state : open
port : 91 state : open
port : 25 state : open
port : 51 state : open
port : 53 state : open
port : 80 state : open
port : 81 state : open
port : 85 state : open
port : 91 state : open
port : 25 state : open
port : 51 state : open
port : 53 state : open
port : 80 state : open
port : 81 state : open
port : 85 state : open
port : 91 state : open
port : 25 state : open
port : 51 state : open
port : 53 state : open
port : 80 state : open
port : 81 state : open
port : 85 state : open
port : 91 state : open
port : 25 state : open
port : 51 state : open
port : 53 state : open
port : 80 state : open
port : 81 state : open
port : 85 state : open
port : 91 state : open
Execution time: 0.015624761581420898 seconds
Чтобы преобразовать вывод в csv, используйте:
print(nm.csv())
В результате этого расследования на моем компьютере был установлен Nmap. Ради интереса я также запустил сканирование в командной строке, используя приведенную ниже команду. Это сканирование выполнялось для диапазона «1-1000» и заняло более 15 минут (я не просидел весь сеанс!).
![введите описание изображения здесь](https://i.stack.imgur.com/SOSGH.png)
person
amanb
schedule
09.03.2018
nmap
python? github.com/johanlundberg/python-nmap/blob/master/ nmap/ - person Tarun Lalwani   schedule 09.03.2018open_ports
. Поскольку к этой переменной обращаются несколько потоков, вы должны использовать threading.Lock, чтобы гарантировать, что только один добавляется за раз... Однако я не могу воспроизвести проблему локально!? - person urban   schedule 15.03.2018