Shelify python scripts

This commit is contained in:
oitsjustjose 2026-06-20 19:24:43 -05:00
commit cf03a4ffc9
13 changed files with 239 additions and 342 deletions

View file

@ -1,17 +1,21 @@
#!/bin/bash #!/bin/bash
if [[ -z "$1" ]]; then if [[ -z "$1" ]]; then
echo "Missing required argument [heif_file]!" echo "Missing required argument [heif_file]!"
exit 1 exit 1
fi fi
# Set up the python environment # Set up the python environment
if [ ! -f "/tmp/shell-scripts/venv/bin/python" ]; then
mkdir -p /tmp/shell-scripts mkdir -p /tmp/shell-scripts
python3 -m venv /tmp/shell-scripts/env > /dev/null 2>&1 python3 -m venv /tmp/shell-scripts/venv > /dev/null 2>&1
fi
# Install reqs # Install reqs
/tmp/shell-scripts/venv/bin/pip install pillow pillow-heif > /dev/null 2>&1 /tmp/shell-scripts/venv/bin/pip install pillow pillow-heif > /dev/null 2>&1
# Finally run the script # Finally run the script
/tmp/shell-scripts/venv/bin/python << EOF /tmp/shell-scripts/venv/bin/python << EOF
from PIL import Image from PIL import Image
from pillow_heif import register_heif_opener from pillow_heif import register_heif_opener
from pathlib import Path from pathlib import Path
@ -24,6 +28,7 @@ if path.suffix.lower() != ".heic":
register_heif_opener() register_heif_opener()
im = Image.open(path) im = Image.open(path)
im.save(path.with_suffix(".jpeg"), quality=100) im.save(path.with_suffix(".jpeg"), quality=100)
EOF EOF

128
linux/jarscan Executable file
View file

@ -0,0 +1,128 @@
#!/bin/bash
export DIR=$(pwd)
# Source - https://stackoverflow.com/a/7069755
# Posted by Flexo - Save the data dump, modified by community. See post 'Timeline' for change history
# Retrieved 2026-06-20, License - CC BY-SA 4.0
while test $# -gt 0; do
case "$1" in
-h|--help)
echo "jarscan - scan jars for a file with a given search string."
echo " Supports deep searching (searching all files within the jar) and regex"
echo " "
echo "Usage:"
echo " jarscan your-query-here [-d,--dir=DIR] [-r,--regex] [-D,--deep] "
echo " "
echo "options:"
echo "-h, --help Show this prompt"
echo "-d, --dir=DIR The directory to scan. Defaults to $(pwd)"
echo "-r, --regex Parse and use RegExp in your expression"
echo "-D, --deep Perform a deep search, scanning file contents for your query"
exit 0
;;
-d)
shift
if test $# -gt 0; then
export DIR=$1
else
echo "No directory specified!"
exit 1
fi
shift
;;
--dir*)
export DIR=`echo $1 | sed -e 's/^[^=]*=//g'`
shift
;;
-r|--regex)
export USE_REGEX=1
shift
;;
-D|--deep)
export USE_DEEP=1
shift
;;
*)
if test -z "$QUERY"; then
export QUERY=$1
shift
else
echo "Only one query can be provided!"
exit 1
fi
;;
esac
done
if test -z "$QUERY"; then
echo "Query is required!"
exit 1
fi
# Set up the python environment
if [ ! -f "/tmp/shell-scripts/venv/bin/python" ]; then
mkdir -p /tmp/shell-scripts
python3 -m venv /tmp/shell-scripts/venv > /dev/null 2>&1
fi
# Finally run the script
/tmp/shell-scripts/venv/bin/python << EOF
import os
import re
from argparse import ArgumentParser
from pathlib import Path
from sys import exit
from zipfile import ZipFile
scan_dir = Path("$DIR").resolve()
query = "$QUERY"
regex = "$USE_REGEX" == "1"
deep = "$USE_DEEP" == "1"
def scan_jar(jar_path: Path) -> None:
"""Opens the jar at jar_path and iterates over all files within,
determining if the file name matches
Args:
jar_path (Path): The absolute path, resolved, to the Jar file
"""
def __test(scan_target: str) -> bool:
"""Scans the scan_target to see if it contains the queries from the parsed args.
If the args instruct us to use regex, compile the regex and attempt to use it
Args:
scan_target (str): The text to scan for - can be a filename or file contents
Returns:
bool: True if the scan_target contains the query or regex
"""
if regex:
try:
return re.compile(query).search(scan_target) is not None
except re.error as err:
print(f"Regex Error! Invalid regular expression passed:\nFull Trace:\n{err}")
exit(1)
else:
return query in scan_target
with ZipFile(jar_path, "r") as jar:
for file_name in jar.namelist():
if deep: # Perform a deep scan of the jar itself
with jar.open(file_name) as file:
try:
if __test(file.read().decode()):
print(f"[{jar_path.relative_to(scan_dir)}] :: {file_name}")
except UnicodeDecodeError:
pass # This just means the file was a binary / non-text file
elif __test(file_name):
print(f"[{jar_path.relative_to(scan_dir)}] :: {file_name}")
for root, _, files in os.walk(Path("$DIR").resolve()):
for file in list(filter(lambda x: x.endswith(".jar"), files)):
scan_jar(Path(f"{root}/{file}"))
EOF

