2017-01-11 6 views
0

Я следил за руководством по созданию простого портального сканера, я пытаюсь сканировать свой собственный IP-адрес, но он застревает в цикле и не печатает порты. Трудно понять, что он не дает ошибок и застревает в цикле.Python Port Scanner Stuck In Loop

Любая помощь была бы принята с благодарностью.

import socket 
import subprocess 
import sys 
from datetime import datetime 

#clears the shell screen 
subprocess.call('clear', shell=True) 

#ask for input 
remoteServer = raw_input("Please enter a host to scan:") 
remoteServerIP = socket.gethostbyname(remoteServer) 

#print a banner saying we are scanning 
print "-" * 60 
print "now scanning your host...", remoteServerIP 
print "-" * 60 

#Check what time the scan started 
t1 = datetime.now() 

# Using the range function to specify which ports (1 - 1025) 

#Errors. 

try: 
    for port in range(1, 1025): 
    sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM) 
    result = sock.connect_ex((remoteServerIP, port)) 
    if result == 0: 
     #if the socket is listening it will print out the port 
     print("Port{}:\t Open".format(port)) 
    sock.close() 

except KeyboardInterrupt: 
    print "You pressed ctrl+c" 
    sys.exit() 

except socket.gaierror: 
    print 'Hostname could not be resolved to IP. Exiting' 
    sys.exit() 

except socket.error: 
    print "couldn't connect to server" 
    sys.exit() 

# checking the time again 
t2 = datetime.now() 

#calculates the differnce of time, to see how long it took to run the script 
total = t2 - t1 

#printing the info to screen 
print "scanning compelte in :", total 
+0

вы уверены, что вы не получаете сообщение об ошибке при запуске в консоли/Termina/cmd.exe/PowerShell? Возможно, добавьте больше 'print()', чтобы увидеть, какой порт создает проблему. – furas

+0

BTW: для меня экран очистки бесполезен - вы не можете сравнить текущий результат с предыдущим. – furas

+0

Что значит «застрял в петле»? –

ответ

-1

По крайней мере, на моей машине (Ubuntu 16.something) это действительно работает. Выход:

Please enter a host to scan:localhost 
------------------------------------------------------------ 
now scanning your host... 127.0.0.1 
------------------------------------------------------------ 
Port21: Open 
Port22: Open 
Port25: Open 
Port80: Open 
Port139:   Open 
Port443:   Open 
Port445:   Open 
Port631:   Open 
scanning compelte in : 0:00:00.047478 

Однако, он сканирует только порты 1-1024, в то время как порты идут до 65535. Чтобы сделать его просканировать все порты, изменить for port in range(1, 1025): к for port in range(1, 65536):

+0

проблема не решена - вы можете поместить это как комментарий. – furas

0

Вы можете использовать sock.timeout(0.1) так будет нет ждать подключения.

Я положил print port, чтобы узнать, какой порт сканируется.

Вы можете попробовать 8.8.8.8 - без sock.timeout(0.1) он висит на первом порту.

Возможно, у вас есть хороший защищенный компьютер и он блокирует соединения с закрытыми портами.

import sys 
from datetime import datetime 
import socket 

#ask for input 
remoteServer = raw_input("Please enter a host to scan: ") 
remoteServerIP = socket.gethostbyname(remoteServer) 

#print a banner saying we are scanning 
print "-" * 60 
print "now scanning host ...", remoteServerIP 
print "-" * 60 

#Check what time the scan started 
t1 = datetime.now() 

# Using the range function to specify which ports (1 - 1025) 

#Errors. 

try: 
    for port in range(1, 1025): 
    print port 
    sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM) 

    sock.settimeout(0.1) 

    result = sock.connect_ex((remoteServerIP, port)) 
    if result == 0: 
     #if the socket is listening it will print out the port 
     print("Port {:4d}: Open".format(port)) 
    sock.close() 

except KeyboardInterrupt: 
    print "You pressed ctrl+c" 
    sys.exit() 

except socket.gaierror: 
    print 'Hostname could not be resolved to IP. Exiting' 
    sys.exit() 

except socket.error: 
    print "couldn't connect to server" 
    sys.exit() 

# checking the time again 
t2 = datetime.now() 

#calculates the differnce of time, to see how long it took to run the script 
total = t2 - t1 

#printing the info to screen 
print "scanning compelte in:", total 

КСТАТИ:

Вы можете сравнить свои результаты с результатами из инструментов, как nmap

См scapy - модуль питона для работы с сетевыми пакетами. (Книга: Black Hat Python)


 Смежные вопросы

  • Нет связанных вопросов^_^