You are not logged in.

#751 2009-12-28 11:09:58

Barrucadu
Member
From: York, England
Registered: 2008-03-30
Posts: 1,158
Website

Re: Post your handy self made command line utilities

Thanks, I thought I used to know a better way to do that sort of thing…

#!/bin/zsh

function showhelp()
{
    echo "fix.sh - script for attempting to fix completely hosed Arch installations."
    echo
    echo "-m     Fix the pacman mirrorlist"
    echo "-p     Manually reinstall pacman"
    echo "-u     Update system"
    echo "-i     Reinstall all packages"
    echo "-a     Reinstall all foreign packages (using yaourt)"
    echo "-s     Sanity-check package lists before reinstalling using \$EDITOR (no effect if neither -i or -a are given)"
    echo "-o     Run pacman-optimize after reinstallations (no effect if neither -i or -a are given)"
    echo
    echo "Warning: All package installations are forced."
    echo "Note:    Arguments are processed in the order displayed above."
}

function fixmirrors()
{
    echo "Fixing pacman mirrorlist..."

    if [[ -d /etc/pacman.d ]]; then
        sudo rm -f /etc/pacman.d/mirrorlist
    else
        sudo mkdir -p /etc/pacman.d/
    fi

    sudo echo "Server = ftp://ftp.archlinux.org/\$repo/os/`uname -m`" > /etc/pacman.d/mirrorlist
}

function fixpacman()
{
    echo "Manually reinstalling pacman..."

    wget ftp://ftp.archlinux.org/core/os/`uname -m`/core.db.tar.gz -O /tmp/core.db.tar.gz
    pacmanver=`tar tzf /tmp/core.db.tar.gz | grep pacman | head -n1 | sed "s/\///"`

    wget ftp://ftp.archlinux.org/core/os/`uname -m`/$pacmanver-`uname -m`.pkg.tar.gz -O /tmp/pacman.pkg.tar.gz
    sudo tar xvfz /tmp/pacman.pkg.tar.gz /
    sudo pacman -Sy pacman
}

function updatesystem()
{
    sudo pacman -Syuf
}

function repackages()
{
    echo "Generating package lists..."
    pacman -Qqe  | sort > /tmp/packages-qqe
    pacman -Qqem | sort > /tmp/packages-qqem
    pacman -Qqd  | sort > /tmp/packages-qqd
    pacman -Qqdm | sort > /tmp/packages-qqdm
    
    comm -23 /tmp/packages-qqe /tmp/packages-qqem > /tmp/packages1
    comm -23 /tmp/packages-qqd /tmp/packages-qqdm > /tmp/packages2
    
    mv /tmp/packages1 /tmp/packages-qqe
    mv /tmp/packages2 /tmp/packages-qqd
    
    if $3; then
        EDITOR=`[[ $EDITOR == "" ]] && echo "vim" || echo $EDITOR` # As much as I dislike it, vim *is* the one editor guaranteed to be everywhere...
    
        $EDITOR /tmp/packages-qqe
        $EDITOR /tmp/packages-qqd
        $EDITOR /tmp/packages-qqem
        $EDITOR /tmp/packages-qqdm
    fi
    
    sudo pacman -Syy
    
    if $1; then
        sudo pacman -Sf `cat /tmp/packages-qqe`
        sudo pacman -Sf --asdeps `cat /tmp/packages-qqd`
    fi
    
    if $2; then
        yaourt -Sf `cat /tmp/packages-qqem`
        yaourt -Sf --asdeps `cat /tmp/packages-qqdm`
    fi

    if $4; then
        sudo pacman-optimize
    fi
}

installpackages=false
installaur=false
sanitycheck=false
optimize=false

for arg in "${*[@]}"; do
    case $arg in
        "-h")
            showhelp;;
        "-m")
            fixmirrors;;
        "-p")
            fixpacman;;
        "-u")
            updatesystem;;
        "-i")
            installpackages=true;;
        "-a")
            installaur=true;;
        "-s")
            sanitycheck=true;;
        "-o")
            optimize=true;;
    esac
done

if $installpackages || $installaur; then
    repackages $installpackages $installaur $sanitycheck $optimize
fi

Last edited by Barrucadu (2009-12-28 11:11:50)

Offline

#752 2009-12-28 22:06:50

markp1989
Member
Registered: 2008-10-05
Posts: 431

Re: Post your handy self made command line utilities

this checkes my log file for flexget.  and displays any new downloads in dzen2

#!/bin/bash
FG='#ffffff'
BG='#000000'