103
linux/makerand Executable file
View file

@ -0,0 +1,103 @@
#!/bin/bash
# Source - https://stackoverflow.com/a/7069755
# Posted by Flexo - Save the data dump, modified by community. See post 'Timeline' for change history
# Retrieved 2026-06-20, License - CC BY-SA 4.0
while test $# -gt 0; do
case "$1" in
-h|--help)
echo "makerand - generate a random string"
echo " "
echo "Usage:"
echo " makerand char-count [-e,--exclude-chars=a,b,c,d,e] [-u,--uuid-only]"
echo " "
echo "options:"
echo "-h, --help Show this prompt"
echo "-e,--exclude-chars A comma-delimited list of characters to exclude"
echo "-u,--uid-only Only use [0-9,A-F] characters"
exit 0
;;
-e)
shift
if test $# -gt 0; then
export EXCLUDED=$1
else
echo "No excluded characters were specified!"
exit 1
fi
shift
;;
--exclude-chars*)
export EXCLUDED=`echo $1 | sed -e 's/^[^=]*=//g'`
shift
;;
-u|--uuid-only)
export ONLY_USE_UUID=1
shift
;;
*)
if test -z "$COUNT"; then
export COUNT=$1
shift
else
echo "Only one count can be provided!"
exit 1
fi
;;
esac
done
if test -z "$COUNT"; then
echo "Character count is required!"
exit 1
fi
# Set up the python environment
if [ ! -f "/tmp/shell-scripts/venv/bin/python" ]; then
mkdir -p /tmp/shell-scripts
python3 -m venv /tmp/shell-scripts/venv > /dev/null 2>&1
fi
# Finally run the script
/tmp/shell-scripts/venv/bin/python << EOF
from argparse import ArgumentParser
from random import randint
from uuid import uuid4
def generate_uuid(length: int, current="") -> str:
if len(current) >= length:
return current[:length]
next = current + str(uuid4()).replace("-", "")
return generate_uuid(length, current=next)
def generate(length: int, chars: str, current="") -> str:
if len(current) >= length:
return current[:length]
next = current + chars[randint(0, (len(chars) - 1))]
return generate(length, chars, current=next)
num = int("$COUNT")
chars = "0123456789ABCDEF" if "$ONLY_USE_UUID" == "1" else "ABCDEFGHIJKLMONPQRSTUVWXYZabcdefghijklmonpqrstuvwxyz1234567890!@#$%^&*()-_=+[{]}|;:,<.>/?\`~"
# Support for splitting by commas or not
exclusions = list("".join(map(lambda x: x.strip(), "$EXCLUDED".split(","))))
for exclusion in exclusions:
print(exclusion)
chars = chars.replace(exclusion, "")
# Max recursion depth workaround
rem, accumulator = num, ""
while rem > 0:
amt = min(128, rem)
accumulator += generate(amt, chars)
rem -= amt
print(accumulator)
EOF

View file

@ -1 +0,0 @@
__pycache__

View file

