You are not logged in.

#1276 2010-09-03 00:57:37

karol
Archivist
Registered: 2009-05-06
Posts: 25,440

Re: Post your handy self made command line utilities

This is nice but reports one instance to many, as 'grep $shell' gets counted as well.
I split the long awk line so you get the idea of how the output will look like.
Should still work tongue

#! /bin/sh
#
# Based on https://bbs.archlinux.org/viewtopic.php?pid=786332#p786332
# posted by Procyon

shell=dash
ps -C $shell -o rss= -o vsize= -o cmd= | awk '{rss+=$1;virt+=$2}END \
{print "COUNT: " NR; \
print "RESIDENT: " int(rss/1024) " MB"; \
print "VIRTUAL: " int(virt/1024) " MB"}'

Example output for dash:

[karol@black code]$ ./shellram
COUNT: 11
RESIDENT: 5 MB
VIRTUAL: 19 MB

Offline

#1277 2010-09-03 07:20:51

TaylanUB
Member
Registered: 2009-09-16
Posts: 150

Re: Post your handy self made command line utilities

I've been in need of a battery checker/warner/shutdowner since some time now.

#!/bin/dash

Warn () { DISPLAY=:0 ratpoison -c "echo ${*:-BATTERY WARNING}" 2> /dev/null; }

AC () { grep -q 1 /sys/class/power_supply/AC0/online } # Use return value

Shutdown ()
{
    local sec=30
    while true
    do
        AC && break
        [ $sec -eq 0 ] && exec init 0
        Warn "${sec} SECONDS TO SHUTDOWN"
        sec=$((sec-5))
        sleep 5
    done
}

while true
do
    cap=$(cat /sys/class/power_supply/BAT0/charge_now)

    if [ $cap -lt 100000 ]
    then
        AC || Shutdown
        sleep=5

    elif [ $cap -lt 200000 ]
    then
        AC || Warn 'THIRD AND LAST BATTERY WARNING'
        sleep=15

    elif [ $cap -lt 300000 ]
    then
        AC || Warn 'SECOND BATTERY WARNING'
        sleep=30

    elif [ $cap -lt 400000 ]
    then
        AC || Warn 'FIRST BATTERY WARNING'
        sleep=45

    else sleep=60

    fi

    sleep $sleep
done

Edit: Use sysfs for battery/AC info.
Edit: Specify DISPLAY for ratpoison.

Last edited by TaylanUB (2010-09-03 19:42:32)


``Common sense is nothing more than a deposit of prejudices laid down by the mind before you reach eighteen.''
~ Albert Einstein

Offline

#1278 2010-09-03 09:05:51

Ogion
Member
From: Germany
Registered: 2007-12-11
Posts: 367

Re: Post your handy self made command line utilities

I do it this way:

A warner for the user:

#!/bin/bash
# script sends alarm when battery low
export DISPLAY=":0"
batterylevel=$(acpi -b | cut -d ' ' -f 4 | tr -d '%,')

battery_alarm() {
    zenity --warning --text="Achtung Akku ist nur noch bei ${batterylevel}%"
}

[[ $batterylevel -le 15 ]] && battery_alarm

This gets run every 5 minutes from the user crontab.

The following gets run every 5 mintues from the root crontab:

#!/bin/bash
# script to automatically suspend when battery low

batterystate=`acpi -b`
batterylevel=$(echo $batterystate | cut -d ' ' -f 4 | tr -d '%,')
chargestate=$(echo $batterystate | cut -d ' ' -f 3 | tr -d ',')

suspend_netbook() {
    mpc stop
    killall mplayer
    soundoff
    pm-suspend && soundon
}

if [[ $batterylevel -le 5 && $chargestate == "Discharging" ]]
then
    suspend_netbook
fi

Ogion


(my-dotfiles)
"People willing to trade their freedom for temporary security deserve neither and will lose both." - Benjamin Franklin
"Enlightenment is man's leaving his self-caused immaturity." - Immanuel Kant

Offline

#1279 2010-09-03 09:11:13

my0pic
Member
From: Melbourne, Australia
Registered: 2008-05-23
Posts: 206

Re: Post your handy self made command line utilities

This just to tell me how many suspends my netbook has done since last boot. It's a bit horrendous but it works.

systat()
{
    SYSON=$(grep "syslog-ng starting up" $(find /var/log \
          -iname "*everything.log*" | sort -gr) | sed '$!d' \
          | cut -d: -f2- | awk '{print $1" "$2" "$3}')
    SUSPN=$(cat $(find /var/log -iname "*everything.log*" \
          | sort -gr) | sed -n '/'"$SYSON"'/,$p' | grep \
          "ACPI: Waking up from system sleep state S3" | wc -l)
    echo -e "\033[37;1;1mSystem Boot: $SYSON\nSuspends: $SUSPN\033[0m"
}