while true ; do
showsadded=`/usr/bin/tail -n 4 /home/mark/showsadded.txt  | cut -f1 -d'[' | cut$
    printf "%s\n" "$showsadded "
    sleep 3600
done | dzen2 -e '' -y '695' -h '20' -sa 'r'  -ta c -fg $FG -bg $BG

and this one checks rss feeds every hour  and puts the latest 4 feeds in dzen2 bar



 
#!/bin/bash 
FG='#ffffff'
BG='#000000'
while true ; do
url=http://www.harrowtimes.co.uk/news/rss/                             #URl of RSS Feed
lines=4                                           #Number of headlines
titlenum=2
newsrss=`curl -A "Mozilla/5.0" -s --connect-timeout 30 $url | grep -io "<title>[^<]*"| sed -e 's/<[^>]*>//'| head -n $(($lines + $titlenum)) | tail -n $(($lines))|tr '\n' ':'`
    printf "%s\n" "$newsrss"
    sleep 3600 
done | dzen2 -e '' -y '885' -h '15' -sa 'r'  -ta c -fg $FG -bg $BG -fn $FONT

Last edited by markp1989 (2009-12-29 00:24:31)


Desktop: E8400@4ghz - DFI Lanparty JR P45-T2RS - 4gb ddr2 800 - 30gb OCZ Vertex - Geforce 8800 GTS - 2*19" LCD
Server/Media Zotac GeForce 9300-ITX I-E - E5200 - 4gb Ram - 2* ecogreen F2 1.5tb - 1* wd green 500gb - PicoPSU 150xt - rtorrent - xbmc - ipazzport remote - 42" LCD

Offline

#753 2009-12-30 02:02:36

Barrucadu
Member
From: York, England
Registered: 2008-03-30
Posts: 1,158
Website

Re: Post your handy self made command line utilities

A little script I just wrote to run in cron hourly to start/stop daemons. I could add the start/stop commands to my crontab for everything, but I prefer having one start/stop script and a clear config file to edit.
I haven't actually tested this yet, but I think it'll work tongue

/etc/cron.hourly/autodaemons.sh

#!/bin/zsh

# Start/stop daemons at certain times.

hour=`date +%H`
conf=/etc/autodaemons.conf

grep "^$hour" $conf | sed "s/^$hour//" > /tmp/actions

while read line; do
    if echo $line | grep -q "start$"; then
        daemon=`echo $line | sed "s/start$//" | tr -d "[:blank:]"`
        echo "Starting $daemon ($hour)"
        /etc/rc.d/$daemon start
    elif echo $line | grep -q "stop$"; then
        daemon=`echo $line | sed "s/stop$//" | tr -d "[:blank:]"`
        echo "Stopping $daemon ($hour)"
        /etc/rc.d/$daemon stop
    else
        echo "Cannot understand $line" 1>&2
    fi
done < /tmp/actions

rm /tmp/actions

/etc/autodaemons.conf

# Autodaemon config file.
# See /etc/cron.hourly/autodaemons.sh

# Hour    Daemon    Action

# Taking advantage of Karoo free bandwidth:
00 rtorrent start
00 fttps    start

08 rtorrent stop
08 fttps    stop

Last edited by Barrucadu (2009-12-30 02:15:06)

Offline

#754 2009-12-30 02:30:23

lolilolicon
Member
Registered: 2009-03-05
Posts: 1,676

Re: Post your handy self made command line utilities

Nice idea, Barrucadu.

My thought is, crontab has a nice time/frequency syntax already, why not take advantage of that?
The crontab:

0 0 * * * script start rtorrent fttps
0 8 * * * script stop rtorrent fttps

The script:

#!/bin/sh
action=$1; shift
for daemon in "$@"; do
  /etc/rc.d/${daemon} ${action}
done
#You may want some sanity check.

Benefits:
1. You don't actually need an extra config file.
2. You don't call the script every hour with 22 of them doing nothing.


This silver ladybug at line 28...

Offline

#755 2009-12-30 09:35:24

Ashren
Member
From: Denmark
Registered: 2007-06-13
Posts: 1,221
Website

Re: Post your handy self made command line utilities

A really simple script to mail the ipadress of a headless vboxserver on DHCP:

#!/bin/bash

# A small script to check ip for headless server on DHCP and mail it me.

IF=`ifconfig eth0 | awk '/inet addr:/ {print $2}'`

echo -e "To: my@email \nFrom: mybox \nSubject: ipadress myserver\n\n$IF" > /tmp/mail.txt

ssmtp my@email < /tmp/mail.txt

I have placed the script in /etc/rc.local on the server so it will send an email to me as soon as the server is up. Pretty nice thing to have when using a headless server on different locations using DHCP.

Last edited by Ashren (2009-12-30 09:35:48)

Offline

#756 2009-12-30 10:11:47

lolilolicon
Member
Registered: 2009-03-05
Posts: 1,676

Re: Post your handy self made command line utilities

@Ashren, you probably could have written instead:

#!/bin/bash
ssmtp my@email < <(ifconfig eth0 | awk '/inet addr:/ {print "To: my@email \nFrom: mybox \nSubject: ipadress myserver\n\n" $2}')

Last edited by lolilolicon (2009-12-30 10:31:51)


This silver ladybug at line 28...

Offline

#757 2009-12-30 15:38:04

Ashren
Member
From: Denmark
Registered: 2007-06-13
Posts: 1,221
Website

Re: Post your handy self made command line utilities

lolilolicon: Thanks for the oneliner.

Offline

#758 2009-12-30 20:15:24

bobdob
Member
Registered: 2008-06-13
Posts: 138

Re: Post your handy self made command line utilities

Here's a script I made to update software stacks. I use it to update my git/svn pkgs in the right order, like building x264 before ffmpeg before mplayer.
It not overly robust, but it gets the job done.

#!/bin/bash
#

# non-root user for makepkg
user=matt
# root dir of stacks
stackdir="/media/disk/aur"
# prefix and suffix of stacks base directory
dirprefix=""
dirsuffix="-stack"
# colors
COLOR_R="\e[1;31m"
COLOR_G="\e[1;32m"
COLOR_B="\e[1;34m"
COLOR_Y="\e[1;33m"
COLOR_W="\e[1;37m"
COLOR_M="\e[1;35m"
COLOR_N="\e[0m"

# stacks
stacks=('mplayer' 'mpd' 'xorg')
stackmplayer=('x264-git' 'ffmpeg-svn' 'libdvdread-svn' 'libdvdnav-svn' 'mplayer-svn')
stackmpd=('mpd-git' 'libmpdclient-git' 'mpc-git' 'ncmpc-git')
stackxorg=('libdrm-git' 'glproto-git' 'dri2proto-git'  'mesa-git ati-dri-git libgl-git' 'xf86-video-ati-git')

# scrip variables
declare -a currentstack=
newest_pkg=
pkg_name=
# number of pkgs in split pkg
no_pkgs=

usage () {
    echo "stackman usage:"
    echo "    stackman [options] [stack]"
    echo ""
    echo "    -h|--help    display this help message"
    echo "    -c|--check   check stack directories exist"
    echo "    -u|--update  update stack"
    exit 0
}

# print error message $1: message, $2: indent
errormsg () {
    echo -e "$2${COLOR_R}Error${COLOR_N}: $1"
    exit 1
}

# print pass message $1: message, $2: indent
passmsg () {
    echo -e "$2${COLOR_G}Pass${COLOR_N}: $1"
}

# print status message $1: message, $2: indent
statusmsg () {
    echo -e "$2${COLOR_G}=>${COLOR_N} $1"
}

# get newest pkg of pkg_name in directory
get_newest_pkg () {
    newest_pkg=$(ls -1 ${pkg_name}*.pkg.tar.gz | tail -n 1)
}

# update pkg using newest_pkg
update_pkg () {
    pacman -U ${newest_pkg}
    if [ $? == 0 ]; then
        passmsg "${pkg_name} updated"
    else
        errormsg "${pkg_name} failed to update"
    fi
}

# make pkg
make_pkg () {
    # execute makepkg as non root user
    statusmsg "Building ${pkg_name}"
    su -c "makepkg -s" ${user}
#    if [ $? == "0" ]; then
#        passmsg "${pkg_name} built" "  "
#    else
#        errormsg "${pkg_name} failed to build" "  "
#        exit 1
#    fi
}

# cheack all directories of current stack exist
check_stack () {
    set_stack $1
    statusmsg "Checking directory for current stack:"
    for i in $(seq 0 $((${#currentstack[@]} - 1)))
    do
        if [ $(echo ${currentstack[$i]} | awk '{print NF}') = "1" ]; then
            dir=${currentstack[$i]}
        else
            dir=$(echo ${currentstack[$i]} | awk '{print $1}')
        fi
        if [ -d $dir ]; then
            passmsg "${currentstack[$i]} found" "  "
        else
            errormsg "${currentstack[$i]} not found" "  "
        fi
    done
    statusmsg "Stack complete"
}

# set current stack $1: stack
set_stack () {
    statusmsg "Setting current stack:"

    case $1 in
        mplayer)  currentstack=("${stackmplayer[@]}")  ;;
        mpd)      currentstack=("${stackmpd[@]}")      ;;
        xorg)     currentstack=("${stackxorg[@]}")     ;;
        *)        errormsg "Stack not found"; exit 1   ;;
    esac

    statusmsg "Stack set to $1"
}

# update all pkgs in stack
update_stack () {
    # check script is running as root
    check_id
    # set stack and check directories exist
    set_stack $1
    cd ${stackdir}/${dirprefix}${1}${dirsuffix}/ || errormsg "Directory doesn't exist..."
    check_stack $1
    # start update
    statusmsg "Updating stack in 5 seconds..."
    statusmsg "Press C^c to exit"
    sleep 5

    for i in $(seq 0 $((${#currentstack[@]} - 1)))
    do
        # determine if pkg is a split pkg
        no_pkgs=$(echo ${currentstack[$i]} | awk '{print NF}')
        # if not a split pkg
        if [ $no_pkgs = "1" ]; then
            # make and install pkg
            pkg_name=${currentstack[$i]}
            cd ${pkg_name}
            make_pkg
            get_newest_pkg
            update_pkg
            cd ..
        # if a split pkg
        else
            # make base pkg
            pkg_name=$(echo ${currentstack[$i]} | awk '{print $1}')
            cd ${pkg_name}
            make_pkg
            for j in $(seq 1 ${no_pkg})
            do
                # install chosen pkgs
                pkg_name=$(echo ${currentstack[$i]} | awk '{print $j}')
                get_newest_pkg
                update_pkg
            done
            cd ..
        fi
    done
    statusmsg "Stack updated."
}

# check user id
check_id () {
    statusmsg "Checking user id..."
    if [ $(id -u) != "0" ]; then
        errormsg "You must be root to run this!"
    else
        passmsg "Running as root"
    fi
}

### Start ###

case $1 in
    -c|--check)    check_stack $2  ;;
    -u|--update)   update_stack $2 ;;
    -h|--help|*)   usage           ;;
esac

Offline

#759 2009-12-31 12:59:08

upsidaisium
Member
From: Vietnam
Registered: 2006-09-16
Posts: 263
Website

Re: Post your handy self made command line utilities

i'm always browser-hopping, it seems.. so i've bound this script to alt+w in wmii so i can choose my browser and the supply a URL through dmenu.

#!/bin/sh

BROWSER=`cat $HOME/.browsers | dmenu`
if [ $BROWSER == "w3m" -o $BROWSER == 'elinks' ]
then
    BROWSER="xterm -e $BROWSER"
fi
URL=`echo "" | dmenu`
eval "$BROWSER $URL"

(.browsers is just a new-line serparated list of browsers)


I've seen young people waste their time reading books about sensitive vampires. It's kinda sad. But you say it's not the end of the world... Well, maybe it is!

Offline

#760 2009-12-31 22:06:39

munkyeetr
Member
From: Merritt, BC
Registered: 2008-08-07
Posts: 83

Re: Post your handy self made command line utilities

contoggle - A BASH script to automate running and display of conky configuration files

I wanted to create a way to toggle conky on/off, as well as automate the display of different conky configuration files. So I wrote 'contoggle' and set up keyboard hotkeys to call the functions.

SYNTAX:
     contoggle on          Start conky (loads the last used config file)
     contoggle off          Kill conky
     contoggle toggle     Toggle conky on/off
     contoggle next       Load the next config file in $MODES array
     contoggle prev       Load the previous config file in $MODES array

USAGE NOTES:
     1) All conky config files handled by this script need to have the naming convention .conky_<name>
     2) The $CONKYDIR variable needs to be set to the directory where you store your configuration files for conky.
     3) Populate the $MODES array with each <name> you appended to the config files. Example: If your config file is named '.conky_systeminfo', you add "systeminfo" to the array.

BUGS, WARNINGS and HELP:
     1) I just finished the script this morning, so haven't had much time to play around with it. It seems to work quite well, but I have had a couple instances where calling 'next' and 'prev' got stuck toggling between two config files instead of the seven I have listed in my $MODES array. I also had the contoggle script and several of the config files open for editing at the time, so that may have been the cause. Now that I think about it, it hasn't happened since I stopped editing.
     2) If you do play with this, please keep an eye out for that issue and any other anomalies you come across. As always, Use at your own risk!
     3) If you find any bugs or make improvements to the script, please send me a message so I can check it out.

OTHER:
     This script was somewhat thrown together, so there are probably a thousand improvements that could be made to the code. Please feel free to message me or post here any improvements that can be made. Please be specific when making suggestions (Don't say: "You should do it this way" Say: "You should do it this way because..." Don't be shy.

#!/bin/bash

# CONKYDIR is the directory that holds conky configuration files
#    used by this script
CONKYDIR="/home/munky/";

# MODES is a list of different conky configurations
# EXAMPLE: MODES=( "network" "system" ) will toggle conky files
#     with the naming scheme $CONKYDIR/.conky_network and $CONKYDIR/.conky_system
MODES=( "network" "disks" "audacious" "power" "sysinfo" "cpuinfo" "meminfo" )

# MODE_LAST is the last mode that was assigned by this script
#    It will also be the default conky file loaded if you first start
#    conky through this script with the 'on' argument
MODE_LAST=3;

# Return the next mode index
function Next() {
    if [ ${1} == $((${#MODES[@]}-1)) ]; then
    # if current is the last mode, next will be 0
        next=0;
    else
    # else increment
        next=$(($1+1));
    fi

    return ${next}
}

# Return the previous mode index
function Prev() {
    if [ ${1} == 0 ]; then
    # if current is the first mode, next will be last
        prev=$((${#MODES[@]}-1));
    else
    # else decrement
        prev=$(($1-1));
    fi

    return ${prev}
}

# Start conky with the passed config file
function On() {
    conky -c ${CONKYDIR}.conky_${1} &
}

# Kill all running instances of conky
function Off() {
    killall conky 1> /dev/null
}

# Toggle conky on/off
function Toggle() {
# check if any instances of conky are running
    running=$(ps -C conky | grep -c conky);
# if conky is running
    if [ ${running} -gt 0 ]; then
    # kill it
        Off
    else
    # else start it, using last used mode
        On ${MODES[${MODE_LAST}]};
    fi
}

# Return the currently running mode
function GetCurrentMode() {
# check which mode is running    
    mode=$(ps x -C conky | grep ".conky_" | cut -f2 -d "_")
    counter=0
# cycle through available modes    
    for i in ${MODES[@]};
    do
    # test if this is the current mode 
        if [[ "${i}" == "${mode}" ]]; then
        # if it is, return
            return ${counter};
            break;
        else
        # if it isn't, increment
            counter=$[$counter+1]
        fi
    done
}

function SaveMode() {
# save the new mode as MODE_LAST
    sed -i "0,/MODE_LAST=.*/s//MODE_LAST=${1};/" ${2};
}

# This is where the script starts running
# and parses the passed argument
case ${1} in
    'on')
        On ${MODES[${MODE_LAST}]} ;;
    'off')
        Off ;;
    'toggle')
        Toggle ;;
    'next')
        GetCurrentMode
        Next $?
        next=$?
        Off
        On ${MODES[${next}]} 
        SaveMode ${next} ${0} ;;
    'prev')
        GetCurrentMode
        Prev $?
        prev=$?
        Off
        On ${MODES[${prev}]} 
        SaveMode ${prev} ${0} ;;
    *) echo "Unknown argument '${1}'" ;;
esac

Thanks in advance for any input you have, and hopefully someone will find this useful.
Munky


If the advice you're given in this forum solves your issue, please mark the post as [SOLVED] in consideration to others.

"More than any time in history mankind faces a crossroads. One path leads to despair and utter hopelessness, the other to total extinction.
Let us pray that we have the wisdom to choose correctly." -- Woody Allen

Offline

#761 2010-01-03 16:21:04

brisbin33
Member
From: boston, ma
Registered: 2008-07-24
Posts: 1,796
Website

Re: Post your handy self made command line utilities

so i've been using a rule from our udev wiki to automount my usb drives under /media and it's great.  i ran into an issue while partitionaing a drive, and decided i needed a quick/easy way to turn this feature on and off.  by removing or restoring this file under /etc/udev/rules.d, i've effectively achieved that, so why not script it? 

pass 'on', 'off', or nothing to just see the current state.

here you are:

#!/bin/bash
#
# pbrisbin 2009
#
# http://pbrisbin.com:8080/bin/automount
#
# just moves a rules file about to change udev behavior regarding
# the automounting of usb devices. 
#
# see http://wiki.archlinux.org/index.php/Udev for details.
#
#   exit statuses
#     0    success
#     1    improper usage
#     2    already on
#     3    already off
#     *    unknown error
#
###

# if this file's present, automounting is 'on'
FILE='/etc/udev/rules.d/11-media-by-label-auto-mount.rules'

# functions
message() {
  echo "usage: automount [on|off]"
  echo
  exit 1
}

# note: you should adjust the first KERNEL line to skip your persistent drives
write_file() {
  cat > "$FILE" << EOF
KERNEL!="sd[c-z][0-9]", GOTO="media_by_label_auto_mount_end"

# Global mount options
ACTION=="add", ENV{mount_options}="relatime,users"

# Filesystem specific options
ACTION=="add", PROGRAM=="/lib/initcpio/udev/vol_id -t %N", RESULT=="vfat|ntfs", ENV{mount_options}="\$env{mount_options},utf8,gid=100,umask=002"

ACTION=="add", PROGRAM=="/lib/initcpio/udev/vol_id --label %N", ENV{dir_name}="%c"
ACTION=="add", PROGRAM!="/lib/initcpio/udev/vol_id --label %N", ENV{dir_name}="usbhd-%k"
ACTION=="add", RUN+="/bin/mkdir -p /media/%E{dir_name}", RUN+="/bin/mount -o \$env{mount_options} /dev/%k /media/%E{dir_name}"
ACTION=="remove", ENV{dir_name}=="?*", RUN+="/bin/umount -l /media/%E{dir_name}", RUN+="/bin/rmdir /media/%E{dir_name}"
LABEL="media_by_label_auto_mount_end"
EOF
}

turn_on() {
  [ -f "$FILE" ] && exit 2
  write_file
}

turn_off() {
  [ -f "$FILE" ] || exit 3
  rm "$FILE"
}

check_state() {
  [ -f "$FILE" ] && echo "on" || echo "off"
}

# main
[ -z "$1" ] && check_state

# must be root to change things
[ $(id -u) -ne 0 ] && exit 1

# args are on|off only
case $1 in
  on)  turn_on  ;;
  off) turn_off ;;
  *)   message  ;;
esac

Offline

#762 2010-01-09 11:50:25

Peasantoid
Member
Registered: 2009-04-26
Posts: 928
Website

Re: Post your handy self made command line utilities

Tiny Python script to xor-'encrypt' a file so as to hide it from casual snooping. Hardly worth mentioning, really:

#!/usr/bin/env python
import sys
with open(sys.argv[1], 'rb') as f:
  data = ''.join(chr(ord(c) ^ 64) for c in f.read())
with open(sys.argv[1], 'wb') as f:
  f.write(data)

Any value can be substituted for 64.

Last edited by Peasantoid (2010-01-09 12:02:06)

Offline

#763 2010-01-09 22:13:43

vkumar
Member
Registered: 2008-10-06
Posts: 166

Re: Post your handy self made command line utilities

#!/bin/sh
aplay /usr/share/sounds/error.wav &>/dev/null

I like to append this to commands that will take a long time to run. It plays a little "ding" to let me know the job is done.


div curl F = 0

Offline

#764 2010-01-09 22:30:41

ludovico
Member
From: Oslo, Norway
Registered: 2008-08-24
Posts: 75

Re: Post your handy self made command line utilities

@vkumar: thanks, great idea! wink


Sin? What's all this about sin?

Offline

#765 2010-01-09 23:16:24

tomd123
Developer
Registered: 2008-08-12
Posts: 565

Re: Post your handy self made command line utilities

Peasantoid wrote:

Tiny Python script to xor-'encrypt' a file so as to hide it from casual snooping. Hardly worth mentioning, really:

#!/usr/bin/env python
import sys
with open(sys.argv[1], 'rb') as f:
  data = ''.join(chr(ord(c) ^ 64) for c in f.read())
with open(sys.argv[1], 'wb') as f:
  f.write(data)

Any value can be substituted for 64.

Why not just zlib.compress it? You'll 'encrypt' it and save space smile

Offline

#766 2010-01-10 04:02:30

vkumar
Member
Registered: 2008-10-06
Posts: 166

Re: Post your handy self made command line utilities

tomd123: Because of the way xor works - xor(xor("hello")) is "hello". If he used zlib, he'd have to check if the file was compressed already before 'encrypting' it smile.


div curl F = 0

Offline

#767 2010-01-10 05:22:49

tomd123
Developer
Registered: 2008-08-12
Posts: 565

Re: Post your handy self made command line utilities

vkumar wrote:

tomd123: Because of the way xor works - xor(xor("hello")) is "hello". If he used zlib, he'd have to check if the file was compressed already before 'encrypting' it smile.

zlib.decompress(zlib.compress('hello')) == 'hello'
tongue

Offline

#768 2010-01-10 13:59:20

Daenyth
Forum Fellow
From: Boston, MA
Registered: 2008-02-24
Posts: 1,244

Re: Post your handy self made command line utilities

But zlib.compress(zlib.compress('hello')) != 'hello'

Offline

#769 2010-01-10 17:35:01

brisbin33
Member
From: boston, ma
Registered: 2008-07-24
Posts: 1,796
Website

Re: Post your handy self made command line utilities

vkumar wrote:
#!/bin/sh
aplay /usr/share/sounds/error.wav &>/dev/null

I like to append this to commands that will take a long time to run. It plays a little "ding" to let me know the job is done.

i do the same with

echo -e "\a"

then however you handle termanil bells (WM urgency hints, flashing term, audible pcbeep, whatever) will notify you.

Offline

#770 2010-01-10 21:27:41

Dieter@be
Forum Fellow
From: Belgium
Registered: 2006-11-05
Posts: 1,959
Website

Re: Post your handy self made command line utilities

brisbin33 wrote:
vkumar wrote:
#!/bin/sh
aplay /usr/share/sounds/error.wav &>/dev/null

I like to append this to commands that will take a long time to run. It plays a little "ding" to let me know the job is done.

i do the same with

echo -e "\a"

then however you handle termanil bells (WM urgency hints, flashing term, audible pcbeep, whatever) will notify you.

cool stuff.  I use this:

notify_state ()
{
        ($@)   
        if [ $? = 0 ]
        then
                notify-send ":-) done: $@"
        else
                notify-send --urgency critical ":'( failed: $@"
        fi
}


< Daenyth> and he works prolifically
4 8 15 16 23 42

Offline

#771 2010-01-12 02:52:58

ataraxia
Member
From: Pittsburgh
Registered: 2007-05-06
Posts: 1,537

Re: Post your handy self made command line utilities

I wrote a little script called "jukebox" to play music painlessly in the background:

#!/bin/bash

oggpid=$(pgrep -x ogg123)

if [ -z "$oggpid" ] ; then
    exec ogg123 -q -Z $HOME/music/vorbis
fi

grep -q "^State:.*stopped" /proc/$oggpid/status

if [ $? -eq 0 ] ; then
    kill -CONT "$oggpid"
else
    kill -STOP "$oggpid"
fi

Unlike some other scripts of this purpose I've seen around, this one doesn't rely on any saved state to decide what to do, but instead considers the situation "from scratch" on each run. As an added bonus, it will "adopt" any ogg123 that you start by hand, rather than ignoring it and starting another one.

I have some keybinds for Openbox to go with it:

               <keybind key="W-z">
                       <action name="Execute">
                               <command>jukebox</command>
                       </action>
               </keybind>
               <keybind key="W-x">
                       <action name="Execute">
                               <command>pkill -INT ogg123</command>
                       </action>
               </keybind>

(For those who aren't familiar with it, SIGINT causes ogg123 to skip to the next file, or to quit if you send two within one second.)

The trunk version on ogg123 supports ReplayGain, so I'm finally enabled to get rid of MPD completely. (The vorbis-tools maintainer is looking for help getting 1.3.0 out if anybody is interested - he's working 2 jobs ATM and has no time for vorbis-tools.)

Offline

#772 2010-01-12 12:22:02

dark_dragon
Member
Registered: 2008-09-25
Posts: 7

Re: Post your handy self made command line utilities

I use this script with dzen/wmii status bar to display my battery information. Probably similar posted before, but only read half of the posts.

#!/bin/bash
##
#
# A simple battery script giving a short and sweet battery message.
#
# Can probably be improved. The use of grep to get the last word really 
# ought to be sed or similar, but I couldn't be bothered to look up the 
# syntax. Feel free to modify at will. (improvements more than welcome!).
#
# Dependencies:
#    bc
#    acpi in kernel
#
##

PRESENT=`cat /proc/acpi/battery/BAT0/state | grep -o "present:.*$" |grep -o "yes"`

if [[ "$PRESENT" = "yes" ]]; then
    STATUS=`cat /proc/acpi/battery/BAT0/state | grep -o "charging state:.*$" | grep -E -o "[a-zA-Z]*$"`
    CAPACITY=`cat /proc/acpi/battery/BAT0/info | grep "design capacity:" | grep -E -o "[0-9]{3,5}"`
    CHARGE=`cat /proc/acpi/battery/BAT0/state| grep "remaining capacity:" | grep -E -o "[0-9]{2,5}"`
    PERCENT=`echo "scale=2; ($CHARGE/$CAPACITY)*100" | bc | grep -E -o "[0-9]{1,3}" | grep -v "^00" | tr -d "\n\r"`;
    
    RATE=`cat /proc/acpi/battery/BAT0/state| grep "present rate:" | grep -E -o "[0-9]{1,4}"`
    TIME=`echo "scale=2; ($CHARGE/$RATE)" | bc | tr -d "\n\r"`
    HOURS=`echo "scale=0; ($TIME/1)" |bc`
    MINUTES=`echo "scale=0; (($TIME-($TIME/1))*60/1)" |bc`
    
    #echo -e "stat=$STATUS\ncap=$CAPACITY\ncharge=$CHARGE\n%=$PERCENT\nrate=$RATE\ntime=$TIME\nhours=$HOURS\nmins=$MINUTES"
    
    
    #check if minutes is singular and add leading zero
    if [[ `echo $MINUTES| grep -E "^[0-9]{1}$"` ]]; then
        MINUTES="0$MINUTES";
    fi;
    
    if [[ "$STATUS" == "charging" ]]; then
        sleep 0;
    elif [[ "$STATUS" == "charged" ]]; then
        sleep 0;
    else
        STATUS="($HOURS:$MINUTES)";
    fi;
    echo "$PERCENT% $STATUS";
else
    echo "not present"
fi

sample invocation:

>bat.sh
not present
>bat.sh
30% (3:23)
>bat.sh
34% charging
>bat.sh
100% charged

'bc' could probably be changed for perl/python if you don't want to install it.

Last edited by dark_dragon (2010-01-12 12:26:12)

Offline

#773 2010-01-12 12:30:31

dark_dragon
Member
Registered: 2008-09-25
Posts: 7

Re: Post your handy self made command line utilities

This status script can either print a status message or uses dzen2 to make a small statusbar at the bottom of the screen. Works great either with wmii ("status.sh --string" in wmiirc) or openbox ("status.sh --dzen &" in autostart.sh). Makes use of the above battery script for my laptop.

#! /bin/bash

##
# Simple script to write status information on cli or using dzen (a la wmii)
# depends on:
#        volch.sh
#        sensors
#        bat.sh
#        dzen2 (when using --dzen switch)
##

netstatus(){
    if [[ `ifconfig | grep $1` ]]; then
        IP=`ifconfig | grep "wlan0.*$" -A1 | grep -o "[0-9]*\.[0-9]*\.[0-9]*\.[0-9]*" | head -1`;
        if [[ ! $IP ]]; then
            IP="unassociated";
        fi;
    else 
        IP="down";
    fi;
    echo $IP
}




status() {
    IP_wlan0=`netstatus wlan0`
    IP_eth0=`netstatus eth0`

    #echo -n $(mpc | head -1) \
    echo '|' $(echo "vol:"; cat /tmp/volume_cur) \
    '|' $(sensors |grep temp1| grep -Eo "\+[0-9]{2}\.[0-9]") 'C' \
    '| E:' $IP_eth0 \
    '| W:' $IP_wlan0 \
    '| up:' $(uptime | awk '{print $3}'| grep -o "[([:digit:]+:[:digit:]+)]" | tr -d [:space:]) \
    '| bat:' $(/home/brice/scripts/bat.sh)  \
    '|' $(date +"%a %d %b, %H:%M   ") 
}


if [[ $1 == --string ]]; then
    status;
elif [[ $1 == --dzen ]]; then
    while true; do 
        status
        sleep 1
    done | dzen2 -p -fn "-*-terminal-*-*-*-*-11-*-*-*-*-*-*-*"  -y 800 -ta r
else
    echo "invoke with --string or --dzen"
fi;

Example output:

>status.sh --string
| vol: 50 | +39.5 C | E: down | W: 192.168.1.72 | up: 1:21 | bat: not present | Tue 12 Jan, 12:37

Offline

#774 2010-01-12 12:36:57

dark_dragon
Member
Registered: 2008-09-25
Posts: 7

Re: Post your handy self made command line utilities

oh, and just for fun:

#!/bin/bash
#bofh
echo `telnet bofh.jeffballard.us 666 2>/dev/null` |grep --color -o "Your excuse is:.*$"

eg:

>bofh
Your excuse is: network down, IP packets delivered via UPS

Last edited by dark_dragon (2010-01-12 12:38:59)

Offline

#775 2010-01-12 13:29:24

upsidaisium
Member
From: Vietnam
Registered: 2006-09-16
Posts: 263
Website

Re: Post your handy self made command line utilities

i like the little alias that uses curl to sent a status update to twitter -- who knew it was so easy! yikes ... but knowing my tendency to ramble along, going over that pesky 140 character limit, i thought it might be prudent to put in a check:

function tweet() {
    CHARS=`echo $* | wc -m`
    if [ $CHARS -gt 140 ]
    then
        echo ":("
    else
        curl -s -u U:P -d "status=$*" http://twitter.com/statuses/update.xml >/dev/null
    fi  
}

I've seen young people waste their time reading books about sensitive vampires. It's kinda sad. But you say it's not the end of the world... Well, maybe it is!

Offline

Board footer

Powered by FluxBB