Python實現(xiàn)IP端口掃描程序
完整代碼
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
IP端口掃描程序
輸入IP地址,掃描該IP哪些端口對外是開放的,輸出端口列表
"""
import socket
import sys
import concurrent.futures
import ipaddress
from tabulate import tabulate
import time
def is_valid_ip(ip):
"""
驗證IP地址是否有效
"""
try:
ipaddress.ip_address(ip)
return True
except ValueError:
return False
def scan_port(ip, port, timeout=1):
"""
掃描單個端口是否開放
參數(shù):
ip (str): 目標IP地址
port (int): 要掃描的端口
timeout (float): 連接超時時間(秒)
返回:
bool: 如果端口開放返回True,否則返回False
"""
try:
# 創(chuàng)建TCP套接字
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(timeout)
# 嘗試連接
result = sock.connect_ex((ip, port))
# 關(guān)閉套接字
sock.close()
# 如果連接成功,端口是開放的
return result == 0
except (socket.error, socket.timeout, OSError):
return False
def scan_ports(ip, port_range=None, max_workers=100):
"""
掃描IP地址的多個端口
參數(shù):
ip (str): 目標IP地址
port_range (tuple): 端口范圍,格式為(起始端口, 結(jié)束端口)
max_workers (int): 最大并發(fā)線程數(shù)
返回:
list: 開放端口列表
"""
if port_range is None:
# 默認掃描常見端口
port_range = (1, 1024)
start_port, end_port = port_range
open_ports = []
total_ports = end_port - start_port + 1
print(f"開始掃描 {ip} 的端口 {start_port}-{end_port}...")
start_time = time.time()
# 使用線程池進行并發(fā)掃描
with concurrent.futures.ThreadPoolExecutor(max_workers=max_workers) as executor:
# 創(chuàng)建掃描任務
future_to_port = {
executor.submit(scan_port, ip, port): port
for port in range(start_port, end_port + 1)
}
# 處理完成的任務
completed = 0
for future in concurrent.futures.as_completed(future_to_port):
port = future_to_port[future]
completed += 1
# 顯示進度
if completed % 100 == 0 or completed == total_ports:
progress = (completed / total_ports) * 100
elapsed = time.time() - start_time
print(f"進度: {completed}/{total_ports} ({progress:.1f}%) - 已用時間: {elapsed:.1f}秒", end="\r")
try:
if future.result():
open_ports.append(port)
print(f"\n發(fā)現(xiàn)開放端口: {port}")
except Exception as e:
print(f"\n掃描端口 {port} 時出錯: {e}")
print(f"\n掃描完成! 總用時: {time.time() - start_time:.1f}秒")
return open_ports
def display_open_ports(ip, open_ports):
"""
顯示開放端口列表
"""
if not open_ports:
print(f"\n{ip} 沒有發(fā)現(xiàn)開放的端口")
return
# 嘗試獲取常見端口的服務名稱
port_info = []
for port in sorted(open_ports):
try:
service = socket.getservbyport(port)
except (socket.error, OSError):
service = "未知"
port_info.append([port, service])
# 顯示表格
print(f"\n{ip} 的開放端口:")
headers = ["端口", "可能的服務"]
print(tabulate(port_info, headers=headers, tablefmt="grid"))
def main():
"""
主函數(shù)
"""
# 獲取用戶輸入
if len(sys.argv) > 1:
target_ip = sys.argv[1]
else:
target_ip = input("請輸入要掃描的IP地址: ")
# 驗證IP地址
if not is_valid_ip(target_ip):
print(f"錯誤: '{target_ip}' 不是有效的IP地址")
sys.exit(1)
# 獲取端口范圍
try:
custom_range = input("請輸入要掃描的端口范圍 (格式: 起始端口-結(jié)束端口) [默認: 1-1024]: ")
if custom_range:
start, end = map(int, custom_range.split('-'))
if start < 1 or end > 65535 or start > end:
raise ValueError
port_range = (start, end)
else:
port_range = (1, 1024)
except ValueError:
print("錯誤: 無效的端口范圍,使用默認范圍 1-1024")
port_range = (1, 1024)
# 掃描端口
open_ports = scan_ports(target_ip, port_range)
# 顯示結(jié)果
display_open_ports(target_ip, open_ports)
if __name__ == "__main__":
try:
main()
except KeyboardInterrupt:
print("\n\n掃描被用戶中斷")
sys.exit(0)
except Exception as e:
print(f"\n程序執(zhí)行出錯: {e}")
sys.exit(1)結(jié)果如下

方法補充
python批量掃描ip端口
該程序的主要功能如下:
1. 從自有API接口獲取所有的外網(wǎng)IP段;
2. 用Nmap 遍歷掃描所有的IP段,-oX 生成XML的掃描報告;
3. 用xml.etree.ElementTree模塊方法讀取XML文件,將ip,開放端口,對應服務等寫入Mysql數(shù)據(jù)庫。
功能很簡單,沒有滿足老大高大上的需求,所以這個小項目就這么英勇的掛掉了!~~~完全都還沒考慮程序異常終止,掃描服務器異常歇菜的情況。
貼上代碼:
#coding:utf-8
import sys,os,time,subprocess
import MySQLdb
import re,urllib2
import ConfigParser
from IPy import IP
import xml.etree.ElementTree as ET
nowtime = time.strftime('%Y-%m-%d',time.localtime(time.time()))
configpath=r'c:portscanconfig.ini'
#傳入api接口主路徑,遍歷獲取所有的ip列表,用IPy模塊格式成127.0.0.1/24的格式
def getiplist(ipinf):
serverarea=['tj101','tj103','dh','dx']
iplist=[]
for area in serverarea:
ipapi=urllib2.urlopen(ipinf+area).read()
for ip in ipapi.split('n'):
#判斷如果ip列表不為空,轉(zhuǎn)換成ip/網(wǎng)關(guān)格式,再格式化成ip/24的格式
if ip:
ip=ip.replace('_','/')
ip=(IP(ip))
iplist.append(str(ip))
ipscan(iplist,nmapathx)
#傳遞ip地址文件和nmap路徑
def ipscan(iplist,nmapath):
#古老的去重,對ip文件中的ip地址進行去重
newiplist=[]
scaniplist=[]
for ip in iplist:
if ip not in newiplist:
newiplist.append(ip)
#遍歷所有ip段,批量掃描,生成xml格式報告
for ip in newiplist:
filename=nowtime+ip.split('/')[0]+'.xml'
filepath=r"c:portscanscanres\"
nmapcmd=nmapath+' -PT '+ip.strip('rn')+' -oX '+filepath+filename
os.system(nmapcmd)
scaniplist.append(ip)
writeinmysql(scaniplist)
#入庫模塊是某大嬸發(fā)寫好的給我 我只是簡單修改了哈,主要是xml.etree.ElementTree模塊。
def writeinmysql(scaniplist):
filepath=r"c:portscanscanres"
for ip in scaniplist:
xmlfile=filepath+'\'+ip+'.xml'
#縮進哈 發(fā)文章的時候臨時改的,懶得縮進了
root=ET.parse(xmlfile).getroot()
allhost=root.findall('host')
conn=MySQLdb.connect(host='10.5.10.57',user='nxadmin',passwd='nxadmin.com',port=3306,db='scandb',charset='utf8')
cur= conn.cursor()
for host in allhost:
address = host.find('address')
#首先判斷端口是不是open的,如果是再進行入庫
for port in host.find('ports').findall('port'):
if port.find('state').attrib['state']=="open":
ip=address.attrib['addr']
portval=port.attrib['portid']
state=port.find('state').attrib['state']
sql = "INSERT INTO portscan (ip,port,state) VALUES(%s,%s,%s)"
params=[ip,portval,state]
cur.execute(sql,params)
conn.commit()
cur.close()
conn.close()
if __name__=="__main__":
#讀取配置文件中要掃描的IP apiurl和nmap安裝文件路徑
config=ConfigParser.ConfigParser()
config.readfp(open(configpath,'rb'))
nmapathx=config.get('nmap','nmapath')
ipinf=config.get('ip','ipinf')
getiplist(ipinf)配置文件c:portscanconfig.ini中主要是api接口主url,nmap安裝路徑。
python 使用 scapy 掃描內(nèi)網(wǎng)IP或端口
1.利用ICMP協(xié)議探測內(nèi)網(wǎng)IP
def ping_ip(ip_fex):
# 掃描范圍: 128~254
for i in range(128, 255):
ip = f'{ip_fex}.{i}'
print(f'\r{ip}', end='')
output = os.popen(f'ping -n 1 -w 100 {ip} | findstr TTL=').read()
if len(output) > 0:
print(f"\n{ip} online")
if __name__ == '__main__':
ping_ip('192.168.110')2.利用ARP協(xié)議探測內(nèi)網(wǎng)IP
def ip_thread(start, ip_fex):
for i in range(start, start + 20):
ip = f'{ip_fex}.{i}' # 目標ip
try:
pkg = ARP(psrc=f'{ip_fex}.1', pdst=ip) # 偽造ARP廣播
reply = sr1(pkg, timeout=1, verbose=False) # 發(fā)送ARP并獲取響應包
if reply:
print(f'\n{ip}->{reply[ARP].hwsrc}') # 顯示MAC地址
else:
print(f'\r{ip} ...', end='')
except Exception as e:
print(e)
def ip_scan(ip_fex):
# 關(guān)閉警告
import logging
logging.getLogger("scapy.runtime").setLevel(logging.ERROR)
# 端口范圍 1~254
for i in range(1, 255, 20):
threading.Thread(target=ip_thread, args=(i, ip_fex)).start()3.利用TCP協(xié)議探測端口
端口信息在TCP層, 可以使用TCP協(xié)議數(shù)據(jù)包探測端口是否開放
偽造 SYN 數(shù)據(jù)包, 根據(jù)響應數(shù)據(jù)中的標志位 flags 來判斷端口是否正常響應.
SYN: 0x002
ACK: 0x010
SYN-ACK: 0x012
def scan_port(ip):
for port in range(22, 100):
try:
pkg = IP(src='192.168.112.123', dst=ip) / TCP(dport=port, flags='S')
reply = sr1(pkg, timeout=1, verbose=False)
if reply:
if reply[TCP].flags == 0x12: # SYN-ACK
print(f'port->[{port}]')
except Exception as e:
print(e)到此這篇關(guān)于Python實現(xiàn)IP端口掃描程序的文章就介紹到這了,更多相關(guān)Python IP端口掃描內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
python登陸asp網(wǎng)站頁面的實現(xiàn)代碼
這篇文章主要介紹了python登陸asp網(wǎng)站頁面的實現(xiàn)代碼,需要的朋友可以參考下2015-01-01
Python在內(nèi)網(wǎng)安裝python第三方包(庫)的方法
日常我們工作的計算機環(huán)境是內(nèi)網(wǎng),做項目需要安裝python?第三方庫,在外網(wǎng)一般使用"pip?install?包名"很快就安裝上了,但是在內(nèi)網(wǎng)無法連接pypi網(wǎng)站或者國內(nèi)鏡像,那該如何安裝呢,下面小編給大家?guī)砹薖ython如何在內(nèi)網(wǎng)安裝python第三方包庫,感興趣的朋友一起看看吧2024-01-01
python 實現(xiàn)查找文件并輸出滿足某一條件的數(shù)據(jù)項方法
今天小編就為大家分享一篇python 實現(xiàn)查找文件并輸出滿足某一條件的數(shù)據(jù)項方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-06-06
Python使用combinations實現(xiàn)排列組合的方法
今天小編就為大家分享一篇Python使用combinations實現(xiàn)排列組合的方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-11-11
Python循環(huán)中else,break和continue的用法實例詳解
這篇文章主要介紹了Python循環(huán)中else,break和continue的用法,結(jié)合實例形式詳細分析了Python for循環(huán)、while循環(huán)中else,break和continue的功能、用法及相關(guān)操作注意事項,需要的朋友可以參考下2019-07-07