Offline

#1280 2010-09-03 09:57:09

gtklocker
Member
Registered: 2009-09-01
Posts: 462

Re: Post your handy self made command line utilities

I'm making some scripts to use with crontab...

flashcookie:

#!/bin/bash

rm -rf ~/.macromedia/Flash_Player/#SharedObjects/*/*
chmod 0500 ~/.macromedia/Flash_Player/#SharedObjects/*
rm -rf ~/.macromedia/Flash_Player/macromedia.com/support/flashplayer/sys/*
chmod 0500 ~/.macromedia/Flash_Player/macromedia.com/support/flashplayer/sys

pong:

#!/bin/bash

addr="achilles.noc.ntua.gr"

ping -c1 $addr > /dev/null
if [ $? -eq 0 ]; then
echo "ping"
else
echo "crap"
fi

Offline

#1281 2010-09-03 11:57:41

skanky
Member
From: WAIS
Registered: 2009-10-23
Posts: 1,847

Re: Post your handy self made command line utilities

karol wrote:

This is nice but reports one instance to many, as 'grep $shell' gets counted as well.
I split the long awk line so you get the idea of how the output will look like.
Should still work tongue

#! /bin/sh
#
# Based on https://bbs.archlinux.org/viewtopic.php?pid=786332#p786332
# posted by Procyon

shell=dash
ps -C $shell -o rss= -o vsize= -o cmd= | awk '{rss+=$1;virt+=$2}END \
{print "COUNT: " NR; \
print "RESIDENT: " int(rss/1024) " MB"; \
print "VIRTUAL: " int(virt/1024) " MB"}'

Example output for dash:

[karol@black code]$ ./shellram
COUNT: 11
RESIDENT: 5 MB
VIRTUAL: 19 MB

You don't need the escapes inside the awk script. It handles new lines okay without them.


"...one cannot be angry when one looks at a penguin."  - John Ruskin
"Life in general is a bit shit, and so too is the internet. And that's all there is." - scepticisle

Offline

#1282 2010-09-03 12:05:59

karol
Archivist
Registered: 2009-05-06
Posts: 25,440

Re: Post your handy self made command line utilities

I think the first one is sort of mandatory (if we want to keep the lines separated as they are now):

awk: cmd. line:1: END blocks must have an action part

I didn't bother to check the other two.
Thanks, skanky :-)

Offline

#1283 2010-09-03 12:24:45

skanky
Member
From: WAIS
Registered: 2009-10-23
Posts: 1,847

Re: Post your handy self made command line utilities

karol wrote:

I think the first one is sort of mandatory (if we want to keep the lines separated as they are now):

awk: cmd. line:1: END blocks must have an action part

I didn't bother to check the other two.
Thanks, skanky :-)

Yeah, the first one is you're right. smile
That's because you're formatting it "differently" wink

It could be

#! /bin/sh
#
# Based on https://bbs.archlinux.org/viewtopic.php?pid=786332#p786332
# posted by Procyon

shell=dash
ps -C $shell -o rss= -o vsize= -o cmd= | awk '{rss+=$1;virt+=$2}
END {
print "COUNT: " NR; 
print "RESIDENT: " int(rss/1024) " MB"; 
print "VIRTUAL: " int(virt/1024) " MB"
}'

or


#! /bin/sh
#
# Based on https://bbs.archlinux.org/viewtopic.php?pid=786332#p786332
# posted by Procyon

shell=dash
ps -C $shell -o rss= -o vsize= -o cmd= | awk '{rss+=$1;virt+=$2} END {
print "COUNT: " NR; 
print "RESIDENT: " int(rss/1024) " MB"; 
print "VIRTUAL: " int(virt/1024) " MB"
}'

etc. HTH

smile


"...one cannot be angry when one looks at a penguin."  - John Ruskin
"Life in general is a bit shit, and so too is the internet. And that's all there is." - scepticisle

Offline

#1284 2010-09-03 14:59:57

TaylanUB
Member
Registered: 2009-09-16
Posts: 150

Re: Post your handy self made command line utilities

Edited my battery checker to use sysfs. Apparently some procfs functions are depracated.
Edit: And add DISPLAY for ratpoison.

Last edited by TaylanUB (2010-09-03 19:42:56)


``Common sense is nothing more than a deposit of prejudices laid down by the mind before you reach eighteen.''
~ Albert Einstein

Offline

#1285 2010-09-04 21:40:15

JeffreyV
Member
Registered: 2010-07-24
Posts: 15

Re: Post your handy self made command line utilities

1. I use this script regularly to backup my databases

#!/bin/bash
# Author: Jeffrey Vandenborne
function login_mysql()
{
    echo -e "MYSQL Username: \c"
    read USERNAME
    
    echo -e "$USERNAME's password?: \c"
    read -s PASSWORD
    echo "" # just print a newline

    # Check if username and password are correct
    mysql -u$USERNAME -p$PASSWORD 2>/dev/null <<!
exit
!

    [ $? -eq 1 ] && login_mysql
}

function load_databases()
{

    DATABASES=()
    INDEX=0
    while read db; do
        if [[ "$db" =~ ^Database$ ]]; then
            continue
        fi
        DATABASES[${#DATABASES[@]}+1]=$db
    done < <(echo "SHOW DATABASES;" | mysql -u$USERNAME -p$PASSWORD)
}

function display_databases()
{
    for ind in ${!DATABASES[*]}; do
        printf "%2d. %s\n" $ind "${DATABASES[$ind]}"
    done

    # Backup all databases and quit
    printf "%2d. All databases\n" "0"
    printf "Q. Quit\n"
}

login_mysql
load_databases

[ ${#DATABASES[@]} -eq 0 ] && exit

echo ""
INPUT="Default"
until [[ "$INPUT" == "Q" || "$INPUT" == "q" || -z "$INPUT" ]]; do
    # Keep displaying menu
    display_databases

    printf "Your choice: "
    read INPUT

    # if input is a number, check if its within the array bounds
    # Then backup the specified index in the array
    [ $INPUT -eq 0 ] 2>/dev/null
    STATE=$? # Capture last state

    if [ $STATE -eq 0 -o $STATE -eq 1 ]; then
        # Input is a number
        if [ $INPUT -gt 0 -a $INPUT -le ${#DATABASES[@]} ]; then
            echo -e "You have chosen to backup database: \c"
            echo ${DATABASES[$INPUT]}

            # Dump it to an sql file
            mysqldump ${DATABASES[$INPUT]} -u$USERNAME -p$PASSWORD | gzip > ${DATABASES[$INPUT]}.sql.gz

            [ $? -eq 0 ] && printf "Selected database has been backed up. \n\n"
        elif [ $INPUT -eq 0 ]; then
            # Backup all databases
            echo "Backing up all databases."
            for db in ${DATABASES[@]}; do
                mysqldump "$db" -u$USERNAME -p$PASSWORD | gzip > ${db}.sql.gz
            done
        fi
    fi    
done

2. Making playlists for mplayer is really easy

#!/bin/bash

# Define input and output path
REGEX=".*[.]\(mp3\|wav|ogg\)"
O_PATH=""
I_PATH=""
RECURSIVE=0

while getopts "o:i:r" args; do
    case $args in
        o) O_PATH="$(readlink -f $OPTARG)";;
        i) I_PATH="$(readlink -f $OPTARG)";;
        r) RECURSIVE=$(($RECURSIVE + 1))
    esac
done


if [ -z "$O_PATH" -a -z "$I_PATH" ]; then
    echo "You need to specify valid arguments" >&2
    exit
fi

# Check if input path is a folder
if [ ! -d "$I_PATH" ]; then
    echo "Your input path is not a folder" >&2
    exit
elif [ ! -f "$O_PATH" ]; then
    echo "Your output path can't be read" >&2
    exit
fi

printf "Input folder: %s\nOutput file: %s\n\n" $I_PATH $O_PATH

# Do the magic
if [ $RECURSIVE -gt 0 ]; then
    find $I_PATH -regex "$REGEX" >$O_PATH 2>/dev/null
else
    find $I_PATH -maxdepth 1 -regex "$REGEX" >"$O_PATH" 2>/dev/null
fi

lines=$(cat "$O_PATH" | wc -l)
printf "Playlist contains: %d songs!\n" "$lines"

3. Swapping 2 files' contents in an instant

#!/bin/bash
# Author: Jeffrey Vandenborne
# Year: 2010
# Description: Swap 2 files' contents instantly by switching their file names

if [ ! $# -eq 2 ]; then
    echo "You need to specify 2 files"
    exit
fi

# These are actually not even needed
# Variables
# FILE1="$1"
# FILE2="$2"

if [ ! -f "$1" ]; then
    echo "File 1 is not a file"
    exit
fi

if [ ! -f "$2" ]; then
    echo "File 2 is not a file"
    exit
fi    

# do the renaming
CUR_INDEX=1
REPLACE=tmp_rep_1
while [ -f "$REPLACE" ]; do
    CUR_INDEX=$(( $CUR_INDEX + 1 ))
    REPLACE=${REPLACE/%[0-9]*/$CUR_INDEX}