@ -1,70 +0,0 @@
from argparse import ArgumentParser
from random import randint
from uuid import uuid4
from utils import copy_to_clipboard
def generate_uuid(length: int, current="") -> str:
if len(current) >= length:
return current[:length]
next = current + str(uuid4()).replace("-", "")
return generate_uuid(length, current=next)
def generate(length: int, chars: str, current="") -> str:
if len(current) >= length:
return current[:length]
next = current + chars[randint(0, (len(chars) - 1))]
return generate(length, chars, current=next)
def main(args) -> None:
num = int(args.num)
if args.uuid_only:
# Max recursion depth workaround
rem, accumulator = num, ""
while rem > 0:
amt = min(128, rem)
accumulator += generate_uuid(amt)
rem -= amt
if args.copy_to_clipboard:
copy_to_clipboard(accumulator)
print("Copied to clipboard!")
else:
print(accumulator)
else:
exclusions = list(map(lambda x: str(x).strip(), args.exclude_chars.split(",")))
char_choices = "ABCDEFGHIJKLMONPQRSTUVWXYZabcdefghijklmonpqrstuvwxyz1234567890!@#$%^&*()-=_+[]{}\\|;:,<.>/?`~"
for exclusion in exclusions:
char_choices = char_choices.replace(exclusion, "")
# Max recursion depth workaround
rem, accumulator = num, ""
while rem > 0:
amt = min(128, rem)
accumulator += generate(amt, char_choices)
rem -= amt
if args.copy_to_clipboard:
copy_to_clipboard(accumulator)
print("Copied to clipboard!")
else:
print(accumulator)
if __name__ == "__main__":
parser = ArgumentParser(
prog="Make Random",
description="Creates a random GUID-like value of a provided length",
)
parser.add_argument("num")
parser.add_argument("-u", "--uuid-only", action="store_true")
parser.add_argument("-e", "--exclude-chars", default="")
parser.add_argument("-c", "--copy-to-clipboard", action="store_true")
args = parser.parse_args()
main(args)

View file

@ -1,19 +0,0 @@
from argparse import ArgumentParser
from uuid import uuid4
from utils import copy_to_clipboard
def main(args):
if args.copy_to_clipboard:
copy_to_clipboard(str(uuid4()))
print("Copied to clipboard!")
else:
print(str(uuid4()))
if __name__ == "__main__":
parser = ArgumentParser(prog="new-uuid")
parser.add_argument("-c", "--copy-to-clipboard", action="store_true")
args = parser.parse_args()
main(args)

View file

@ -1,2 +0,0 @@
pillow==11.3.0
pillow_heif==1.1.1

View file

@ -1,85 +0,0 @@
import os
import re
from argparse import ArgumentParser
from pathlib import Path
from sys import exit
from zipfile import ZipFile
def scan_jar(jar_path: Path, args) -> None:
"""Opens the jar at jar_path and iterates over all files within,
determining if the file name matches
Args:
jar_path (Path): The absolute path, resolved, to the Jar file
args (Namespace): The program's args from argparse
"""
scan_dir = Path(args.dir).resolve()
def __test(scan_target: str) -> bool:
"""Scans the scan_target to see if it contains the queries from the parsed args.
If the args instruct us to use regex, compile the regex and attempt to use it
Args:
scan_target (str): The text to scan for - can be a filename or file contents
Returns:
bool: True if the scan_target contains the query or regex
"""
if args.regex:
try:
return re.compile(args.query).search(scan_target) is not None
except re.error as err:
print(f"Regex Error! Invalid regular expression passed:\nFull Trace:\n{err}")
exit(1)
else:
return args.query in scan_target
with ZipFile(jar_path, "r") as jar:
for file_name in jar.namelist():
if args.deep: # Perform a deep scan of the jar itself
with jar.open(file_name) as file:
try:
if __test(file.read().decode()):
print(f"[{jar_path.relative_to(scan_dir)}] :: {file_name}")
except UnicodeDecodeError:
pass # This just means the file was a binary / non-text file
elif __test(file_name):
print(f"[{jar_path.relative_to(scan_dir)}] :: {file_name}")
def main(args) -> None:
scan_dir = Path(args.dir).resolve()
for root, _, files in os.walk(scan_dir):
for file in list(filter(lambda x: x.endswith(".jar"), files)):
scan_jar(Path(f"{root}/{file}").resolve(), args)
if __name__ == "__main__":
parser = ArgumentParser(prog="Jar Scanner", description="Scans jars for a given file")
parser.add_argument("query", help="The term (or regex) to search for within the filename")
parser.add_argument(
"-d",
"--dir",
default=os.getcwd(),
help="The directory to scan. Defaults to cwd",
)
parser.add_argument(
"-r",
"--regex",
default=False,
action="store_true",
help="Parse and use regex any in your query.",
)
parser.add_argument(
"-D",
"--deep",
default=False,
action="store_true",
help="Rather than searching the file *name* for the given term (or regex), searches the contents of files instead",
)
args = parser.parse_args()
main(args)

View file

