分类: Python/Ruby
2013-02-03 13:47:06
先说明一番,这处在刚开始学习Python网络编程时在群上有人囔着要微型端口扫描器,给我个思路就是可以用Python写个这样的功能,算是给自己练练手吧。。。一开始想用SYN或ACK来实现的,因为这样的效率肯定比Socket高得多!由于还是菜鸟,大牛勿喷,就用Socket充当了。。。不说废话,上代码:
#!/usr/bin/env python
# -*- coding: gb18030 -*-
from socket import *
import os
import sys
type = sys.getfilesystemencoding()
#从文件中读取扫描端口
def getPort(fileroute = "PORTS.txt"):
list={}
fileobject = open(fileroute,'r')
for eachLine in fileobject:
strs = str(eachLine).split('=')
if len(strs) > 1 :
list[int(strs[0])] = strs[1]
return list
#主程序
list = getPort()
keys = list.keys()
keys.sort()
HOST = sys.argv[0]
fileobject = open("D:\\result1.txt",'w')
tcpCliSock = socket(AF_INET,SOCK_STREAM)
result = ''
#list_sort = sorted(list, key = lambda d:d[0], reverse = False)
for p in keys:
try:
tcpCliSock = socket(AF_INET,SOCK_STREAM)
tcpCliSock.connect((HOST,int(p)))
tcpCliSock.close()
del tcpCliSock
result = str(p)+" -> " + list[p]
print result
fileobject.writelines([result])
except error:
print str(p) + " -> not open"
continue
从PORTS.TXT文本中读取端口及作用的列表保存起来,然后用Socket逐个尝试连接,将开启的端口信息保存在D:\result1.txt中