done

mv "$1" "$REPLACE"
mv "$2" "$1"
mv "$REPLACE" "$2"

Last edited by JeffreyV (2010-09-04 21:47:00)

Offline

#1286 2010-09-04 22:15:53

GraveyardPC
Member
Registered: 2008-11-29
Posts: 99

Re: Post your handy self made command line utilities

JeffreyV wrote:

2. Making playlists for mplayer is really easy
...

I prefer:

mplist(){ mplayer -playlist <(tree -aif "$1" | awk '/\.(mp3|wav|ogg|avi|mpg|iso)$/'); }

Last edited by GraveyardPC (2010-09-04 22:18:09)

Offline

#1287 2010-09-04 22:21:49

karol
Archivist
Registered: 2009-05-06
Posts: 25,440

Re: Post your handy self made command line utilities

@ JeffreyV
One useless use of cat spotted!

lines=$(cat "$O_PATH" | wc -l)

Offline

#1288 2010-09-04 23:46:25

JeffreyV
Member
Registered: 2010-07-24
Posts: 15

Re: Post your handy self made command line utilities

karol wrote:

@ JeffreyV
One useless use of cat spotted!

lines=$(cat "$O_PATH" | wc -l)

Thanks for pointing that out, I added that line just today, and was wondering if that was the best way to do it.
I do wonder if <"$O_PATH" wc -l is a lot faster though big_smile

