首先我们供给一台主机,要进行的步骤就是对其主机端口的扫描,查看其中开放的端口。我们创建一个TCP的全连接的扫描器,使用socket来创建连接器。
扫描端口开放
#测试当前主机和端口是否开放,直接使用socket连接
def connScan(host,port):
try:
connSkt = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
connSkt.connect((host,port))
print("tcp open port:" + str(port))
except:
print('tcp closed:'+str(port))
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:
print('Scanning port ' + str(tgtPort)) connScan(tgtHost, int(tgtPort))
portScan('www.baidu.com', [80,443,3389,1433,23,445])
对百度的端口进行扫描
[+] Scan Results for: 61.135.169.125
Scanning port 80
tcp open port:80
Scanning port 443
tcp open port:443
Scanning port 3389
tcp closed:3389
Scanning port 1433
tcp closed:1433
Scanning port 23
tcp closed:23
Scanning port 445
tcp closed:445
捕获应用标识
为了从捕获我们的目标主机的应用标识,我们必须首先插入额外的验证代码到 connScan函数中。
一旦发现开放的端口,我们发送一个字符串数据到这个端 口然后等待响应。收集这些响应并推断可能会得到运行在目标主机端口上的应 用程序的一些信息。
#测试当前主机和端口是否开放,直接使用socket连接
def connScan(host,port):
try:
connSkt = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
connSkt.connect((host,port))
connSkt.send('Pythonrn')
results = connSkt.recv(100)
print("tcp open port:" + str(port))
print('[+] ' + str(results))
except:
print('tcp closed:'+str(port))
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:
print('Scanning port ' + str(tgtPort))
connScan(tgtHost, int(tgtPort))
portScan('www.qq.com', [22,80,443,3389,1433,23,445])
多线程扫描
因为每一个socket都有时间延迟,每一个socket扫描都将会耗时几秒钟,虽 然看起来无足轻重,但是如果我们扫描多个端口和主机延迟时间将迅速增大。
理想情况下,我们希望这些socket按顺序扫描。引入Python线程。线程提供 了一种同时执行的方式。在我们的扫描中利用线程,只需将 portScan()函数的迭代改一下。
请注意,我们可以把每一个connScan()函数都 当做是一个线程。在迭代的过程中产生的每一个线程将在同时执行。
for tgtPort in tgtPorts:
print('Scanning port ' + str(tgtPort))
t = threading.Thread(target=connScan, args=(tgtHost,
int(tgtPort)))
t.start()
使用nmap
import nmap
def nmapScan(tgtHost, tgtPort):
nmScan = nmap.PortScanner()
results = nmScan.scan(tgtHost, tgtPort)
state = results['scan'][tgtHost]['tcp'][int(tgtPort)]['state']
print(" [*] " + tgtHost + " tcp/" + tgtPort + " " + state)
nmapScan('10.108.x.x','8080')
福利→[linux和python的学习资料大合集](详情页内有提取码)(https://ke.magedu.com/detail/i_5f040f3ce4b036f1c0cf1f90/1)