基于Python socket的端口扫描程序实例代码
作者:cighao 时间:2021-02-24 03:05:09
本文研究的主要是Python的端口扫描程序,具体实例代码如下。
先来看看第一个端口扫描程序代码,获取本机的IP和端口号:
import socket
def get_my_ip():
try:
csock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
csock.connect(('8.8.8.8', 80))
(addr, port) = csock.getsockname()
csock.close()
return addr,port
except socket.error:
return "127.0.0.1"
def int_to_ip(int_ip):
return socket.inet_ntoa(struct.pack('I', socket.htonl(int_ip)))
def ip_to_int(ip):
return socket.ntohl(struct.unpack("I", socket.inet_aton(str(ip)))[0])
(ip,port)=get_my_ip()
print "ip=%s port=%d" %(ip,port)
PortScan.py
#!/usr/bin/python
# -*- coding: utf-8 -*-
import optparse
from socket import *
from threading import *
screenLock = Semaphore(value=1)
def connScan(tgtHost, tgtPort):
try:
connSkt = socket(AF_INET, SOCK_STREAM)
connSkt.connect((tgtHost, tgtPort))
connSkt.send('ViolentPython\r\n')
results = connSkt.recv(100)
screenLock.acquire()
print '[+] %d/tcp open' % tgtPort
print '[+] ' + str(results)
except:
screenLock.acquire()
print '[-] %d/tcp closed' % tgtPort
finally:
screenLock.release()
connSkt.close()
def portScan(tgtHost, tgtPorts):
try:
tgtIP = gethostbyname(tgtHost)
except:
print "[-] Cannot resolve '%s': Unknown host" %tgtHost
return
try:
tgtName = gethostbyaddr(tgtIP)
print '\n[+] Scan Results for: ' + tgtName[0]
except:
print '\n[+] Scan Results for: ' + tgtIP
setdefaulttimeout(1)
for tgtPort in tgtPorts:
t = Thread(target=connScan,args=(tgtHost,int(tgtPort)))
t.start()
def main():
parser = optparse.OptionParser('usage %prog '+\
'-H <target host> -p <target port>')
parser.add_option('-H', dest='tgtHost', type='string',\
help='specify target host')
parser.add_option('-p', dest='tgtPort', type='string',\
help='specify target port[s] separated by comma')
(options, args) = parser.parse_args()
tgtHost = options.tgtHost
tgtPorts = str(options.tgtPort).split(',')
if (tgtHost == None) | (tgtPorts[0] == None):
print parser.usage
exit(0)
portScan(tgtHost, tgtPorts)
if __name__ == '__main__':
main()
基于Python socket的端口扫描程序
#-------------------------------------------------------------------------------
# Name: PortScan
# Purpose: 扫描网段主机的端口开放情况
# Author: Hao Chen
# Python3.4
#-------------------------------------------------------------------------------
import socket
def main():
ip_start=input('请输入开始IP:(默认:127.0.0.1)')
if ip_start=='':
ip_start='127.0.0.1'
ip_end='127.0.0.1'
else:
ip_end=input('请输入结束IP:')
if ip_end=='':
ip_end='127.0.0.1'
s=input('请输入目标主机开始端口:(默认扫描常用端口)')
if s=='':
portList=[21, 22, 23, 25, 80, 135, 137, 139, 445, 1433, 1502, 3306, 3389, 8080, 9015]
else:
startport=int(s)
s=input('请输入目标主机结束端口:(默认:65535)')
if s=='':
endport=65535
else:
endport=int(s)
portList=[i for i in range(startport,endport+1)]
while 1:
#ip_start<ip_end
x1=ip_start.rfind('.');
x2=ip_end.rfind('.')
if int(ip_start[x1+1:])>int(ip_end[x2+1:]):
break;
#开始扫描端口
for port in portList:
print('正在扫描%s :%d' %(ip_start,port))
try:
sk = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sk.settimeout(10)
sk.connect((ip_start,port))
sk.settimeout(None)
print('Server %s port %d OK!' % (ip_start,port))
sk.close()
#结果保存在文件中
f=open("IP_Port.txt",'a')
f.write(ip_start+' : '+str(port)+'\n')
f.close()
except Exception:
print('Server %s port %d is not connected!' % (ip_start,port))
#更新ip_start
i=ip_start.rfind('.')
x=int(ip_start[i+1:])+1
ip_start=ip_start[:i+1]+str(x)
print('扫描完成,结果保存在IP_Port.txt文件中')
if __name__ == '__main__':
main()
来源:http://blog.csdn.net/cighao/article/details/44731709
标签:python,socket,端口
0
投稿
猜你喜欢
Python实现ping指定IP的示例
2023-10-05 04:20:10
asp获取文件md5值
2008-10-13 09:10:00
Windows 64位下python3安装nltk模块
2023-11-20 09:42:12
MySQL日志管理详解
2024-01-26 14:35:24
python实现将列表中各个值快速赋值给多个变量
2023-11-23 18:02:05
python实现神经网络感知器算法
2021-03-06 11:23:39
python sort、sort_index方法代码实例
2022-12-16 00:43:17
整合ckeditor+ckfinder,解决上传文件路径问题
2022-12-10 09:25:39
golang 如何自动下载所有依赖包
2024-02-20 11:26:32
python 基于dlib库的人脸检测的实现
2022-08-23 22:59:07
python导入同级模块的实现
2021-03-09 10:08:51
python爬虫框架feapder的使用简介
2021-07-20 14:38:27
PyQt5 QListWidget选择多项并返回的实例
2022-12-14 07:49:25
你可能不知道的Python 技巧小结
2022-12-18 07:08:10
Spring MVC 框架搭建配置方法及详解
2024-03-13 19:04:36
Python操作列表常用方法实例小结【创建、遍历、统计、切片等】
2021-07-26 12:56:49
MySQL数据库优化之索引实现原理与用法分析
2024-01-27 08:12:37
用Python+OpenCV对比图像质量的几种方法
2022-06-28 10:57:59
基于python分析你的上网行为 看看你平时上网都在干嘛
2021-09-02 15:04:39
python基础教程项目四之新闻聚合
2021-10-03 01:31:33