Offline

#1289 2010-09-05 07:20:34

Ogion
Member
From: Germany
Registered: 2007-12-11
Posts: 367

Re: Post your handy self made command line utilities

If your variable O_PATH points to a file or list of files you can directly use wc. wc -l file_or_list_of_files.

Ogion


(my-dotfiles)
"People willing to trade their freedom for temporary security deserve neither and will lose both." - Benjamin Franklin
"Enlightenment is man's leaving his self-caused immaturity." - Immanuel Kant

Offline

#1290 2010-09-05 10:38:16

bluewind
Administrator
From: Austria
Registered: 2008-07-13
Posts: 172
Website

Re: Post your handy self made command line utilities

JeffreyV wrote:

mysql -u$USERNAME -p$PASSWORD 2>/dev/null

Anyone can read your password in top here.

Offline

#1291 2010-09-05 11:24:22

JeffreyV
Member
Registered: 2010-07-24
Posts: 15

Re: Post your handy self made command line utilities

bluewind wrote:
JeffreyV wrote:

mysql -u$USERNAME -p$PASSWORD 2>/dev/null

Anyone can read your password in top here.

Excuse me? Don't quite see what you mean

Offline

#1292 2010-09-05 11:47:36

bluewind
Administrator
From: Austria
Registered: 2008-07-13
Posts: 172
Website

Re: Post your handy self made command line utilities

JeffreyV wrote:
bluewind wrote:
JeffreyV wrote:

mysql -u$USERNAME -p$PASSWORD 2>/dev/null

Anyone can read your password in top here.

Excuse me? Don't quite see what you mean

top (and other utils like htop, ps) (can) also show the parameters of the called program. So instead of "mysql" everyone (who has a shell on that system of course) can see "mysql -uroot -psecret" when running top -c.

That holds true for all programs so you might want to use a generated mysql config file with the password in it and strict permissions if there are other users on the system.

Offline

#1293 2010-09-05 11:55:47

JeffreyV
Member
Registered: 2010-07-24
Posts: 15

Re: Post your handy self made command line utilities

bluewind wrote:
JeffreyV wrote:
bluewind wrote:

Anyone can read your password in top here.

Excuse me? Don't quite see what you mean

top (and other utils like htop, ps) (can) also show the parameters of the called program. So instead of "mysql" everyone (who has a shell on that system of course) can see "mysql -uroot -psecret" when running top -c.

That holds true for all programs so you might want to use a generated mysql config file with the password in it and strict permissions if there are other users on the system.

Oh yes, I see, didn't think that through, it's not super important though, well I'm just using it on my working computer. The config file does sound like better practice, thanks for clearing it up

Offline

#1294 2010-09-05 14:22:42

karol
Archivist
Registered: 2009-05-06
Posts: 25,440

Re: Post your handy self made command line utilities

bluewind wrote:
JeffreyV wrote:

mysql -u$USERNAME -p$PASSWORD 2>/dev/null

Anyone can read your password in top here.

Or 'ps -Af' :-)

Offline

#1295 2010-09-07 04:49:29

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

