From b9948f0daee1f9a6d714c7d93ca07db8ba9a6872 Mon Sep 17 00:00:00 2001 From: Loic Nageleisen Date: Thu, 22 Aug 2013 15:40:05 +0200 Subject: [PATCH] a few scripts --- battery.py | 131 ++++++++++++++++++++++++++ battery.sh | 122 ++++++++++++++++++++++++ com.nullvision.noatime.plist.disabled | 18 ++++ free | 109 +++++++++++++++++++++ keep_en0_alive.sh | 38 ++++++++ lock_screen.sh | 2 + ovpn.sh | 20 ++++ vm_stat | 1 + wol.py | 38 ++++++++ 9 files changed, 479 insertions(+) create mode 100755 battery.py create mode 100755 battery.sh create mode 100644 com.nullvision.noatime.plist.disabled create mode 100755 free create mode 100755 keep_en0_alive.sh create mode 100755 lock_screen.sh create mode 100755 ovpn.sh create mode 120000 vm_stat create mode 100755 wol.py diff --git a/battery.py b/battery.py new file mode 100755 index 0000000..57b5682 --- /dev/null +++ b/battery.py @@ -0,0 +1,131 @@ +#!/usr/bin/env python + +from __future__ import print_function +from __future__ import division + +from subprocess import Popen, PIPE + +def ioreg_battery_info(): + output = Popen(["ioreg", "-r", "-k", "LegacyBatteryInfo", "-w", "0"], stdout=PIPE).communicate()[0] + try: #python3 + return str(output, encoding='utf-8') + except TypeError: #python2 + return output + +def parse_ioreg_dict(output): + return dict( + [ (kw.strip().strip('"'), vw.strip()) + for kw, vw + in [ line.split("=", 1) + for line + in output.split('\n') if line.find('=')>0 + ] + ] + ) + +def is_two_complement_negative(value): + return value > (2**63-1) + +def two_complement(value): + return 2**64 - value + +def fix_negative(value): + if is_two_complement_negative(value): + return -two_complement(value) + else: + return value + +def ioreg_battery_dict(): + output = ioreg_battery_info() + return parse_ioreg_dict(output) + + +def fix_integer(string): + return fix_negative(int(string)) + +def format_time(string): + minutes = int(string) + if minutes == 65535: + return None + else: + return "%s:%s" % (minutes//60, minutes%60) + +def percentage(ratio): + return "%s%%" % (int(ratio*100)) + +humanize_index = { + "TimeRemaining": format_time, + "AvgTimeToEmpty": format_time, + "AvgTimeToFull": format_time, + "InstantTimeToEmpty": format_time, + "FullToEmptyTime": format_time, + "WearRatio": percentage, + "ChargeRatio": percentage, + } + +def humanize_data(k, v): + if k in humanize_index: + return humanize_index[k](v) + else: + return v + +def wear_ratio(info): + return int(info["MaxCapacity"]) / int(info["DesignCapacity"]) + +def charge_ratio(info): + return int(info["CurrentCapacity"]) / int(info["MaxCapacity"]) + +def full_to_empty_time(info): + if get_data(info, "Amperage") < 0: + return -int(info["MaxCapacity"])*60 / get_data(info, "Amperage") + else: + return 65535 + +synthetize_index = { + "Amperage": lambda i: fix_integer(i["Amperage"]), + "InstantAmperage": lambda i: fix_integer(i["InstantAmperage"]), + "WearRatio": wear_ratio, + "ChargeRatio": charge_ratio, + "FullToEmptyTime": full_to_empty_time, + } + +def synthetize_data(battery_info, k): + if k in synthetize_index: + return synthetize_index[k](battery_info) + +def get_data(battery_info, k): + if k in synthetize_index: + return synthetize_data(battery_info, k) + elif k in battery_info: + return battery_info[k] + else: + raise KeyError("%s" % k) + +keys_to_show = [ + "Temperature", + "CycleCount", + #"DesignCycleCount9C", + "DesignCapacity", + "MaxCapacity", + "WearRatio", + "CurrentCapacity", + "ChargeRatio", + "Voltage", + "Amperage", + "InstantAmperage", + "InstantTimeToEmpty", + "TimeRemaining", + "AvgTimeToEmpty", + "AvgTimeToFull", + "FullToEmptyTime", + ] + +def print_key_value(k, v): + if v is not None: + print("%s = %s" % (k, v)) + +battery_info = ioreg_battery_dict() + +for k in keys_to_show: + print_key_value(k, humanize_data(k, get_data(battery_info, k))) + diff --git a/battery.sh b/battery.sh new file mode 100755 index 0000000..c0b8f8f --- /dev/null +++ b/battery.sh @@ -0,0 +1,122 @@ +#!/bin/bash + +legacyinfo=$(ioreg -l -w 2048 | grep 'LegacyBatteryInfo') + +get_attribute() +{ + echo $legacyinfo | sed "s/.*\"$@\"=\([^,}][^,}]*\)[,}].*/\1/" +} + +is_negative() +{ + [ $(echo "$@ > (2^63-1)" | bc) == "1" ] +} + +two_complement() +{ + echo "2^64 - $@" | bc +} + +fix_negative() +{ + # is the value negative? + if is_negative "$@"; then + # compute two's complement + echo "-$(two_complement "$@")" + else + echo "$@" + fi +} + +get_integer_attribute() +{ + fix_negative "$(get_attribute "$@")" +} + +amperage() +{ + get_integer_attribute 'Amperage' +} + +full_capacity() +{ + get_integer_attribute 'Capacity' +} + +current_capacity() +{ + get_integer_attribute 'Current' +} + +voltage() +{ + get_integer_attribute 'Voltage' +} + +cycle_count() +{ + get_integer_attribute 'Cycle Count' +} + +discharge_time() +{ + hours=$(echo "-$(current_capacity) / $(amperage)" | bc) + minutes=$(echo "-( $(current_capacity) % $(amperage) ) * 60 / $(amperage)" | bc) + echo "$hours:$minutes" +} + +full_discharge_time() +{ + hours=$(echo "-$(full_capacity) / $(amperage)" | bc) + minutes=$(echo "-( $(full_capacity) % $(amperage) ) * 60 / $(amperage)" | bc) + echo "$hours:$minutes" +} + +charge_time() +{ + hours=$(echo "( $(full_capacity) - $(current_capacity) ) / $(amperage)" | bc) + minutes=$(echo "( ( $(full_capacity) - $(current_capacity) ) % $(amperage) ) * 60 / $(amperage)" | bc) + echo "$hours:$minutes" +} + +full_charge_time() +{ + hours=$(echo "$(full_capacity) / $(amperage)" | bc) + minutes=$(echo "( $(full_capacity) % $(amperage) ) * 60 / $(amperage)" | bc) + echo "$hours:$minutes" +} + +remaining_time() +{ + if [ $(echo "$(amperage) < 0" | bc) == "1" ]; then + discharge_time + elif [ $(echo "$(amperage) > 0" | bc) == "1" ]; then + charge_time + else + echo "0:00" + fi +} + +full_time() +{ + if [ $(echo "$(amperage) < 0" | bc) == "1" ]; then + full_discharge_time + elif [ $(echo "$(amperage) > 0" | bc) == "1" ]; then + full_charge_time + else + echo "0:00" + fi +} + +charge_ratio() +{ + echo "$(echo "( $(current_capacity) * 100 / $(full_capacity) )" | bc)%" +} + +attributes=('amperage' 'full_capacity' 'current_capacity' 'voltage' 'cycle_count' 'remaining_time' 'charge_ratio' 'full_time') + +for ((i=0;i<${#attributes[*]};i++)); do + data=$(${attributes[$i]}) + echo "${attributes[$i]}: $data" +done + diff --git a/com.nullvision.noatime.plist.disabled b/com.nullvision.noatime.plist.disabled new file mode 100644 index 0000000..50436f4 --- /dev/null +++ b/com.nullvision.noatime.plist.disabled @@ -0,0 +1,18 @@ + + + + + Label + com.nullvision.noatime + ProgramArguments + + mount + -vuwo + noatime + / + + RunAtLoad + + + diff --git a/free b/free new file mode 100755 index 0000000..653844b --- /dev/null +++ b/free @@ -0,0 +1,109 @@ +#!/usr/bin/perl + +use strict; +use warnings; + +use File::Basename; +use List::MoreUtils qw(firstidx); + +my $VM_STAT = "/usr/bin/vm_stat"; + +my $vm_stat = 0; +my $human = 0; # TODO: -h +my $scale; +my $unit = 1024; # TODO: --si +my $page_size; +my %mem = ( ); + +if (basename($0) eq "vm_stat") { + $vm_stat = 1; +} + +if (@ARGV > 0) { + # TODO: use Getopt::Long + # TODO: add --help, --version + # TODO: add --old, --total, --lohi, --seconds, --count + # TODO: add --bytes, --kilo, --mega, --giga + my @params = qw(-b -k -m -g --tera); + my $idx = firstidx { $_ eq $ARGV[0] } @params; + if ($idx == -1) { $idx = 1 }; + $scale = $unit ** $idx; +} + +if ($vm_stat && !defined $scale) { + exec $VM_STAT or die; +} + +unless ($scale) { + $scale = $unit; +} + +open(PIPE, "-|", $VM_STAT); +my %vm = ( ); + +while() { + /page size of (\d+)/ and $page_size = $1; + + if ($vm_stat) { + /Pages\s+([^:]+)[^\d]+(\d+)/ and printf("%-16s % 16d\n", "$1:", $2 * $page_size / $scale); + } else { + my @keys = ( "free", "active", "inactive", "speculative", "wired down" ); + foreach my $key (@keys) { + /Pages $key[^\d]+(\d+)/ and $vm{$key} = $1 * $page_size; + } + + } +} + +close(PIPE); + +unless ($vm_stat) { + `sysctl hw.memsize` =~ /(\d+)/ and $mem{total} = $1; + $mem{free} = $vm{free} + $vm{speculative}; + $mem{used} = $vm{'wired down'} + $vm{active} + $vm{inactive}; + $mem{shared} = 0; + $mem{buffers} = 0; + $mem{cached} = $vm{inactive}; + $mem{no_cache_used} = $vm{'wired down'} + $vm{active}; + $mem{no_cache_free} = $mem{total} - $mem{no_cache_used}; + + # alternative for total + #while (my $swapfile = ) { + # $mem{swap_total} += (stat($swapfile))[7]; + #} + + foreach my $key ( qw(total used free) ) { + if (`sysctl vm.swapusage` =~ /$key = ([0-9.]+)/) { + $mem{"swap_$key"} = $1 * 1048576; + } + } + + foreach my $key ( keys %mem ) { + $mem{$key} /= $scale; + } + + my @keys = qw(total used free shared buffers cached); + printf("%7s", ""); + foreach my $key (@keys) { + printf("%11s", $key); + } + print("\n"); + + printf("%7s", "Mem:"); + foreach my $key (@keys) { + printf("%11d", $mem{$key}); + } + print("\n"); + + print("+/- buffers/cache:"); + printf("%11d", $mem{no_cache_used}); + printf("%11d", $mem{no_cache_free}); + print("\n"); + + printf("%7s", "Swap:"); + printf("%11d", $mem{swap_total}); + printf("%11d", $mem{swap_used}); + printf("%11d", $mem{swap_free}); + print("\n"); + +} diff --git a/keep_en0_alive.sh b/keep_en0_alive.sh new file mode 100755 index 0000000..17e9045 --- /dev/null +++ b/keep_en0_alive.sh @@ -0,0 +1,38 @@ +#!/bin/bash + +[ "$UID" == 0 ] || exec sudo $0 + +TARGET='10.0.100.254' +TIMEOUT='5' + +kext='/System/Library/Extensions/BCM5722D.kext' + +std_date() { + echo -n $(date +'%Y-%m-%d %H:%M:%S') +} + +is_up() { + ping -q -t $TIMEOUT -o -r $TARGET > /dev/null +} + +wait_for_up() { + ping -q -o -r $TARGET > /dev/null +} + +restart_iface() { + echo "syncing" + sync + echo "unloading kext" + kextunload $kext + echo "loading kext" + kextload $kext +} + +while wait_for_up; do + while is_up; do + sleep 1 + done + + echo "en0 down @ `std_date`" + restart_iface +done diff --git a/lock_screen.sh b/lock_screen.sh new file mode 100755 index 0000000..f4139ec --- /dev/null +++ b/lock_screen.sh @@ -0,0 +1,2 @@ +#!/bin/sh +open -a /System/Library/Frameworks/ScreenSaver.framework/Versions/A/Resources/ScreenSaverEngine.app diff --git a/ovpn.sh b/ovpn.sh new file mode 100755 index 0000000..90c9cfe --- /dev/null +++ b/ovpn.sh @@ -0,0 +1,20 @@ +#!/bin/sh + +case "$1" in + home) + cd ~/.openvpn/adhoc + sudo openvpn --config udp.conf --daemon + ;; + adhoc) + cd ~/.openvpn/adhoc + sudo openvpn --config lnageleisen.conf --auth-user-pass up --daemon + ;; + stop) + sudo killall openvpn + ;; + *) + echo "usage: "$(basename $0) $(ls ~/.openvpn|tr "\n" '|')"stop" + exit 1 + ;; +esac + diff --git a/vm_stat b/vm_stat new file mode 120000 index 0000000..d5ff057 --- /dev/null +++ b/vm_stat @@ -0,0 +1 @@ +free \ No newline at end of file diff --git a/wol.py b/wol.py new file mode 100755 index 0000000..ffcf9d0 --- /dev/null +++ b/wol.py @@ -0,0 +1,38 @@ +#!/usr/bin/python +from __future__ import division, print_function, unicode_literals + +from socket import socket, AF_INET, SOCK_DGRAM, SOL_SOCKET, SO_BROADCAST + + +def interact(): + import code + code.InteractiveConsole(locals=globals()).interact() + + +def mac_to_bytes(mac): + try: # py2 + return b''.join(chr(int(b, 16)) for b in mac.split(':')) + except TypeError: # py3 + return bytes([int(b, 16) for b in mac.split(':')]) + + +def bytes_to_mac(bytes): + try: # py3 + return ':'.join("%02X" % b for b in bytes).lower() + except TypeError: # py2 + return ':'.join("%02X" % ord(b) for b in bytes).lower() + + +mac = "78:2b:cb:93:fc:8e" +destination = "255.255.255.255" +port = 9 + +data = b'\xFF' * 6 + mac_to_bytes(mac) * 16 + +print("Sending magic packet to %s:%s with %s" % + (destination, port, bytes_to_mac(mac_to_bytes(mac)))) + +sock = socket(AF_INET, SOCK_DGRAM) +sock.setsockopt(SOL_SOCKET, SO_BROADCAST, 1) +sock.sendto(data, (destination, port)) +sock.close()