@ -1,54 +0,0 @@
import os
from platform import release, system
from subprocess import check_call
from sys import executable as python
from tempfile import mktemp
from requests import get as fetch
def copy_to_clipboard(val: str) -> bool:
sys = system()
copy_cmd = ""
if sys == "Windows":
copy_cmd = "clip.exe"
elif sys == "macOS":
copy_cmd = "pbcopy"
elif sys == "Linux":
if "WSL" in release():
copy_cmd = "clip.exe" # Windows native clip.exe still works in WSL
else:
copy_cmd = "xclip -selection clipboard"
else:
print(f"System {sys} is not supported - cannot copy to clipboard")
return False
tmp_path = mktemp()
with open(tmp_path, "w", encoding="utf-8") as fh:
fh.write(val.strip())
try:
ret_val = check_call(f"cat {str(tmp_path)} | {copy_cmd}", shell=True)
finally:
os.unlink(tmp_path)
return ret_val == 0
def install_package(package_name: str) -> None:
def _prereq() -> None:
res = os.system(f"{python} -m pip")
if res == 0:
return
data = fetch("https://bootstrap.pypa.io/get-pip.py")
filename = mktemp()
with open(filename, "w", encoding="utf-8") as fh:
fh.write(data.text)
os.system(f"{python} {filename}")
os.unlink(filename)
_prereq()
os.system(f"{python} -m pip install {package_name}")
print(f"Package {package_name} has been installed - please rerun this command!")

View file

@ -1,27 +0,0 @@
#!/bin/bash
cmd_name="jarscan"
script_fn="scan_jars.py"
# Re-run the script as root if we're not
if [ "$EUID" != 0 ]; then
sudo "$0" "$@"
exit $?
fi
echo "Setting up $cmd_name"
if ! command -v /usr/bin/python3 2>&1 >/dev/null
then
echo "/usr/bin/python3 does not exist! Please install it before continuing..."
exit 1
fi
mkdir -p /opt/scripts
cp "../python/$script_fn" "/opt/scripts/$script_fn"
cp "../python/utils.py" "/opt/scripts/utils.py"
# Create executable as a script, install to local/bin
echo "/usr/bin/python3 /opt/scripts/$script_fn \"\$@\"" > $cmd_name
chmod +x $cmd_name
mv $cmd_name /usr/local/bin
echo "Done! Try the command '$cmd_name' to see the effects!"

View file

@ -1,27 +0,0 @@
#!/bin/bash
cmd_name="makerand"
script_fn="make_random.py"
# Re-run the script as root if we're not
if [ "$EUID" != 0 ]; then
sudo "$0" "$@"
exit $?
fi
echo "Setting up $cmd_name"
if ! command -v /usr/bin/python3 2>&1 >/dev/null
then
echo "/usr/bin/python3 does not exist! Please install it before continuing..."
exit 1
fi
mkdir -p /opt/scripts
cp "../python/$script_fn" "/opt/scripts/$script_fn"
cp "../python/utils.py" "/opt/scripts/utils.py"
# Create executable as a script, install to local/bin
echo "/usr/bin/python3 /opt/scripts/$script_fn \"\$@\"" > $cmd_name
chmod +x $cmd_name
mv $cmd_name /usr/local/bin
echo "Done! Try the command '$cmd_name' to see the effects!"

View file

@ -1,27 +0,0 @@
#!/bin/bash
cmd_name="new-uuid"
script_fn="new-uuid.py"
# Re-run the script as root if we're not
if [ "$EUID" != 0 ]; then
sudo "$0" "$@"
exit $?
fi
echo "Setting up $cmd_name"
if ! command -v /usr/bin/python3 2>&1 >/dev/null
then
echo "/usr/bin/python3 does not exist! Please install it before continuing..."
exit 1
fi
mkdir -p /opt/scripts
cp "../python/$script_fn" "/opt/scripts/$script_fn"
cp "../python/utils.py" "/opt/scripts/utils.py"
# Create executable as a script, install to local/bin
echo "/usr/bin/python3 /opt/scripts/$script_fn \"\$@\"" > $cmd_name
chmod +x $cmd_name
mv $cmd_name /usr/local/bin
echo "Done! Try the command '$cmd_name' to see the effects!"

View file

@ -1,27 +0,0 @@
#!/bin/bash
cmd_name="wifi-qr"
script_fn="wifi_qr.py"
# Re-run the script as root if we're not
if [ "$EUID" != 0 ]; then
sudo "$0" "$@"
exit $?
fi
echo "Setting up $cmd_name"
if ! command -v /usr/bin/python3 2>&1 >/dev/null
then
echo "/usr/bin/python3 does not exist! Please install it before continuing..."
exit 1
fi
mkdir -p /opt/scripts
cp "../python/$script_fn" "/opt/scripts/$script_fn"
cp "../python/utils.py" "/opt/scripts/utils.py"
# Create executable as a script, install to local/bin
echo "/usr/bin/python3 /opt/scripts/$script_fn \"\$@\"" > $cmd_name
chmod +x $cmd_name
mv $cmd_name /usr/local/bin
echo "Done! Try the command '$cmd_name' to see the effects!"