Re: Post your handy self made command line utilities

Random Character Generator

I had originally written this in perl a couple years ago for creating random passwords, and today (because I was bored) decided to make a python version. Someone may find it useful. As always, any comments or suggestions are appreciated.

python version

#!/usr/bin/env python

# ----------------------------------------------------------------------
# chargen.py - Character Generator
# ----------------------------------------------------------------------

from optparse import OptionParser
import sys
import random

def Main():
# ----------------------------------------------------------------------
# PARSE USER INPUT
# ----------------------------------------------------------------------
    parser = OptionParser(usage="%prog [-clnsuq] LEN", version="%prog 1.0");
    parser.add_option("-c","--confusable", dest="confusable", action="store_false", default=True, help="Exclude confusable characters");
    
    parser.add_option("-l","--lowercase", dest="lowercase", action="store_false", default=True, help="Exclude lowercase characters");
    parser.add_option("-n","--numbers", dest="numbers", action="store_false", default=True, help="Exclude numeric characters");
    parser.add_option("-s","--symbols", dest="symbols", action="store_false", default=True, help="Exclude symbol characters");
    parser.add_option("-u","--uppercase", dest="uppercase", action="store_false", default=True, help="Exclude uppercase characters");
    parser.add_option("-q","--qty", dest="qty", action="store", default=1, type="int", help="Quantity of strings to generate");
    
    (options, args) = parser.parse_args();

# ----------------------------------------------------------------------
# START VALIDATE INPUT
# ----------------------------------------------------------------------
    ERRORS = [False, ""]

# check if all character-types were excluded on the command line
    if not options.uppercase and not options.lowercase and not options.numbers and not options.symbols:
        ERRORS[0] = True;
        ERRORS[1] += "STOP 0x001: At least 1 character-type must be allowed in order to generate a character string.\n";

# check if -q was set to 0 (or negative)                
    if options.qty < 1:
        ERRORS[0] = True;
        ERRORS[1] += "STOP 0x002: Quantity [-qX] option must be at least 1 (default) or there is nothing to do.\n";

# check that exactly 1 length argument was passed        
    if len(args) <> 1:
        ERRORS[0] = True;
        ERRORS[1] += "STOP 0x003: Program requires exactly 1 numeric LEN argument\n";

# check that length argument was passed a number
    try:
        length = int(args[0]);
    except:
        ERRORS[0] = True;
        ERRORS[1] += "STOP 0x004: LEN argument must be a numeric value\n";

# if any errors    were found: print usage and error output before
# exiting.
    if ERRORS[0]:
        SYNTAX = "%s [-clnsuq] LEN" % (sys.argv[0])
        print "\n%s\n%s" % (SYNTAX, ERRORS[1]);
        sys.exit();

# ----------------------------------------------------------------------
# END VALIDATE INPUT
# ----------------------------------------------------------------------

# ----------------------------------------------------------------------
# GENERATE CHARACTER STRINGS
# ----------------------------------------------------------------------
    
# character map of usable characters (uppercase will be created from lower)
    charmap = "abcdefghijklmnopqrstuvwxyz0123456789`~!@#$%^&*()_+-=[]{};\\|\':\",./<>?"
# confusable characters
    confuse = "0O1lI";
# initialize
    chars = "";

# append included character-types    
    if options.lowercase: chars += charmap[0:26];
    if options.uppercase: chars += charmap[0:26].upper();
    if options.numbers: chars += charmap[26:36];
    if options.symbols: chars += charmap[36:];

# remove confusable characters if specified    
    if not options.confusable:
        for i in confuse:
            chars = chars.replace(i, '');

# create character strings
    for i in range(options.qty):
        passw = ""    # initialize
        for j in range(length):
            passw += chars[random.randrange(0,len(chars))];
        
        print passw;    # print to stdout
    
Main();

perl version

#!/usr/bin/perl

## ***************************************************************************
#
#  genpass v1.0 (06.2007) Password Generation Program
#  Copyright (C) 2007 Jon Brown
#
#  This program is free software; you can redistribute it and/or modify
#  it under the terms of the GNU General Public License as published by
#  the Free Software Foundation; either version 2 of the License, or
#  (at your option) any later version.
#
#  To read the full text go to http://www.gnu.org/licenses/gpl.txt
#
#  This program is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#
#  You should have received a copy of the GNU General Public License
#  along with this program; if not, write to the Free Software
#  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
#
## ***************************************************************************

use strict;
use warnings;
use Getopt::Long;
Getopt::Long::Configure ("bundling");

