最近在看《Violent Python》,记录一些代码实现。
0x00 简单端口扫描器Python实现
本例使用Socket模块用来建立TCP连接。
0x01 代码实现
import optparse
import socket
import threading
screenLock = threading.Semaphore(value=1)
def connScan(tgtHost, tgtPort):
try:
connSkt = socket.socket(socket.AF_INET, socket.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.release()
print '[-]%d/tcp closed' %tgtPort
finally:
screenLock.release()
connSkt.close()
def portScan(tgtHost, tgtPorts):
try:
tgtIP = socket.gethostbyname(tgtHost)
except:
print "[-] Cannot resolve '%s':Unknown host" %tgtHost
return
try:
tgtName = socket.gethostbyaddr(tgtIP)
print '\n[+] Scan Results for: ' + tgtName[0]
except:
print '\n[+] Scan Results for: ' + tgtIP
socket.setdefaulttimeout(1)
for tgtPort in tgtPorts:
t = threading.Thread(target=connScan, args=(tgtHost, int(tgtPort)))
t.start()
def main():
parser = optparse.OptionParser("userage%prog -H -p ")
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 '[-] You must specify a target host and port[s].'
exit(0)
portScan(tgtHost, tgtPorts)
if __name__ == '__main__':
main()
0x10 效果
Tips:多个端口需用引号在命令行中引出来,书中并没有说明!
0x11 利用python-nmap实现端口扫描
import nmap
import optparse
def nmapScan(tgtHost, tgtPort):
# Init a nmap portscanner
nmScan = nmap.PortScanner()
nmScan.scan(tgtHost, tgtPort)
#get the port state
state = nmScan[tgtHost]['tcp'][int(tgtPort)]['state']
print " [*] " + tgtHost + " tcp/" + tgtPort + " " + state
def main():
parser = optparse.OptionParser("usage %prog -H -p ")
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)
for tgtPort in tgtPorts:
nmapScan(tgtHost, tgtPort)
if __name__ == '__main__':
main()
例子比较简单,也可使用线程完成,主要是简单了解Nmap模块的使用。