更新于2024.01.03
ffmpeg
字幕压入
文件输出在当前目录下的output
目录中。
Python
版
自动读取视频目录下同名/同名.sc/同名.tc的ass
字幕文件
import os
input_folder = "./"
output_folder = "output"
if not os.path.exists(output_folder):
os.makedirs(output_folder)
for filename in os.listdir(input_folder):
if filename.endswith(".mkv"):
# .ass为默认后缀,.sc.ass或.tc.ass都是一个道理
subtitle_file = os.path.splitext(filename)[0] + ".ass"
subtitle_path = os.path.join(input_folder, subtitle_file)
if os.path.exists(subtitle_path):
print(f"Found subtitle file: {subtitle_file}")
output_filename = os.path.join(output_folder, f"{os.path.splitext(filename)[0]}_with_subtitles.mkv")
cmd = f'ffmpeg -i "{os.path.join(input_folder, filename)}" -c:v hevc_nvenc -preset slow -vf "ass=\'{subtitle_path}\'" -c:a copy "{output_filename}"'
os.system(cmd)
else:
print(f"Not Found subtitle file: {subtitle_file}")
只有集数相同,命名不同。
import os
# 假设你有多个目录
input_directories = ["./S1/", "./S2/"]
for input_folder in input_directories:
# 构建对应目录的 output_folder
output_folder = os.path.join(input_folder, "output")
if not os.path.exists(output_folder):
os.makedirs(output_folder)
for video_filename in os.listdir(input_folder):
if video_filename.endswith(".mkv"):
# 提取视频文件名的集数信息
# 将视频文件先以[进行分割。
# 如原视频名字为"[Hakugetsu&VCB-Studio] No Game No Life [11][Hi10p_1080p][x264_flac].mkv",则产生的数组为"'', 'Hakugetsu&VCB-Studio] No Game No Life ', '11][Hi10p_1080p][x264_flac].mkv'"
# [2]: 这一部分选择了列表中的第三个元素,即 '11][Hi10p_1080p][x264_flac].mkv'
# .split("]"): 接着,我们再次使用 ] 分割该元素,得到数组 "'11', '', 'Hi10p_1080p', '', 'x264_flac', '.mkv'"
# [0]: 最后,我们选择这个列表的第一个元素,即 '11'
# .strip(): 最后,我们使用 .strip() 方法去除可能存在的额外空格或换行符。
video_info = video_filename.split("[")[2].split("]")[0].strip()
# 构建基于集数信息的字幕文件名
# 字幕文件 前缀
subtitle_file_prefix = "[Haruhana] Shigatsu wa Kimi no Uso"
subtitle_file = f"{subtitle_file_prefix} [{video_info}]"
# 获取以subtitle_file开头的字幕文件。循环查找是因为有些字幕文件分为chs/cht这种,循环查找是方便取第一个或者是第二个
subtitle_file_list = [f for f in os.listdir(input_folder) if f.startswith(subtitle_file) and f.endswith(".ass")]
if subtitle_file_list:
# 取第一个匹配的字幕文件
subtitle_file_final = subtitle_file_list[0]
# 构建最终的字幕文件名
subtitle_path = os.path.join(input_folder, f"{subtitle_file_final}")
# 字幕文件名与视频文件相同的代码
# subtitle_file = os.path.splitext(video_filename)[0] + ".ass"
# subtitle_path = os.path.join(input_folder, subtitle_file)
if os.path.exists(subtitle_path):
print(f"找到字幕文件:{subtitle_path}(视频文件名:{video_filename})")
output_filename = os.path.join(output_folder, f"{os.path.splitext(video_filename)[0]}_with_subtitles.mkv")
cmd = f'ffmpeg -i "{os.path.join(input_folder, video_filename)}" -c:v hevc_nvenc -preset slow -vf "ass=\'{subtitle_path}\'" -c:a copy "{output_filename}"'
#os.system(cmd)
else:
print(f"未找到与视频对应的字幕文件:{subtitle_path}(视频文件名:{video_filename})")
将视频流的软字幕压为硬字幕
import os
# 获取当前脚本文件所在目录
script_dir = os.path.dirname(os.path.realpath(__file__))
# 假设你有多个目录,每个目录都是相对于当前脚本文件的路径
input_directories = [
os.path.join(script_dir, "specials1"),
os.path.join(script_dir, "specials2"),
# 添加其他目录...
]
for input_folder in input_directories:
# 进入当前视频文件所在的目录,因为读取视频流的字幕时无法使用路径
os.chdir(input_folder)
for video_filename in os.listdir(input_folder):
if video_filename.endswith(".mkv"):
video_path = os.path.join(input_folder, video_filename)
output_folder = os.path.join(input_folder, "output")
output_filename = os.path.join(output_folder, f"{os.path.splitext(video_filename)[0]}_with_subtitles.mkv")
if not os.path.exists(output_folder):
os.makedirs(output_folder)
# 构建ffmpeg命令,使用相对路径
cmd = f'ffmpeg -i "{video_filename}" -map 0:v:0 -map 0:a:0 -vf "subtitles=\'{video_filename}\':si=0" -c:v hevc_nvenc -preset slow "{output_filename}"'
# print("command=", cmd)
# 执行ffmpeg命令
os.system(cmd)
# 返回上一级目录
os.chdir('..')
Google Colab
版
自己新建一个ipynb
后缀的文件,然后复制粘贴进去,上传到Google Drive
然后用Google colab
打开即可。
{"nbformat":4,"nbformat_minor":0,"metadata":{"colab":{"provenance":[],"gpuType":"T4","authorship_tag":"ABX9TyMeMbxvDju/r0x4ojRSg0PV"},"kernelspec":{"name":"python3","display_name":"Python 3"},"language_info":{"name":"python"},"accelerator":"GPU"},"cells":[{"cell_type":"markdown","metadata":{"id":"V2TJGw35rxVm"},"source":["### <font size=5px color=\"red\">✦ *Google Colab 突破90分钟自动断开:</font>\n","<p><font size=3px > 每60分钟自动运行代码以刷新90分钟断开限制. 打开 developer-settings (在你的浏览器) 快速健 Ctrl+Shift+I 然后按console 输入以下代码 Enter. ( mac 按 Option+Command+I)</p><b>复制以下隐藏代码粉贴在浏览器console!!不要关闭浏览器以免失效</b>"]},{"cell_type":"markdown","metadata":{"id":"riiKlEyvr24C"},"source":["**加粗文字**<code>function ClickConnect(){\n","console.log(\"Working\");\n","document.querySelector(\"colab-connect-button\").click()\n","}setInterval(ClickConnect,6000)</code>"]},{"cell_type":"code","metadata":{"id":"i3D8AT00r99O","colab":{"base_uri":"https://localhost:8080/","height":35},"executionInfo":{"status":"ok","timestamp":1704197676527,"user_tz":-480,"elapsed":17,"user":{"displayName":"Nothing Impossible","userId":"10750132342185874405"}},"outputId":"2b4047f8-5dd9-4edc-d07f-1e6053233ef6"},"source":["#@markdown <h3>← 输入了代码后运行以防止断开</h>\n","\n","\n","import IPython\n","from google.colab import output\n","\n","display(IPython.display.Javascript('''\n"," function ClickConnect(){\n"," btn = document.querySelector(\"colab-connect-button\")\n"," if (btn != null){\n"," console.log(\"Click colab-connect-button\");\n"," btn.click()\n"," }\n","\n"," btn = document.getElementById('ok')\n"," if (btn != null){\n"," console.log(\"Click reconnect\");\n"," btn.click()\n"," }\n"," }\n","\n","setInterval(ClickConnect,60000)\n","'''))\n","\n","print(\"Done.\")"],"execution_count":null,"outputs":[{"output_type":"display_data","data":{"text/plain":["<IPython.core.display.Javascript object>"],"application/javascript":["\n"," function ClickConnect(){\n"," btn = document.querySelector(\"colab-connect-button\")\n"," if (btn != null){\n"," console.log(\"Click colab-connect-button\");\n"," btn.click()\n"," }\n","\n"," btn = document.getElementById('ok')\n"," if (btn != null){\n"," console.log(\"Click reconnect\");\n"," btn.click()\n"," }\n"," }\n","\n","setInterval(ClickConnect,60000)\n"]},"metadata":{}},{"output_type":"stream","name":"stdout","text":["Done.\n"]}]},{"cell_type":"markdown","source":["# **安装FFMPEG**"],"metadata":{"id":"uw2TkDnUmh_N"}},{"cell_type":"code","execution_count":null,"metadata":{"id":"TvkvILPPl40C"},"outputs":[],"source":["!apt-get install ffmpeg\n"]},{"cell_type":"markdown","source":["# **挂载`google drive`**"],"metadata":{"id":"whMi4krAmdIM"}},{"cell_type":"code","source":["from google.colab import drive\n","\n","drive.mount('/content/drive')\n"],"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"id":"ekTcyptRmxER","executionInfo":{"status":"ok","timestamp":1704192097454,"user_tz":-480,"elapsed":33685,"user":{"displayName":"Nothing Impossible","userId":"10750132342185874405"}},"outputId":"11c97014-44d9-4a80-8349-28e96603af7b"},"execution_count":null,"outputs":[{"output_type":"stream","name":"stdout","text":["Mounted at /content/drive\n"]}]},{"cell_type":"markdown","source":["查看`GPU`型号"],"metadata":{"id":"I78yIXGCvf45"}},{"cell_type":"code","source":["print(\"============查看GPU信息================\")\n","# 查看GPU信息\n","!/opt/bin/nvidia-smi\n","print(\"==============查看pytorch版本==============\")\n","# 查看pytorch版本\n","import torch\n","print(torch.__version__)\n","print(\"============查看虚拟机硬盘容量================\")\n","# 查看虚拟机硬盘容量\n","!df -lh\n","print(\"============查看cpu配置================\")\n","# 查看cpu配置\n","!cat /proc/cpuinfo | grep model\\ name\n","print(\"=============查看内存容量===============\")\n","# 查看内存容量\n","!cat /proc/meminfo | grep MemTotal\n"],"metadata":{"id":"77j7PzPvviVR"},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":["# **安装字体**"],"metadata":{"id":"jorJDTY3t6fY"}},{"cell_type":"code","source":["import os\n","import shutil\n","\n","def copy_fonts(root_folder, target_folder):\n"," # 更改文件系统权限,使其可写\n"," #!sudo mount -o remount,rw /\n","\n"," for root, dirs, files in os.walk(root_folder):\n"," for file in files:\n"," if file.lower().endswith(('.ttf', '.ttc', '.otf')):\n"," font_path = os.path.join(root, file)\n","\n"," # 复制字体文件到目标文件夹\n"," shutil.copy(font_path, target_folder)\n","\n","\n"," # 显示安装进度\n"," print(f\"已安装字体: {file}\")\n","\n"," # 恢复文件系统权限为只读\n"," #!sudo mount -o remount,ro /\n","\n","# 替换为实际的根目录和目标目录\n","root_directory = '/content/drive/MyDrive/字体'\n","target_directory = '/usr/share/fonts/truetype/'\n","\n","# 复制字体文件\n","copy_fonts(root_directory, target_directory)\n","\n","# 更新字体缓存\n","!fc-cache -vf\n"],"metadata":{"id":"pHg5vAW4t_Ro"},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":["# **修改并运行`ffmpeg`命令**\n","\n"],"metadata":{"id":"vZaQngN-nUcs"}},{"cell_type":"code","source":["import os\n","import subprocess\n","\n","input_folder = \"/content/drive/MyDrive/ownbackup/[VCB-Studio] Himouto! Umaru-chan R [Ma10p_1080p]/\"\n","output_folder = \"/content/drive/MyDrive/ownbackup/[VCB-Studio] Himouto! Umaru-chan R [Ma10p_1080p]/output/\"\n","\n","if not os.path.exists(output_folder):\n"," os.makedirs(output_folder)\n","\n","for filename in os.listdir(input_folder):\n"," if filename.endswith(\".mkv\"):\n"," # .ass为默认后缀,.sc.ass或.tc.ass都是一个道理\n"," subtitle_file = os.path.splitext(filename)[0] + \".[Suzu-Kaze].ass\"\n"," subtitle_path = os.path.join(input_folder, subtitle_file)\n","\n"," if os.path.exists(subtitle_path):\n"," print(f\"Found subtitle file: {subtitle_file}\")\n"," output_filename = os.path.join(output_folder, f\"{os.path.splitext(filename)[0]}_with_subtitles.mkv\")\n"," cmd = f'ffmpeg -hwaccel nvdec -y -i \"{os.path.join(input_folder, filename)}\" -c:v hevc_nvenc -preset fast -vf \"ass=\\'{subtitle_path}\\'\" -c:a copy \"{output_filename}\"'\n"," #os.system(cmd)\n"," # 使用subprocess.run捕获输出\n"," process = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True)\n","\n"," # 实时输出ffmpeg的运行情况\n"," for line in process.stdout:\n"," print(line.strip())\n"," else:\n"," print(f\"Not Found subtitle file: {subtitle_file}\")\n"],"metadata":{"id":"aLMYrz4twXUP"},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":["单文件"],"metadata":{"id":"B0CuJ6Y513Xh"}},{"cell_type":"code","source":["import subprocess\n","\n","input_file = '/content/drive/MyDrive/ownbackup/[VCB-Studio] Himouto! Umaru-chan R [Ma10p_1080p]/[VCB-Studio] Himouto! Umaru-chan R [01][Ma10p_1080p][x265_flac].mkv'\n","ass_file = '/content/drive/MyDrive/ownbackup/[VCB-Studio] Himouto! Umaru-chan R [Ma10p_1080p]/[VCB-Studio] Himouto! Umaru-chan [01][Ma10p_1080p][x265_2flac].Kamigami-SC.ass'\n","output_file = '/content/drive/MyDrive/ownbackup/[VCB-Studio] Himouto! Umaru-chan R [Ma10p_1080p]/1.mkv'\n","\n","ffmpeg_command = f'ffmpeg -y -i \"{input_file}\" -c:v hevc_nvenc -preset slow -vf \"ass=\\'{ass_file}\\'\" -c:a copy \"{output_file}\"'\n","#ffmpeg_command = f'ffmpeg -y -i \"{input_file}\" -c:v libx265 -preset slow -vf \"ass=\\'{ass_file}\\'\" -c:a copy \"{output_file}\"'\n","#ffmpeg_command = f'ffmpeg -y -i \"{input_file}\" -c:v hevc_nvenc -preset slow -vf \"subtitles=\\'{ass_file}\\'\" -c:a copy -scodec mov_text \"{output_file}\"'\n","\n","# 使用 Popen 以便能够读取 stderr 输出\n","process = subprocess.Popen(ffmpeg_command, shell=True, stderr=subprocess.PIPE)\n","\n","# 读取并打印输出\n","while True:\n"," line = process.stderr.readline().decode()\n"," if not line:\n"," break\n"," print(line.strip())\n"],"metadata":{"id":"aseHDrHMnYwJ"},"execution_count":null,"outputs":[]}]}
bat
版
一坨浓💩的windows
,对感叹号等特殊符号基本不支持😄
@echo off
setlocal enabledelayedexpansion
if not exist "output" mkdir "output"
for %%i in (*.mkv) do (
::如果字幕名字是视频名字.sc/tc这种,就按照后面这个修改即可
::set "subtitleFile=%%~ni.sc.ass"
set "subtitleFile=%%~ni.ass"
if exist "!subtitleFile!" (
echo Found subtitle file: "!subtitleFile!"
ffmpeg -i "%%i" -c:v hevc_nvenc -preset slow -vf "ass='!subtitleFile!'" -c:a copy -c:s mov_text "output/%%~ni_with_subtitles.mkv"
) else (
echo Not Found subtitle file: "!subtitleFile!"
)
)
endlocal
宝塔面板/www/backup/panel
目录下文件清理
定时运行即可。默认保留最新的三个目录,版本不同可能为压缩包而非文件夹,请自行修改。
#!/bin/bash
backup_dir="/www/backup/panel"
# 切换到备份目录
cd "$backup_dir" || exit
# 列出目录,并按照时间顺序排序
directories=($(ls -1dt */))
# 列出压缩包文件,并按照时间顺序排序
# directories=($(ls -1t *"$extension"))
# 获取数量
num_directories=${#directories[@]}
# 保留最新的3个目录,删除其余的
if [ "$num_directories" -gt 3 ]; then
directories_to_delete=("${directories[@]:3}")
for dir in "${directories_to_delete[@]}"; do
rm -rf "$dir"
echo "删除目录: $dir"
done
else
echo "目录数量不超过3个,无需删除。"
fi
统计txt
文本总字数以及字频
稍微处理了一下一段长句中英文单词的问题,中文默认按单文字统计。
# -*- coding:utf-8 -*-
import re
def is_english(word):
return all('\u4e00' > c or c > '\u9fff' for c in word)
file_path = input("请输入文件路径:") # 在命令行手动输入文件路径
# 默认使用utf8编码打开,如果乱码请尝试gbk等编码
fr = open(file_path, 'r', encoding='utf8', errors='ignore')
words = []
stat = {}
total_characters = 0
unique_characters_count = 0 # 出现的不同字符数量
current_word = '' # 用于存储当前的英文单词
for line in fr:
line = line.strip() # 去掉空白
if len(line) == 0: # 如果为空,跳过这行
continue
total_characters += len(line) # 统计总字数
# 使用正则表达式识别英文单词
word_list = re.findall(r'\b\w+\b', line)
for word in word_list:
if is_english(word):
if word not in words: # 没有记录的,加入
words.append(word)
if word not in stat: # 没有在字典的,加入并设置初始值0
stat[word] = 0
unique_characters_count += 1 # 出现的字符,不同字符数量+1
stat[word] += 1 # 出现的单词,频率+1
else:
for char in word:
# 用于处理一段有中英文的句子中的英文内容
if is_english(char):
current_word += char
else:
if current_word: # 处理上一个英文单词
if current_word not in words:
words.append(current_word)
if current_word not in stat:
stat[current_word] = 0
unique_characters_count += 1
stat[current_word] += 1
current_word = '' # 重置当前的英文单词
if char not in words: # 没有记录的,加入
words.append(char)
if char not in stat: # 没有在字典的,加入并设置初始值0
stat[char] = 0
unique_characters_count += 1 # 出现的字符,不同字符数量+1
stat[char] += 1 # 出现的字符,频率+1
fr.close()
print(f"总字数:{total_characters}")
print(f"不同字符数量:{unique_characters_count}")
# Output to result.txt
with open('result.txt', 'w', encoding='utf-8') as output_file:
output_file.write(f"总字数:{total_characters}\n")
output_file.write(f"不同字符数量:{len(words)}\n")
stat2 = sorted(stat.items(), key=lambda x: x[1], reverse=True)
for key, value in stat2:
output_file.write(f"{key} {value}\n")
print("结果已经保存到 result.txt 文件中。")
删除qb
torrent not registered with this tracker
种子
个人是按照分类来过滤的,如果是标签啥的请自行修改。
import requests
import concurrent.futures
import time
# 定义你的 qB UI 的地址
host = "http://0.0.0.0:8080"
# 定义用户名和密码
username = "admin"
password = "adminadmin"
# 定义需要过滤的种子分类
categories = ["a1", "a2", "a3"]
# 定义 Telegram Bot 的 API token
telegram_token = 'Your Token'
# 定义 Telegram 用户ID
telegram_chat_id = 'Your ID'
# 登录并获取 CSRF Token
def get_csrf_token():
login_url = f"{host}/api/v2/auth/login"
login_data = {"username": username, "password": password}
headers = {'User-Agent': 'Mozilla/5.0'}
response = requests.post(login_url, data=login_data, headers=headers)
response.raise_for_status()
return response.cookies.get('SID')
# 定义一个函数,用于获取 JSON 数据
def fetchJSON(url, cookies):
headers = {'User-Agent': 'Mozilla/5.0'}
response = requests.get(url, cookies={'SID': cookies}, headers=headers)
response.raise_for_status()
return response.json()
# 删除种子及相关文件的函数
def delete_torrents(hash, cookies):
delete_url = f"{host}/api/v2/torrents/delete"
# deletefiles=true表示种子和文件一起删除
data = {'hashes': hash, 'deleteFiles': 'true'}
headers = {'User-Agent': 'Mozilla/5.0'}
response = requests.post(delete_url, data=data, cookies={'SID': cookies}, headers=headers)
response.raise_for_status()
result = response.json()
if result["deleted"] == [hash]:
messages.append(f"种子 {hash} 及相关文件删除成功")
else:
messages.append(f"种子 {hash} 及相关文件删除失败")
# 处理种子的函数
def process_torrent(hash, data, cookies):
if data["category"] in categories:
# 获取特定种子的信息
trackers = fetchJSON(f"{host}/api/v2/torrents/trackers?hash={hash}", cookies)
name = data["name"]
# 过滤出符合条件的种子信息
filteredTrackers = [tracker for tracker in trackers if tracker["msg"] == "torrent not registered with this tracker"]
if len(filteredTrackers) > 0:
# 发送符合条件的种子信息到 Telegram
message = f"种子名称: {name}\nhash值: {hash}"
messages.append(message)
# 删除符合条件的种子及相关文件
delete_torrents(hash, cookies)
# 发送消息到 Telegram
def send_telegram_message(message):
combined_message = '\n'.join(messages)
requests.get(f"https://api.telegram.org/bot{telegram_token}/sendMessage?chat_id={telegram_chat_id}&text={combined_message}")
# 主函数
def main():
try:
start_time = time.time()
# 获取 CSRF Token
cookies = get_csrf_token()
# 定义全局消息列表
global messages
messages = []
# 获取主数据
maindata_url = f"{host}/api/v2/sync/maindata"
maindata = fetchJSON(maindata_url, cookies)
# 使用多线程处理种子
with concurrent.futures.ThreadPoolExecutor() as executor:
for hash, data in maindata["torrents"].items():
executor.submit(process_torrent, hash, data, cookies)
end_time = time.time()
execution_time = end_time - start_time
message = f"程序运行时间:{execution_time} 秒"
messages.append(message)
send_telegram_message(messages)
except requests.exceptions.RequestException as e:
print("发生错误:", e)
send_telegram_message(f"发生错误: {e}")
# 调用主函数
if __name__ == "__main__":
main()
nexusphp
架构的pt
站种子感谢脚本
不建议滥用,仅在需要时使用
import requests
import time
import random
# pt站感谢的链接,如示例
url = "https://ptexample.com/thanks.php"
# 请求pt站的header
base_referer = "https://ptexample.com/details.php?id="
# 请求pt站的header
h = {
'Host': 'ptexample.com',
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/112.0.0.0 Safari/537.36',
'Accept-Language': 'zh-CN',
}
# pt站cookie信息,这只是示例,你可以自己添加更多
c = {
'c_secure_uid': '',
'c_secure_pass': '',
'c_secure_ssl': '',
'c_secure_tracker_ssl': '',
'c_secure_login': '',
}
s = requests.Session()
s.cookies.update(c)
# 感谢种子的起始ID和结束ID
start_num = 1
end_num = 4000
for d in range(start_num, end_num):
#md = random.randint(start_num, end_num)
md = d
referer = base_referer + str(md)
h['Referer'] = referer # Update the Referer in the header
s.headers.update(h) # Update the headers in the session
req = s.post(url, data={'id': md})
print('第', d - start_num + 1, '个; 种子ID:', md, 'status:', req.status_code)
# 休眠时间随机范围,单位为s
delay_t = random.randint(10, 40)
print("休眠时间:",delay_t)
time.sleep(delay_t) # delay
问卷星刷提交脚本
可能有时效性,请自行甄别。
import time
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.service import Service
from selenium import webdriver
import random
j = 1
word = '填空题'
# 填写次数
while (j < 151):
# chrome_options = webdriver.ChromeOptions()
# chrome_options.add_argument('--headless')
# driver = webdriver.Chrome(options=chrome_options)
# driver = webdriver.Chrome()
option = webdriver.ChromeOptions()
option.binary_location = r'D:\Software\Chrome83_x32\App\chrome.exe' # 替换为你的Chrome安装路径
driver_path = r'D:\Software\Chrome83_x32\App\chromedriver.exe' # 替换为你的chromeDriver路径
service = Service(executable_path=driver_path)
option.add_argument('--no-sandbox')
option.add_argument('--disable-gpu')
option.add_experimental_option('excludeSwitches', ['enable-automation'])
option.add_experimental_option('useAutomationExtension', False)
driver = webdriver.Chrome(options=option, service=service)
driver.execute_cdp_cmd('Page.addScriptToEvaluateOnNewDocument',
{'source': 'Object.defineProperty(navigator, "webdriver", {get: () => undefined})'})
driver.get("https://www.wjx.cn/vm/aaaaa.aspx")
time.sleep(2)
# 选择题数目+1,比如15道就是16
for i in range(1, 17):
n = random.randint(1, 4)
n1 = random.randint(1, 2)
time.sleep(0.3)
try:
element = driver.find_element(
By.CSS_SELECTOR,
"#div{} > div.ui-controlgroup > div:nth-child({})".format(i, n))
element.click()
except:
try:
element = driver.find_element(
By.CSS_SELECTOR,
"#div{} > div.ui-controlgroup > div:nth-child({})".format(i, n1))
element.click()
except:
pass
# 输入题
# input = driver.find_element(By.ID, "q11")
# input.send_keys(word)
# 输入之后与点击提交的时间差
time.sleep(2.5)
tijiao = driver.find_element(By.ID, "ctlNext")
tijiao.click()
time.sleep(1)
# 先点击验证的弹出提示框
try:
driver.find_element(By.XPATH, "//div[@id='captcha']").click()
time.sleep(4)
except:
pass
# 再点击验证
try:
driver.find_element(By.XPATH, "//div[@id='captcha']").click()
time.sleep(4)
except:
pass
driver.close()
print("已经提交{}次".format(j))
j = j + 1
检测域名脚本
依赖于系统的whois
命令。
#!/usr/bin/env python3
# VERSION: 23.11.23
# LICENSE: CC0
# AUTHOR: Cagamine Lin
#
# Usage:
# 脚本依赖于系统的whois命令,跑之前请确保已安装
# 然后自己查询一次对应后缀未注册和已注册域名的输出
# 找到关键词填入sample和sample_fail参数
# sample 通常是类似'not found','not match'的文本
# sample_fail,通常是类似'create time','expiry time'的文本
# - 可以留空,这样会在没搜索到sample时当已注册处理,
# - 不留空,则会既没搜索到sample,又没sample_fail时标记为 [?] , 以便您另外查
# 关键词不要写太短,防止匹配的后面的注释导致误差, 有标点
# 最后把后缀,长度,字符表分别填入参数suffix, length, chars
WORD = 'abcdefghijklmnopqrstuvwxyz'
DIG = '0123456789'
# Begin of params
sample = 'was not found.'
sample_fail = ''
suffix = 'pro'
length = 3
# chars = DIG+WORD
# chars = DIG
chars = WORD
# End of params
import subprocess
from time import sleep
from datetime import datetime
from itertools import product
def check(target, sample, sample_fail='', retry_rule=[5, 5, 20]):
retry = 0
while True:
try:
output = subprocess.check_output(
['whois', target], shell=False, text=True)
if sample in output:
return 'ok'
if sample_fail in output:
return 'fail'
raise Exception('unknown ')
except Exception as e:
print(e)
retry += 1
sleep(retry_rule[retry])
if retry > len(retry_rule):
return 'unknown'
def run(chars, length, suffix, sample, sample_fail='', retry_rule=[5, 5, 20], save=True):
filename = save == True and datetime.now().strftime(
f"{suffix}-{length}_%y-%m-%d_%H%M%S.txt")
file = save and open(filename, "w")
log = save and (lambda s: (file.write(s+'\n'),
file.flush())) or (lambda s: s)
print('# Targets:')
print('[%s]{%d}.%s\n' % (chars, length, suffix))
print('# Report:', save and f'(save to {filename})' or '')
it = product(chars, repeat=length)
for i in it:
name = ''.join(i) + '.' + suffix
print(f' {name} checking...\r', end='')
res = check(name, sample, sample_fail, retry_rule)
if res == 'ok':
print(f' {name} ')
log(name)
elif res == 'unknown':
print(f' {name} [?] ')
log(name+' [?]')
save and file.close()
run(chars, length, suffix, sample, sample_fail)
自用的部分Shell
脚本工具箱
源码在这儿
bash -c "$(curl -L https://github.com/Xiefengshang/ownscript/raw/main/own_box.sh)"