## PARSE AND SET COMMAND-LINE OPTIONS
## -----------------------------------------------------
my %flags=('symbols', 0, 'numbers', 0, 'uppercase', 0, 'lowercase', 0, 'confusable', 0, 'help', 0, 'qty', 1, 'version', 0);

GetOptions( 's|S|symbols' => \$flags{symbols},
        'n|N|numbers' => \$flags{numbers},
        'u|U|uppercase' => \$flags{uppercase},
        'l|L|lowercase' => \$flags{lowercase},
        'c|C|confusable' => \$flags{confusable},
        'q|Q:i' => \$flags{qty},
        'help' => \$flags{help},
        'ver|version' => \$flags{version} );

# Set password characters, excluding those flagged on the command-line
my $pwdchars = join( '', map {chr} ( 0x21 .. 0x7e ));
    $pwdchars =~ s/\d+//    if ( $flags{numbers} );
    $pwdchars =~ s/[A-Z]+// if ( $flags{uppercase} );
    $pwdchars =~ s/[a-z]+// if ( $flags{lowercase} );
    $pwdchars =~ s/[_\W]+//g if ( $flags{symbols} );
    $pwdchars =~ tr/1Il0O//d  if ( $flags{confusable} );

# If user triggered the --help option flag, display and exit
if ($flags{help}) {           
    &DisplayUsage();   
    exit();
}
elsif ($flags{version}) {
    &DisplayVersion();
    exit();
}

## START VALIDATE INPUT
## -----------------------------------------------------
my $kill=0;        # flag to stop the script if input is invalid (or --help is used)
my @errmsg;        # error message descriptions

# If -q option was used to set a quantity of passwords, make sure it contains at
# least a value of 1 so that a password can be generated
if ($flags{qty} == 0 || $flags{qty} < 0) {
    $flags{qty}=1;
}

# Check that user hasn't excluded all character-types, warn user, kill script
if ( length($pwdchars) == 0) {
    push @errmsg, "** 0x1: At least 1 character-type must be included";   
    $kill=1;
}

# Check that user has passed only 1 argument (LENGTH) other than options flags, warn user, kill script
if ($#ARGV > 0 || $#ARGV < 0) {
    push @errmsg, "** 0x2: Incorrect number of arguments passed";
    $kill=1;
}

# Check for only numeric input in LENGTH argument, warn user, kill script
if ($ARGV[0] !~ /^[0-9]+$/) {
        push @errmsg, "** 0x3: Invalid input. LENGTH argument must be a numeric value";
        $kill=1;
}

# If any of the above validation tests triggered the $kill flag...
if ($kill == 1) {                    
    print "\n** GENPASS ERROR ---------------------------------------------------------";
    print "\n** ".@errmsg." Error(s) found";      # display number of errors   
    foreach my $err (@errmsg) {             # display error messages
        print "\n".$err;
    }
    print "\n**\n** Type genpass --help for command usage\n";
    print "** -----------------------------------------------------------------------\n\n";
    exit();                         # exit script
}
## END VALIDATE INPUT

## START MAIN SCRIPT
## -----------------------------------------------------
# From 1 to qty

for ( 1..$flags{qty} ) {
    print &GenPass( $ARGV[0] )."\n";
}
exit();

## END MAIN SCRIPT

## FUNCTION DEFINITIONS
## -----------------------------------------------------
sub GenPass() {
    my ($pwdlen) = @_;
    my $limit = length( $pwdchars );
    my $pwd = '';
   
    for ( 0..$pwdlen-1 ) {
            $pwd .= substr( $pwdchars, rand( $limit ), 1 );
    }

    return $pwd;
}

# use Here-Documents to display usage text
sub DisplayUsage {
    print <<"USAGE";

  Usage: genpass [-snulcqX] LENGTH
  Generate secure passwords LENGTH characters long.
   
    -s, --symbols\tExclude symbols.
    -n, --numbers\tExclude numbers.
    -u, --uppercase\tExclude uppercase letters.
    -l, --lowercase\tExclude lowercase letters.

    -c, --confusable\tExclude confusable characters like: l,I,1,0,O
       
    -qX\t\t\tCreate X number of passwords.
       
    --help\t\tDisplay Usage information.
    --ver, --version\tDisplay version and license information.
       
  Report bugs, comments, and questions to jbrown_home\@yahoo.ca
   
USAGE
}

# use Here-Documents to display version text
sub DisplayVersion {
print <<"VER";
  genpass v1.0 (06.2007) Copyright 2007 Jon Brown

  This is free software.  You may redistribute copies of it under the terms of
  the GNU General Public License <http://www.gnu.org/licenses/gpl.html>.
  There is NO WARRANTY, to the extent permitted by law.

  Written by Jon Scott Brown
VER
}
__END__

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

