1. 程式人生 > >python實現指定ip埠掃描

python實現指定ip埠掃描

在Linux中判斷一臺主機是否可達,可以使用ping命令,而判斷埠是否開啟,可以使用telnet命令,但是telnet命令沒有超時時間的引數,使用起來不是很方便,那麼可以利用Python來完成一個埠掃描的功能

socket實現埠掃描

#!/usr/bin/env python

import socket

def get_ip_status(ip,port):
    server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    try:
        server.connect((ip,port))
        print('{0} port {1} is open'
.format(ip, port)) except Exception as err: print('{0} port {1} is not open'.format(ip,port)) finally: server.close() if __name__ == '__main__': host = '10.0.0.11' for port in range(20,100): get_ip_status(host,port)

telnetlib實現埠掃描

import telnetlib

def get_ip_status
(ip,port):
server = telnetlib.Telnet() # 建立一個Telnet物件 try: server.open(ip,port) # 利用Telnet物件的open方法進行tcp連結 print('{0} port {1} is open'.format(ip, port)) except Exception as err: print('{0} port {1} is not open'.format(ip,port)) finally: server.close() if
__name__ == '__main__': host = '10.0.0.11' for port in range(20,100): get_ip_status(host,port)

多執行緒實現高效掃描

#!/usr/bin/env python

import telnetlib
import threading

def get_ip_status(ip,port):
    server = telnetlib.Telnet()
    try:
        server.open(ip,port)
        print('{0} port {1} is open'.format(ip, port))
    except Exception as err:
        print('{0} port {1} is not open'.format(ip,port))
    finally:
        server.close()

if __name__ == '__main__':
    host = '10.0.0.11'
    threads = []
    for port in range(20,100):
        t = threading.Thread(target=get_ip_status,args=(host,port))
        t.start()
        threads.append(t)

    for t in threads:
        t.join()