python实现简单的端口扫描器
程序员文章站
2022-05-15 22:10:10
...
端口扫描器
之前的都是跟着《python绝技》这本书,上次开完会之后就又跟着gitbook那个网址的书做了一遍端口扫描。
源代码:
# -*- coding: utf-8 -*-
import socket
from threading import *
screenLock = Semaphore(value=1)
def portScan(host,ports):
try:
tgtIP = socket.gethostbyname(host)
except:
print "[-] Cannot Resolve'%s': Unknown host"% host
return
try:
tgtName = socket.gethostbyaddr(tgtIP)
print '\n[+] Scan Results for: '+ tgtNmae[0]
except:
print '\n[+] Scan Results for: '+ tgtIP
socket.setdefaulttimeout(1)
for port in ports:
t = Thread(target=Scanner,args=(host,int(port)))
t.start()
def Scanner(host,port):
try:
print "[+] Connecting to " +host+":" + str(port)
s = socket.socket()
s.connect((host,port))
s.send('Primal Security \n')
banner = s.recv(1024)
if banner:
screenLock.acquire()
print "[+]Port" + str(port) + "open: "
print "[+]>>>"+str(banner)
except:
screenLock.acquire()
print "[-]Port" + str(port) + "closed\n"
finally:
screenLock.release()
s.close()
def main():
tgthost = raw_input("Please enter the hosts you want to scan:");
hosts = []
for i in tgthost.split(','):
hosts.append(str(i))
ports = [20,21,22,23,80,135,443,445,3389,8080]
for host in hosts:
portScan(host,ports)
if __name__ == '__main__':
main()
这是我根据书上,再参考《python绝技》上的案例,进行一点点的修改,添加了根据用户自定义添加主机,也添加了根据网址或IP进行搜索主机,并添加了线程和信号量锁定。但是添加线程之后,还是出现了打印乱序的情况,类似下图:
大致的情况就是有时候输出不会换行;端口扫描的顺序与hosts列表顺序不相符合;每次总是先输出正在扫描某个端口,然后在输出开放的端口,最后输出关闭的端口,可能是整个代码的逻辑问题,我本来想的是输出正在扫描的端口,然后马上输出该端口的状态,然后再扫描下一个端口。后来我想了很多办法,大致解决了一些,修改的代码部分如下:
def Scanner(host,port):
try:
s = socket.socket()
s.connect((host,port))
s.send('Primal Security \n')
banner = s.recv(1024)
screenLock.acquire()
print "[+] Connecting to " +host+":" + str(port)
print "[+]Port" + str(port) + "open: "
print "[+]>>>\n"+str(banner)
screenLock.release()
s.close()
except:
screenLock.acquire()
print "[+] Connecting to " +host+":" + str(port)
print "[-]Port" + str(port) + "closed\n"
screenLock.release()
就这样,每有一个打印,我就给它添加一个信号量锁定,打印完成就释放掉,这样解决了输出不规范的问题,也实现了每扫描一个端口就打印出状态,但是端口的扫描顺序还是没有解决。
不过后来想一想,其实这样也不错,先输出开放的端口,更便于使用的人分析。甚至可以吧后面关闭的端口输出删除掉。所以就没有再修改这个代码。