#1296 2010-09-07 07:11:29

dmz
Member
From: Sweden
Registered: 2008-08-27
Posts: 881
Website

Re: Post your handy self made command line utilities

I'm using MPD on one of the servers and streaming the music to whereever I happen to be.
When a good track comes on and I'd like it transfered to my portable music player, I use...
cpmpd

#!/usr/bin/perl
our $APP     = 'cpmpd';
our $VERSION = 0.2;

use strict;
use Getopt::Long;
use Pod::Usage;

#FIXME throw this crap in a config file
my $base       = '/mnt/Music_1';
my $target     = "$ENV{HOME}/ToTransfer";
my $user       = 'scp1';
my $host       = '192.168.1.101';
my $port       = 19216;
my $scp        = '/usr/bin/scp';

chomp(my $file = `mpc -h $host --format %file%|head -1`);
my $path       = "$base/$file";

my ($basename) = $path =~ m;.+/(.+)$;;
my ($album)    = $path =~ m;(.+)/.+$;;
my ($albname)  = $album =~ m;.+/(.+)$;;

our($opt_album) = undef;
our(@opt_search);

if(!@ARGV) {
  get_track();
}

GetOptions(
  'album'         => \&get_album,
  'track'         => \&get_track,
  'dest:s'        => \$target,
  'search=s{1,}'  => \@opt_search,
  'help'          => sub { pod2usage(verbose => 1); exit(0); },
  'man'           => sub { pod2usage(verbose => 3); exit(0); },
);


search(@opt_search) if(@opt_search);

sub get_album {
  printf("\e[38;5;208m\e[1m$albname\e[0m => \e[1m$target\e[0m\n");
  transfer($album);
}
sub get_track {
  printf("\e[38;5;196m\e[1m$basename\e[0m => \e[1m$target\e[0m\n");
  transfer($path);
}

