Started python conversion

This commit is contained in:
2Shirt 2017-12-17 21:22:53 -07:00
parent 1613d767bf
commit a33a54c5e6
19 changed files with 178 additions and 119 deletions

View file

@ -1,13 +1,13 @@
#!/bin/bash
#
## HW diagnostics - Prime95
## Wizard Kit: Apple fan speed tool
SMCPATH="/sys/devices/platform/applesmc.768"
SET_MAX="True"
function usage {
echo "Usage: $0 auto|max"
echo " e.g. $0 max"
echo "Usage: $(basename "$0") auto|max"
echo " e.g. $(basename "$0") max"
}
# Set mode

31
.bin/Scripts/connect_to_network Executable file
View file

@ -0,0 +1,31 @@
#!/bin/python3
#
## Wizard Kit: Network connection tool
import os
import sys
# Init
os.chdir(os.path.dirname(os.path.realpath(__file__)))
sys.path.append(os.getcwd())
from functions.network import *
init_global_vars()
if __name__ == '__main__':
try:
# Prep
clear_screen()
# Connect
if not is_connected():
connect_to_network()
# Done
print_standard('\nDone.')
#pause("Press Enter to exit...")
exit_script()
except SystemExit:
pass
except:
major_exception()

View file

@ -8,7 +8,11 @@ import subprocess
import sys
import time
import traceback
import winreg
try:
import winreg
except ModuleNotFoundError:
if psutil.WINDOWS:
raise
from subprocess import CalledProcessError
@ -26,9 +30,13 @@ COLORS = {
'YELLOW': '\033[33m',
'BLUE': '\033[34m'
}
HKU = winreg.HKEY_USERS
HKCU = winreg.HKEY_CURRENT_USER
HKLM = winreg.HKEY_LOCAL_MACHINE
try:
HKU = winreg.HKEY_USERS
HKCU = winreg.HKEY_CURRENT_USER
HKLM = winreg.HKEY_LOCAL_MACHINE
except NameError:
if psutil.WINDOWS:
raise
# Error Classes
class BIOSKeyNotFoundError(Exception):
@ -86,8 +94,11 @@ def ask(prompt='Kotaero!'):
return answer
def clear_screen():
"""Simple wrapper for cls."""
os.system('cls')
"""Simple wrapper for cls/clear."""
if psutil.WINDOWS:
os.system('cls')
else:
os.system('clear')
def convert_to_bytes(size):
"""Convert human-readable size str to bytes and return an int."""
@ -160,8 +171,10 @@ def get_ticket_number():
_input = input('Enter ticket number: ')
if re.match(r'^([0-9]+([-_]?\w+|))$', _input):
ticket_number = _input
with open(r'{}\TicketNumber'.format(global_vars['LogDir']), 'w',
encoding='utf-8') as f:
out_file = r'{}\TicketNumber'.format(global_vars['LogDir'])
if not psutil.WINDOWS:
out_file = out_file.replace('\\', '/')
with open(out_file, 'w', encoding='utf-8') as f:
f.write(ticket_number)
return ticket_number
@ -272,7 +285,7 @@ def menu_select(title='~ Untitled Menu ~',
answer = ''
while (answer.upper() not in valid_answers):
os.system('cls')
clear_screen()
print(menu_splash)
answer = input('{}: '.format(prompt))
@ -294,7 +307,11 @@ def pause(prompt='Press Enter to continue... '):
def ping(addr='google.com'):
"""Attempt to ping addr."""
cmd = ['ping', '-n', '2', addr]
cmd = [
'ping',
'-n' if psutil.WINDOWS else '-c',
'2',
addr]
run_program(cmd)
def popen_program(cmd, pipe=False, minimized=False, shell=False, **kwargs):
@ -535,14 +552,20 @@ def init_global_vars():
"""Sets global variables based on system info."""
print_info('Initializing')
os.system('title Wizard Kit')
init_functions = [
['Checking .bin...', find_bin],
['Checking environment...', set_common_vars],
['Checking OS...', check_os],
['Checking tools...', check_tools],
['Creating folders...', make_tmp_dirs],
['Clearing collisions...', clean_env_vars],
]
if psutil.LINUX:
init_functions = [
['Checking environment...', set_linux_vars],
['Clearing collisions...', clean_env_vars],
]
else:
init_functions = [
['Checking .bin...', find_bin],
['Checking environment...', set_common_vars],
['Checking OS...', check_os],
['Checking tools...', check_tools],
['Creating folders...', make_tmp_dirs],
['Clearing collisions...', clean_env_vars],
]
try:
for f in init_functions:
try_and_print(
@ -713,5 +736,14 @@ def set_common_vars():
global_vars['TmpDir'] = r'{BinDir}\tmp'.format(
**global_vars)
def set_linux_vars():
result = run_program(['mktemp', '-d'])
global_vars['TmpDir'] = result.stdout.decode().strip()
global_vars['Date'] = time.strftime("%Y-%m-%d")
global_vars['Date-Time'] = time.strftime("%Y-%m-%d_%H%M_%z")
global_vars['Env'] = os.environ.copy()
global_vars['BinDir'] = '/usr/local/bin'
global_vars['LogDir'] = global_vars['TmpDir']
if __name__ == '__main__':
print("This file is not meant to be called directly.")

View file

@ -0,0 +1,65 @@
#!/bin/python3
#
## Wizard Kit: Functions - Network
import os
import sys
# Init
os.chdir(os.path.dirname(os.path.realpath(__file__)))
sys.path.append(os.getcwd())
from functions.common import *
# REGEX
REGEX_VALID_IP = re.compile(
r'(10.\d+.\d+.\d+'
r'|172.(1[6-9]|2\d|3[0-1])'
r'|192.168.\d+.\d+)',
re.IGNORECASE)
def connect_to_network():
"""Connect to network if not already connected."""
net_ifs = psutil.net_if_addrs()
net_ifs = [i[:2] for i in net_ifs.keys()]
# Bail if currently connected
if is_connected():
return
# LAN
if 'en' in net_ifs:
# Reload the tg3/broadcom driver (known fix for some Dell systems)
try_and_print(message='Reloading drivers...', function=reload_tg3)
# WiFi
if not is_connected() and 'wl' in net_ifs:
cmd = [
'nmcli', 'dev', 'wifi',
'connect', WIFI_SSID,
'password', WIFI_PASSWORD]
try_and_print(
message = 'Connecting to {}...'.format(WIFI_SSID),
function = run_program,
cmd = cmd)
def is_connected():
"""Check for a valid private IP."""
devs = psutil.net_if_addrs()
for dev in devs.values():
for family in dev:
if REGEX_VALID_IP.search(family.address):
# Valid IP found
return True
# Else
return False
def reload_tg3():
"""Reload tg3 module as a workaround for some Dell systems."""
run_program(['sudo', 'modprobe', '-r', 'tg3'])
run_program(['sudo', 'modprobe', 'broadcom'])
run_program(['sudo', 'modprobe', 'tg3'])
sleep(5)
if __name__ == '__main__':
print("This file is not meant to be called directly.")

View file

@ -1,6 +1,6 @@
#!/bin/bash
#
## WK HW diagnostics - Launcher
## Wizard Kit: HW Diagnostics - Menu
MODE="$1"
SHOW_MENU="True"

View file

@ -1,6 +1,6 @@
#!/bin/bash
#
## WK HW diagnostics - Audio (Stereo)
## Wizard Kit: HW Diagnostics - Audio
# Unmute and set volume
amixer -q set "Master" 80% unmute

View file

@ -1,6 +1,6 @@
#!/bin/bash
#
## WK HW diagnostics - badblocks
## Wizard Kit: HW Diagnostics - badblocks
function usage {
echo "Usage: $0 log-dir device"

View file

@ -1,6 +1,6 @@
#!/bin/bash
#
## WK HW Diagnostics - Main script
## Wizard Kit: HW Diagnostics - Main script
die () {
echo "$0:" "$@" >&2
@ -8,16 +8,16 @@ die () {
}
# Load settings
if [[ -f "/run/archiso/bootmnt/arch/arch.conf" ]]; then
source "/run/archiso/bootmnt/arch/arch.conf" || \
die "ERROR: failed to load arch.conf (from /run/archiso/bootmnt/arch/)"
if [[ -f "/run/archiso/bootmnt/arch/main.conf" ]]; then
source "/run/archiso/bootmnt/arch/main.conf" || \
die "ERROR: failed to load main.conf (from /run/archiso/bootmnt/arch/)"
else
source "/usr/local/bin/arch.conf" || \
die "ERROR: failed to load arch.conf (from /usr/local/bin/)"
source "/usr/local/bin/main.conf" || \
die "ERROR: failed to load main.conf (from /usr/local/bin/)"
fi
# Get TICKET
## Inital SKIP_UPLOAD value loaded from arch.conf
## Inital SKIP_UPLOAD value loaded from main.conf
SKIP_UPLOAD="${SKIP_UPLOAD}"
TICKET=""
while [[ "$TICKET" == "" ]]; do
@ -37,7 +37,7 @@ while [[ "$TICKET" == "" ]]; do
done
# Init
## Tautologies left to show which settings are coming from arch.conf
## Tautologies left to show which settings are coming from main.conf
DIAG_DATE="$(date "+%F_%H%M")"
DIAG_SERVER_AVAIL="False"
DIAG_SERVER="${DIAG_SERVER}"
@ -234,7 +234,7 @@ esac
if [[ "$TEST_CPU" == "False" ]] && \
[[ "$TEST_SMART" == "False" ]] && \
[[ "$TEST_BADBLOCKS" == "False" ]]; then
echo -e "${YELLOW}Aborting HW diagnostics${CLEAR}"
echo -e "${YELLOW}Aborting HW Diagnostics${CLEAR}"
exit 1
fi

View file

@ -1,6 +1,6 @@
#!/bin/bash
#
## WK HW diagnostics - Network
## Wizard Kit: HW Diagnostics - Network
function test_connection() {
cmd="a"

View file

@ -1,6 +1,6 @@
#!/bin/bash
#
## HW diagnostics - Prime95
## Wizard Kit: HW Diagnostics - Prime95
function usage {
echo "Usage: $0 log-dir"

View file

@ -1,6 +1,6 @@
#!/bin/bash
#
## WK HW diagnostics - Progress
## Wizard Kit: HW Diagnostics - Progress
# Loop forever
while :; do

View file

@ -1,6 +1,6 @@
#!/bin/bash
#
## WK HW diagnostics - Sensors
## Wizard Kit: HW Diagnostics - Sensors
LOG_DIR="$1"

View file

@ -1,8 +1,8 @@
#!/bin/bash
#
## Mount all volumes read-only
## Wizard Kit: Volume mount tool
# Mount all volumes
# Mount all volumes (read only)
echo "Mounting all volumes"
regex="/dev/((h|s)d[a-z]|md)[0-9]+"
for volume in $(inxi -Dopxx | grep -E "$regex" | sed -r "s#.*($regex).*#\1#" | sort); do

View file

@ -1,6 +1,6 @@
#!/bin/bash
#
## Mount NAS backup shares
## Wizard Kit: Backup share mount tool
die () {
echo "$0:" "$@" >&2
@ -8,12 +8,12 @@ die () {
}
# Load settings
if [[ -f "/run/archiso/bootmnt/arch/arch.conf" ]]; then
source "/run/archiso/bootmnt/arch/arch.conf" || \
die "ERROR: failed to load arch.conf (from /run/archiso/bootmnt/arch/)"
if [[ -f "/run/archiso/bootmnt/arch/main.conf" ]]; then
source "/run/archiso/bootmnt/arch/main.conf" || \
die "ERROR: failed to load main.conf (from /run/archiso/bootmnt/arch/)"
else
source "/usr/local/bin/arch.conf" || \
die "ERROR: failed to load arch.conf (from /usr/local/bin/)"
source "/usr/local/bin/main.conf" || \
die "ERROR: failed to load main.conf (from /usr/local/bin/)"
fi
# Connect to a network

View file

@ -1,5 +1,6 @@
#!/bin/bash
#
## Wizard Kit: MS Word content search tool
TMP_FILE="$(mktemp)"
IFS=$'\n'
@ -35,4 +36,4 @@ rm "$TMP_FILE"
if [[ -s "$HOME/msword-matches.txt" ]]; then
echo "Found $(wc -l "$HOME/msword-matches.txt") possible matches"
echo "The results have been saved to $HOME"
fi
fi

View file

@ -1,6 +1,6 @@
#!/bin/bash
#
## Remount volume read-write
## Wizard Kit: Volume remount tool
if ! mount | grep -q "$1"; then
echo "ERROR: Can't remount $1"
@ -10,6 +10,7 @@ fi
DEVICE=$(mount | grep "$1" | cut -d' ' -f1)
# Remount read-write
echo "Remounting: $DEVICE"
udevil umount $DEVICE
if udevil mount $DEVICE; then

View file

@ -1,69 +0,0 @@
#!/bin/bash
#
## Get connected to a network
# 1. Checks if already online; skips if so
# 2. If no wired devices are present then reload kernel modules
# 3. If wireless devices are present, and we're still offline, then connect to WiFi
die () {
echo "$0:" "$@" >&2
exit 1
}
function test_connection() {
# Check for a valid private IP
if ip a | grep -Eq '10.[0-9]+.[0-9]+.[0-9]+'; then
return 0 # Class A
elif ip a | grep -Eq '172.(1[6-9]|2[0-9]|3[0-1]).[0-9]+.[0-9]+'; then
return 0 # Class B
elif ip a | grep -Eq '192.168.[0-9]+.[0-9]+'; then
return 0 # Class C
else
return 1 # Invalid private IP
fi
}
# Load settings
if [[ -f "/run/archiso/bootmnt/arch/wifi.conf" ]]; then
source "/run/archiso/bootmnt/arch/wifi.conf" || \
die "ERROR: failed to load wifi.conf (from /run/archiso/bootmnt/arch/)"
else
source "/usr/local/bin/wifi.conf" || \
die "ERROR: failed to load wifi.conf (from /usr/local/bin/)"
fi
# Init
WIFI_SSID="${WIFI_SSID}"
WIFI_PASSWORD="${WIFI_PASSWORD}"
# Connect to network
if ! test_connection; then
# LAN
if ! ip l | grep -Eq '[0-9]+: +en'; then
## Reload the tg3/broadcom driver (known fix for some Dell systems)
echo "No wired network adapters found; reloading drivers..."
sudo modprobe -r tg3
sudo modprobe broadcom
sudo modprobe tg3
sleep 5s
fi
# WiFi
if ip l | grep -Eq '[0-9]+: +wl'; then
## Skip if we're already connected (i.e. the code above worked)
if ! test_connection; then
echo "Attempting to connect to ${WIFI_SSID}..."
nmcli dev wifi connect "${WIFI_SSID}" password "${WIFI_PASSWORD}"
sleep 5s
fi
fi
fi
# Done
if test_connection; then
exit 0
else
exit 1
fi

View file

@ -1,2 +0,0 @@
# Wizard Kit: Settings - WiFi