sub search {
  my @search = @_;
  my $query = join(' ', @search);
  chomp(my @result = `mpc -h $host search $query`);
  if(@result) {
    map{$_ = "$base/$_"} @result;
    transfer(@result);
  }
  exit(0);
}
sub transfer {
  my @files = @_;
  #FIXME skip .{jpg,nfo,sfv,m3u} etc. grep for {mp3,flac}?
  # use find on remote host? what about albums/single tracks?
  for(@files) {
    $_ =~ s/([;<>\*\|`&\$!#\(\)\[\]\{\}:'"])/\\$1/g;
    system("$scp -P $port -r $user\@$host:\"$_\" $target");
  }
  exit(0);
}

=pod

=head1 NAME

  cpmpd - copy music from a (remote) MPD server

=head1 DESCRIPTION

  cpmpd is cool

=head1 OPTIONS

  --dest    set target destination
  --album   copy the now playing album to target
  --track   copy the now playing track to target
  --search  search the MPD db and copy results to target

  --help    show the help and exit
  --man     show the manpage and exit

=head1 COPYRIGHT

Copyright (C) Magnus Woldrich 2010

License GPLv2

=cut

I'm streaming the MPD output to my cellphone as well. Sadly it runs an old Perl
version, meaning I can not use all nifty features. I started porting rmcd
but I felt I didn't need all those features anyway (I just want to stream audio
and play media with a daemonized process) so I quickly made...

shivastream

#!/usr/bin/perl
# shivastream - constant stream of mushy mushrooms
# barebone port of http://github.com/trapd00r/rmcd totally stripped
# of the cool stuff and adjusted for the small display. It also needs
# to be compatible with v5.8.3 :(
use strict;
use Getopt::Long;

my $config  = "$ENV{HOME}/.shivastream.conf";
my $fifo    = "$ENV{HOME}/.shivastream.fifo";
my $log     = "$ENV{HOME}/MyDocs/log/shivastream.log"; # Maemo specific
my $pidfile = '/tmp/shivastream.pid';
my $player  = 'mplayer';
my @playopt = (
  '-cache', 400,
  '-cache-min', 10,
  '-identify', 
  '-idle',
  '-input', "file=$fifo",
);



our(%channels);
if(!-f $config) {
  print "$config does not exist\n";
}
else {
  require($config); #FIXME
}

if(!-p $fifo) {
  require POSIX;
  print "Creating $fifo\n";
  POSIX::mkfifo($fifo, 0666) or die("$fifo: $!");
}

if(!@ARGV) {
  load('psy');
}

our(@opt_play_songs);
GetOptions(
  'kill'        => \&killkid,
  'load:s@'     => \@opt_play_songs,
  'clist'       => \&list_chans,
  'help'        => sub {print "-load | -kill\n\n" and exit(0);},
);

load(@opt_play_songs) unless(!@opt_play_songs);


sub geturi {
  my $name = shift;
  return(undef) unless(exists($channels{$name}));
  return($channels{$name}->{uri});
}

sub list_chans {
  for my $name(sort(keys(%channels))) {
    printf("%s\n", $name); # not much space on display
  }
}

sub get_chan_name {
  my $name = shift;
  return($channels{$name}{name});
}

sub load {
  my @toload = @_;
  if($channels{$toload[0]}) {
    $toload[0] = $channels{$toload[0]}->{uri};
  }
  if(!-e $pidfile) { # not started
    if($toload[0] !~ m;(?:http|mms)://;) {
      my @fixme = @toload;
      for(@fixme) {
        s;.+/(.+);$1;;
        print("Adding \e[1m$1\e[0m\n");
      }
    }
    daemonize();
    exec($player, @playopt, @toload);
  }
  exit(0) if(!@toload);
  my @fixme = @toload;
  for(@fixme) {
    s;.+/(.+);$1;;
    print("Adding \e[1m$1\e[0m\n");
  }
  open(my $fh, '>', $fifo) or(die("Cant open fifo $fifo: $!"));
  print $fh "loadfile @toload\n";
  exit(0);
}

sub daemonize {
  use POSIX 'setsid';
  my $PID = fork();
  exit(0) if($PID);
  exit(1) if(!defined($PID));

  setsid();
  $PID = fork();
  exit(1) if(!defined($PID));

  if($PID) { # parent
    waitpid($PID, 0);
    unlink($pidfile);
    exit(0);
  }
  elsif($PID == 0) { # child
    open(my $fh, '>', $pidfile) or die("$pidfile: $!");
    print $fh $$;
    close($fh);
    open(STDOUT, '>', '/dev/null');
    open(STDERR, '>', '/dev/null');
    open(STDIN,  '<', '/dev/null');
  }
}

sub killkid {
  open(my $fh, '<', $pidfile) or(print("shivastream is \e[1mOFF\e[0m\n") and exit(1));
  my $pid = <$fh>;
  close($fh);
  if(kill(9, $pid)) {
    print("shivastream with PID $pid was \e[1mkilled\e[0m\n");
  }
  else {
    print "Could not kill $pid: $!\n";
  }
  exit(0);
}

Offline

#1297 2010-09-07 12:20:48

steve___
Member
Registered: 2008-02-24
Posts: 452

Re: Post your handy self made command line utilities

munkyeetr wrote:

Random Character Generator

I thought you might find this interesting.  I believe it was posted by someone in this thread.

$ tr -dc A-Z </dev/urandom | fold -w 8 | head -n 1  ## generate random characters

Offline

#1298 2010-09-07 12:39:21

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

Re: Post your handy self made command line utilities

steve___ wrote:

I thought you might find this interesting.  I believe it was posted by someone in this thread.

$ tr -dc A-Z </dev/urandom | fold -w 8 | head -n 1  ## generate random characters

nice...that's pretty slim.


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

#1299 2010-09-07 16:24:58

karol
Archivist
Registered: 2009-05-06
Posts: 25,440

Re: Post your handy self made command line utilities

munkyeetr wrote:
steve___ wrote:

I thought you might find this interesting.  I believe it was posted by someone in this thread.

$ tr -dc A-Z </dev/urandom | fold -w 8 | head -n 1  ## generate random characters

nice...that's pretty slim.

tr -dc 'A-Za-z0-9!@#$%^&*'

This will give a bit more variety.

Offline

#1300 2010-09-07 17:32:04

hatten
Arch Linux f@h Team Member
From: Sweden, Borlange
Registered: 2009-02-23
Posts: 736

Re: Post your handy self made command line utilities

karol wrote:
munkyeetr wrote:
steve___ wrote:

I thought you might find this interesting.  I believe it was posted by someone in this thread.

$ tr -dc A-Z </dev/urandom | fold -w 8 | head -n 1  ## generate random characters

nice...that's pretty slim.

tr -dc 'A-Za-z0-9!@#$%^&*'

This will give a bit more variety.

I use

#!/bin/bash
echo "For what do you want to make a password?"
read name
echo "How long?"
read len
pw=$(dd if=/dev/urandom count=1 2> /dev/null | uuencode -m -| sed -ne 2p | cut -c-$len)
echo $name ';' $pw >> ~/password/file
cat ~/password/file | grep $pw

for that, found it somewhere on the internet and modified it for my own uses.

Offline

Board footer

Powered by FluxBB