PDA

View Full Version : Useful scripts


Dr_Phoenix
December 2nd, 2008, 08:27
Hi people!
Please, post here useful scripts which can help to do some useful or difficult operation on FreeBSD OS.

I will be the first:

Script which restarts the PPP daemon if connection is lost or daemon hung up.
The principe: ping remote ~100% uptime server to determine if Internet connection available.

ppp_check.sh

#!/usr/bin/perl

use Net::Ping;

$server_to_ping="ya.ru";


sub check_ping_server
{
$host_alive=1;
$ping=Net::Ping->new('icmp');
if( $ping->ping($_[0]) ) { $host_alive=1;}
else {$host_alive=0;}
return $host_alive;
}



if(!check_ping_server($server_to_ping))
{
system("killall ppp");
system("sleep 2");
# Start PPP ADSL connection
system("/usr/sbin/ppp -quiet -ddial adsl");
# Send the message to
system("echo PPP restarted by timeout...");
}

exit;


Next one - Firebird databases backup script.
Assumed that catalogues have the next structure:

- /Data
| | |
| | Database1 - DB1.FDB, DB2.FDB, ...
| |
| |
| Database2 - Data.FDB, Protocol.FDB, ...

The result of script work will be two archives in backup directory:
Database1-14-11-08_03_04.tar.gz
Database2-14-11-08_04_04.tar.gz

db_backup.sh

#!/bin/sh
#----------------- DB Backup Script -------------------
#------------- by Dr_Phoenix Lutsk 2007 ---------------

# mount backup volume if needed
#mkdir /mnt/temp
mount /dev/ad2s1d /mnt/DB_BACKUP
clear

#---------------- Configure section -------------------
# Path to bases
db_path="/Data"
# Path to Backup directory
backup_path="/mnt/DB_BACKUP"
Set path to GBAK
gbak_path="/usr/local/bin/gbak" #
# Set date format to be attached to file name
current_date=`date "+%d-%m-%y_%H_%M"`
# Enable Logging to console 1-yes/0-no
enable_verbose=1
#------------------------------------------------------

# Creating backup directory if not exist
if [ ! -d $backup_path ]; then
mkdir $backup_path
fi

# Print short info about system
if [ $enable_verbose -gt 0 ]; then
host_name=`uname -i -m -s`
echo " ----> $host_name "
echo " ----> ${current_date} "
fi

# Begin main cycle of backuping :)
for i in `ls $db_path`
do
if [ -d $db_path/$i ]; then
for n in `ls $db_path/$i/`
do

if [ -f $db_path/$i/$n ]; then
if [ $enable_verbose -gt 0 ]; then
echo "Backuping file : < $n >"
echo "File Full Path : $db_path/$i/$n"
fi
# check if backup dir exist
if [ ! -d $backup_path/$i ]; then
mkdir $backup_path/$i
fi
# backuping current database file
$gbak_path -USER SYSDBA -PASS masterkey -b $db_path/$i/$n $backup_path/$i/$n.GBK -V -IG -Y $backup_path/$i/$n.log

fi
done

fi

# Creating GZIPped tar archive of current bases directory
if [ $enable_verbose -gt 0 ]; then
echo "----> GZipping Databases in $i ..."
fi
tar -czf $backup_path/$i-$current_date.tar.gz $backup_path/$i/*

# Clearing DB directory...
if [ $enable_verbose -gt 0 ]; then
echo "----> Clearing DB directory $i ..."
fi
rm $backup_path/$i/*

done

voice
December 2nd, 2008, 08:52
Dr_Phoenix, maybe it is better to add next line
system("killall -9 ppp");
after
system("killall ppp");
in ppp_check.sh script?
I think in this case You have more chance to kill ppp process.

graudeejs
December 2nd, 2008, 10:12
I use this script on file tree, that was copied from MSDOSFS or CD9660.
After copying files are marked executable. Also there are destop.ini and Thumbs.db files. Removing them by hand on large file trees is pain.

It also replaces most problematic characters, like spaces..., but not all (this can be easily adopted)

so here is my sollution:
rmwin****.sh (mod, modify name if you want, but that's original script name)

#!/bin/sh

rmWin____FileNames() {
for fileName in $1/*; do
newFileName=$(echo "$fileName" | tr ' []'\' '_-__')

if [ "$fileName" != "$newFileName" ]; then
mv -f "$fileName" "$newFileName"
fi

if [ -d "$newFileName" ]; then
chmod u+wrx "$newFileName"
rmWin____FileNames "$newFileName"
else
chmod uog-x,u+rw "$newFileName"
fi

done
}

if [ -d "$1" ]; then
dir="$1"
else
dir=`pwd`
fi

find "$dir" -name Thumbs.db -delete
find "$dir" -name "Desktop.ini" -delete

rmWin____FileNames "$dir"
echo "Win**** is removed!!!"
exit 0


I use this script a lot

P.S. i censored it :)

EDIT:
http://aldis.git.bsdroot.lv/rmwinshit/

sverreh
December 2nd, 2008, 10:41
Here is a very simple little script that I use to reduce the size of pictures. Quite useful when you need to send a lot of large pictures by E-mail.

#! /bin/sh

# Convert JPG and PNG images to another quality.
# Used to reduce image size. (Useful for E-mail.)
# Requires convert (part of the ImageMagick port)

if [ $# -lt 2 ]
then
echo "Usage: <quality (0 - 100)> <filenames>"
exit
fi
q=$1
shift
for arg
do
convert -quality "$q" "$arg" "small_""$arg"
done

kamikaze
December 2nd, 2008, 10:47
I collect my useful scripts in the sysutils/bsdadminscripts port:


This is a collection of administration scripts. At the moment it
consists of a script to control rc.d scripts at runtime, a
script that runs common make targets on batches of ports, scripts to set
variables for make jobs (like portconf, but with more possibilities).
And scripts to check for broken packages and missing libraries.

Another script I find useful does automounting without HAL.

A script to dynamically configure amd and populate /media with appropriate
links, when USB mass storage devices appear. It relies on geom labels, hence
it only works for properly labeled devices.

It also allows to automatically attach geli encrypted devices and images with
keys polled from file systems it makes mountable.

The following is my automounter.conf file.

ntfs=ntfs-3g
ntfs_options=rw,noatime,gid=5,umask=113,dmask=002, locale=en_GB.UTF-8
#ntfs_options=ro,force,noatime,gid=5,umask=113,dma sk=002,locale=en_GB.UTF-8
msdosfs_options=$mount_options,-L=en_GB.UTF-8,-m660,-M770
ufs_options=rw,noatime
blacklist_devs="acd*"
blacklist_nodes="ufs/2*"
geli=1
evil_fuse=1


Of course all these ports come with extensive manual page documentation.

bsddaemon
December 9th, 2008, 18:26
There is one of my scripts that could be useful for you guys. If you are managing a number of servers, sometimes it is frustrating to find a command you run before. You search for it in the history file, but it is not there, which means it locates somewhere, in a remote server.

Sometimes you cant even remember which server was it. Not sure about you guys, for me, it is such PITA!

Script to Update All History Commands Across Servers (http://asternix.org/component/content/article/1-shell-scripts/29-script-to-update-all-history-commands-across-servers)

The script should be run by cron.

Dara
December 10th, 2008, 14:20
Small script to clean out old amavisd-new stuff if it dosent do a good job by itselft..


mailclean.sh

#!/usr/local/bin/bash
#set -x #Debug
#
#Script to clean out old junk mail
#
#find $f/cur -type f -mtime +5 -exec rm '{}' '+'
#
MHOME=/var/amavisd/tmp
MDIRS=`/bin/ls -l /var/amavisd/tmp |/usr/bin/awk '{ print $9 }'`
DATE=`date "+%Y-%m-%d %H:%M:%S"`

#First do amavisd/tmp files
cd /var/amavisd/tmp
for f in `/bin/ls -l /var/amavisd/tmp |/usr/bin/awk '{ print $9 }'`
do
find $f -type f -mtime +3d -exec rm {} \;
echo "Tmp_files - $DATE - Cleaned $f" >> /var/log/mailclean.log
done

#Then do amavisd/tmp folders
cd /var/amavisd/tmp
for j in `/bin/ls -l /var/amavisd/tmp |/usr/bin/awk '{ print $9 }'`
do
find $j -type d -name 'amavis-20??????T*' -prune -mtime +1 -exec rm -rf {} \;
echo "Tmp_folders - $DATE - Cleaned $f" >> /var/log/mailclean.log
done

#then do quarantine files
cd /var/amavisd/quarantine
for k in `/bin/ls -l /var/amavisd/quarantine |/usr/bin/awk '{ print $9 }'`
do
find $k -type f -mtime +3d -exec rm {} \;
echo "Quarantine - $DATE - Cleaned $f" >> /var/log/mailclean.log
done

#
Not perfect in any way but maby somebody can have use for it..

bsddaemon
December 11th, 2008, 16:01
The following script is written because I was having problem with database backup of a busy website in "live" mode. The database is archived, but corrupted. Once restored, there were something that didnt work normally.

Script to back up entire website in safe manner (http://asternix.org/component/content/article/1-shell-scripts/31-back-up-the-entire-website-in-a-safe-manner)

harisman
December 11th, 2008, 19:14
Since I don't trust pkg_delete -r for removing my packages ( some times ended with complete remove my whole gnome base by mistake) I use this simple script for manually uninstalling packages.

It stores a backup for each uninstalled package and displays the remaining installed dependencies.

Usage: pkg_remove.sh <package>

Please note that this script needs the /usr/ports/shells/bash and /usr/ports/ports-mgmt/pkg_cutleaves to operate.

#!/usr/local/bin/bash

before="/tmp/pkg_remove_before.tmp"
after="/tmp/pkg_remove_after.tmp"
package_backup="/tmp"

function check_error {
error=$?
if [ $error -gt 0 ] ; then
echo "Fatal! problem found executing $1, exiting"
exit 1
fi
}

pkg_cutleaves -l > $before
check_error "pkg_cutleaves"

for a in $@
do
pkg_create -b `basename $a` $package_backup/`basename $a`
check_error "pkg_create on $a"
pkg_delete `basename $a`
check_error "pkg_delete on $a"

done
pkg_cutleaves -l > $after
check_error "pkg_cutleaves"
diff $before $after | awk '
BEGIN { print "################################################## ##"}
/\</ {print "Unistalled: "$2}
/\>/ {print "Remaining: "$2}
END { print "################################################## ##"}
'
rm $before $after

bsddaemon
December 13th, 2008, 12:54
Inspired by this thread (http://forums.freebsd.org/showthread.php?t=940), I just rewrite my "instead of rm, mv to trash" script (http://asternix.org/component/content/article/1-shell-scripts/33-script-to-avoid-accidental-deletion-move-to-trash-instead-of-deleting)

danger@
December 13th, 2008, 14:12
simple solution is to add the following line into the .cshrc:

alias rm 'mv -i \!* ~/.Trash'

and create ~/.Trash/ directory.

bsddaemon
December 13th, 2008, 14:44
Nice tip, but with the file/dir which has the same name, the alias will overwrite the old one. Meanwhile, my script moves them to trash dir, but put them in the absolute and original path dir. Also, my script works regardless of which shell or OS you are using.

Not sure if it should be called "bug", but with this alias, you get error if you attempt to:

- Create, then delete file named foo.
- At any dir, create new dir named foo
- Error occurs when attempting delete dir foo

Still, it can handle file/dir name with white space, which my script doesnt support. Anyone know how to resolve this problem, please let me know

danger@
December 13th, 2008, 15:02
Nice tip, but with the file/dir which has the same name, the alias will overwrite the old one.

That's why there's mv -i :-)

Not sure if it should be called "bug", but with this alias, you get error if you attempt to:

- Create, then delete file named foo.
- At any dir, create new dir named foo
- Error occurs when attempting delete dir foo

you probably didn't create ~/.Trash/ directory before using it, I forgot to mention it.

bsddaemon
December 13th, 2008, 15:18
you probably didn't create ~/.Trash/ directory before using it, I forgot to mention it.

No, I created ".Trash" dir already. That was because in any dir, the system will not accept if there are a dir and file with the same name. E.g:


bsddaemon@workstation:~% touch foo 19601
bsddaemon@workstation:~% mkdir foo 19602
[1]bsddaemon@workstation:~% mkdir: foo: File exists

danger@
December 13th, 2008, 15:27
ah I see your point now :) well we can call that bug...

graudeejs
December 21st, 2008, 19:20
multimedia/playd

Here's my new script that i now use to control mplayer daemon.
I wrote this mainly because i wanted to improve control over
mplayer daemon.
For many things i control mplayer in daemon mode with fvwm menu.

one of most usefull things is, it can play files in directories recursively.
also it can be used to play playlist that was made last time, when you used it

this can easely be used from console as well.
give it a try, maybe you'll like it


P.S. i didn't wrote entire script, because it's almost 200 lines long, and I'll probably improve it sooner or later ;)

EDIT:
git repo:
http://aldis.git.bsdroot.lv/playd.sh/

graudeejs
December 27th, 2008, 17:01
I've updated playd.sh script
I will continue to update it
you can get it from my git repo homepage
http://hg.bsdroot.lv/pub/aldis/playd.sh/
i will keep version on page up to date :)

Now i use this script all the time as well

kamikaze
December 27th, 2008, 17:44
I have this script which I use for creating start scripts for wine programs. It handles the mounting of ISO images and has some hooks to include own code.
#!/bin/sh
#
# winexec
#
# This script handles running programs with wine that require images to be
# mounted. Simply populate the required variables and put
#
# . winexec
#
# at the end of your script to run a program.
#
# version 1.1

# User line breaks as delimiters.
IFS='
'

# Set default settings.
{
# The script name, by default taken from the filename.
: ${name="$(echo "$0" | grep -Eo '[^/]+$')"}

# Name wine binary.
: ${wine_suffix=""} # Run a different wine binary.
: ${wine_bin="wine"} # The wine binary.

# Set wine directory.

: ${wine_dir="$HOME/.wine"} # Configuration folder.

# Set logfile.
: ${wine_log="$wine_dir/log.$name"} # Name of the logfile

# Set available actions.
: ${exec_default="run"} # The command that is used
# when no command is given.
: ${exec_actions="showlog mount umount"}# Other available commands.

# Set command functions.
: ${run_cmd="winexec_run"}
: ${run_pre_cmd=""}
: ${run_after_cmd=""}
: ${mount_cmd="winexec_mount"}
: ${mount_pre_cmd=""}
: ${mount_after_cmd=""}
: ${umount_cmd="winexec_umount"}
: ${umount_pre_cmd=""}
: ${umount_after_cmd=""}
: ${showlog_cmd="winexec_showlog"}
: ${test_cmd="winexec_test"}
: ${cleanup_cmd="winexec_cleanup"}

# Mount settings.
: ${mount_images=""} # A newline separated list
# of images.
: ${mount_nodes=""} # Set this if you want
# device links to /dev.
: ${mount_devices="$(printf 'd\ne\nf\ng\nh\ni\nj\nk\nl')"}
# List of permitted dos devices.
: ${mount_type="cd9660"} # The image format.
: ${mounted_file="mounted.$name"} # Remember mounted devices.
: ${loaded_file="loaded.$name"} # Remember loaded images.

# Run settings.
: ${run_binary=""} # The name of the binary to run.
: ${run_folder=""} # The folder from where to run.
: ${run_parameters=""} # Parameters for the program.

# X settings to restore if changed.
: ${x_get_res_cmd="xrandr | grep \* | grep -Eo '+[0-9]+x[0-9]+'"}
: ${x_res=$(eval "$x_get_res_cmd")}
: ${x_set_res_cmd="xrandr -s $x_res"}
: ${x_refresh_cmd="xgamma -g 1; xrefresh"}
}

# Mounts the images given in 'mount_isos'.
winexec_mount() {
eval "$mount_pre_cmd"

for image in $mount_images; {
echo "Loading image '$image'."
image=$(mdconfig -a -t vnode -f "$image")
echo "$image" >> "$wine_dir/$loaded_file"

for device in $mount_devices; {
device_dir="$wine_dir/dosdevices/$device:"
if [ ! -L "$device_dir" -a ! -e "$device_dir" ]; then
echo "Creating device '$device:'."
if [ "$mount_nodes" ]; then
ln -s "/dev/$image" "$device_dir:"
fi
mkdir "$device_dir"
mount -r -t $mount_type "/dev/$image" "$device_dir"
echo "$device" >> "$wine_dir/$mounted_file"
break
fi
}
}

eval "$mount_after_cmd"
}

# Unmount images.
winexec_umount() {
eval "$umount_pre_cmd"

for device in $(cat "$wine_dir/$mounted_file" 2> /dev/null); {
echo "Destroying device '$device:'."
device_dir="$wine_dir/dosdevices/$device:"
umount -f "$device_dir"
rmdir "$device_dir" > /dev/null 2>&1
rm "$device_dir:" > /dev/null 2>&1
}
rm "$wine_dir/$mounted_file" > /dev/null 2>&1

for image in $(cat "$wine_dir/$loaded_file" 2> /dev/null); {
echo "Destroying image node '$image'."
mdconfig -d -u "$image"
}
rm "$wine_dir/$loaded_file" > /dev/null 2>&1

eval "$umount_after_cmd"
}

# Show the logfile.
winexec_showlog() {
cat "$wine_log"
}

# Test weather all required settings are set.
winexec_test() {
}

# Cleanup the environment.
winexec_cleanup() {
# Check screnn resolution.
if [ "$(eval "$x_get_res_cmd")" != "$x_res" ]; then
eval "$x_set_res_cmd"
fi

# A little screen refresh never hurts.
eval "$x_refresh_cmd"
}

# Run the given binary.
winexec_run() {
eval "$test_cmd"
eval "$mount_cmd"

eval "$run_pre_cmd"

echo "Running '$run_binary' with '$wine_bin$wine_suffix'."
cd "$run_folder" && $wine_bin$wine_suffix "$run_binary" $run_parameters > "$wine_log" 2>&1

eval "$run_after_cmd"

eval "$cleanup_cmd"
eval "$umount_cmd"
}

# Get the given command.
command=run
if [ $1 ]; then
command=$1
fi

# Run the requested action.
for action in $exec_default $exec_actions; {
if [ "$command" = "$action" ]; then
eval $"${action}_cmd"
exit 0
fi
}

# This happens when a wrong parameter is supplied.
exit 1

This is an example for running starcraft:#!/bin/sh

wine_suffix="-kthread"
mount_images="/mnt/msdos/vault/images/starcraft.iso
/mnt/msdos/vault/images/broodwar.iso"
run_binary="starcraft.exe"
run_folder="/mnt/msdos/software/games/rts/Starcraft"

. winexec

milosz
December 30th, 2008, 07:26
I have a script that I used on FreeBSD 5 (2005/2006) at home, it was unused and not updated since then.

It's a startup script used to keep network connection using usb adsl modem (speedtouch as I remember). It can also update .Xauthority file and reconnect...

Maybe someone find some parts of it useful.


#!/bin/sh
#
# Plik: neo
#
# Info:
# Skrypt startowy (rc) połączenia dla użytkowników Neostrady.
#
# Parametry:
# start - połącz się
# restart - restart połączenia (cron)
# beonline - stara się zapewnić nieprzerwane połączenie (cron)
# stop - zatrzymaj połączenie
#
# Zmienne:
# modem_driver - określa położenie firmware'u
# ppp_flags - parametry polecenia ppp
# modem_run_flags - parametry polecenia modem_run
# ...
#
# Konfiguracja:
# echo 'neo_enable="yes"' >> /etc/rc.conf
# echo 'modem_driver="/etc/ppp/st330"' >> /etc/rc.conf
#
# Konfiguracja cron'a:
# */5 * * * * root /etc/rc.d/neo beonline
#
# Komentarz:
# Paremetry "start" oraz "stop" służą do rozpoczęcia i zakończenia połaczenia.
# Parametr restart przeznaczony jest do okresowego restartowania połaczenia
# używając cron'a (tylko z założenia), natomiast "beonline" służy
# do restartowania połączenia w przypadku jego utraty (ping), aktualizacji (ppp -ddial)
# i również przeznaczony jest dla cron'a.
#
# Konfiguracja wymaga skopiowania skrytpu do katalogu /etc/rc.d/
# i zdefiniowania w pliku /etc/rc.conf zmiennych neo_enable oraz modem_driver.
#
# Dla skryptów startowych wymagających wcześniejszego połączenia z siecią
# należy zmodyfikować regułę REQUIRE dodając parametr neo.
#
#
#
# PROVIDE: neo
# REQUIRE: netif mountcrit local
# KEYWORD: nojail
#

. /etc/rc.subr

modem_driver=${modem_driver:-"/etc/ppp/st330"}

name="neo"
rcvar=`set_rcvar`
extra_commands="beonline"
start_cmd="neo_start"
stop_cmd="neo_stop"
restart_cmd="neo_start"
beonline_cmd="neo_beonline"


#Polecenia
sh_command=${sh_command:-"/bin/sh"}
kill_command=${kill_command:-"/bin/kill"}
basename_command=${basename:-"/usr/bin/basename"}
xauth_command=${xauth_command:-"/usr/X11R6/bin/xauth"}
hostname_command=${hostname_command:-"/bin/hostname"}
domainname_command=${domainname_command:-"/bin/domainname"}
grep_command=${grep_command:-"/usr/bin/grep"}
ifconfig_command=${ifconfig_command:-"/sbin/ifconfig"}
awk_command=${awk_command:-"/usr/bin/awk"}
expr_command=${expr_command:-"/bin/expr"}
route_command=${route_command:-"/sbin/route"}
chown_command=${chown_command:-"/usr/sbin/chown"}
rm_command=${rm_command:-"/bin/rm"}

modem_run_command=${modem_run_command:-"/usr/sbin/modem_run"}
modem_run_flags=${modem_run_flags:-"-f"}

ppp_command=${ppp_command:-"/usr/sbin/ppp"}
ppp_flags=${ppp_flags:-"-quiet -ddial adsl"}
ppp_iface=${ppp_iface:-"tun0"}

ping_command=${ping_command:-"/sbin/ping"}
ping_flags=${ping_flags:-"-c1"}
ping_host=${ping_host:-"www.wp.pl"}

# Funkcja odpowiedzialna za restart firewall'a
# Wymaga dostrojenia do własnych potrzeb
neo_firewall(){
$sh_command /etc/rc.firewall
}

# Funkcja odpowiedzialna za wczytanie firmware'u
neo_driver_load(){
local modem_run_check

modem_run_check=`check_process $modem_run_command`
echo -n "Neo driver: "
if [ -z "$modem_run_check" ]; then
echo "loading"
$modem_run_command $modem_run_flags $modem_driver >/dev/null
else
echo "already loaded"
fi
}

# Funkcja sprawdzająca, czy mamy połączenie
# sprawdzając proces ppp
neo_connection_check(){
local ppp_check

ppp_check=`check_process $ppp_command`
if [ -n "$ppp_check" ]; then
echo "wait"
fi
}

# Funkcja wywołująca ppp
neo_connection_start(){
$ppp_command $ppp_flags 2>/dev/null
}

# Funkcja zatrzymująca ppp
neo_connection_stop(){
local ppp_pid

ppp_pid=`check_process $ppp_command`
if [ -n "$ppp_pid" ]; then
$kill_command $sig_stop $ppp_pid 2>/dev/null
wait_for_pids $ppp_pid > /dev/null
fi
}

# Funkcja pobierająca adres ip
# Zwraca pusty string w przypadku niepowodzenia
neo_ip_get(){
local ip="";
local ppp_loop=1
while [ -z "$ip" ] && [ "$ppp_loop" -le 12 ]; do
sleep 4
ip=`$ifconfig_command $ppp_iface | $grep_command netmask | $awk_command '/inet/ {print $2}'`
ppp_loop=`$expr_command $ppp_loop \+ 1`
done

if [ "$ppp_loop" -eq "13" ]; then
echo ""
exit 1
fi
echo $ip
}

# Funkcja odpowiedzialna za czynności po wykonaniu połączenia
# Wymaga dostrojenia do własnych potrzeb
neo_postconfigure(){

# Pobierz adres IP
local ip=""
local hostname=""
local name_stat=""

ip=`neo_ip_get`

while [ -z "$ip" ]; do
echo "Error"
sleep 10
exit 1
done

echo "IP: " $ip

# Firewall
echo "Firewall: configuring"
neo_firewall 2> /dev/null

# Pobranie nowej nazwy hosta oraz wywołanie poleceń
# hostname, domainname
hostname=""
while [ -z "$hostname" ]; do
hostname=`$route_command get $ip | $awk_command '/route/ {print $3}'`

if [ -n $hostname ]; then
name_stat=`echo $hostname | $grep_command "tpnet.pl"`
if [ -z "$name_stat" ]; then
hostname=${hostname}.neoplus.adsl.tpnet.pl
fi
else
sleep 2
fi
done

echo "Hostname: " $hostname

$hostname_command $hostname
$domainname_command $hostname

# Restart określonych usług po zmianie adresu IP
#if [ -n "$ppp_restarted" ]; then
#fi

# X'y + xauth
# Aktualizacja .Xauthority
local xauth_file=/home/milosz/.Xauthority

local mcookie=`dd if=/dev/urandom bs=16 count=1 2>/dev/null | hexdump -e \\"%08x\\"`
$rm_command $xauth_file
$xauth_command -f $xauth_file add $hostname:0 MIT-MAGIC_COOKIE-1 $mcookie 2>/dev/null
$xauth_command -f $xauth_file add $hostname/unix:0 MIT-MAGIC-COOKIE-1 $mcookie 2>/dev/null

$chown_command milosz:milosz $xauth_file
}

# Funkcja oficjalnie rozpoczynająca połączenie
neo_start()
{
local ppp_loop=1
local ppp_check=""
local ip=""

if [ -f "$modem_driver" ]; then
neo_driver_load
ppp_check=`neo_connection_check`

echo -n "Connection: "

if [ -n "$ppp_check" ]; then
echo "restarting"
neo_connection_stop
ppp_restarted=1
while [ "$ppp_check" = "wait" ]; do
if [ "$ppp_loop" -eq "13" ]; then
echo "Error: IP address not assigned"
sleep 10
exit 1
fi
sleep 3
ppp_check=`neo_connection_check`
ppp_loop=`$expr_command $ppp_loop \+ 1`
done
else
echo "starting"
fi
neo_connection_start
ip=`neo_ip_get`
echo $ip > /var/run/neo_ip
neo_postconfigure
fi
}

# Funkcja oficjalnie zatrzymująca połączenie
neo_stop(){
echo "Connection: stopped"
neo_connection_stop 2>/dev/null
}

# Funkcja sprawdzająca stan połączenia (ping)
neo_ping_check(){
local ping_check
ping_check=`$ping_command $ping_flags ${ping_host} 2>/dev/null | $grep_command "1 packets"` 2>/dev/null
echo $ping_check
}

# Funkcja odpowiedzialna za wznawianie utraconego połączenia
neo_beonline(){
local ping_check=""
local ip=""
local neo_ip
ping_check=`neo_ping_check` > /dev/null
if [ -z "$ping_check" ]; then
echo "Connection lost!"
neo_start
else
ip=`neo_ip_get`
if [ -f /var/run/neo_ip ] && [ -n `cat /var/run/neo_ip` ]; then
neo_ip=`cat /var/run/neo_ip`
if [ "$ip" != "$neo_ip" ]; then
echo $ip > /var/run/neo_ip
ppp_restarted=1
neo_postconfigure
fi
else
neo_start
fi

fi
}

load_rc_config $name
run_rc_command "$1"

estrabd
January 5th, 2009, 18:44
This is a script I wrote to take care of the arduous task of updating the ssh key of a single machine on some the machines listed in the variable, HOSTS below. Comments and suggestions are welcome.


#!bin/sh

HOSTS="host1 host2 host3"

KEYFILE=id_rsa # careful, change to not overwrite default!
PRVKEYFILE=~/.ssh/${KEYFILE}
PUBKEYFILE=${PRVKEYFILE}.pub
TMPKEY=${KEYFILE}.tmp

ssh-keygen -b 2048 -t rsa -f $PRVKEYFILE

for HOST in $HOSTS; do
echo $HOST ###
scp ${PUBKEYFILE} ${HOST}:~/${TMPKEY} && echo OK && \
ssh ${HOST} "cat ${TMPKEY} >> ~/.ssh/authorized_keys && rm ~/${TMPKEY}" && echo OK
done


Also, the vee blogger thing (see sig) is really just a sh script. I use it as a blog tool when I feel the urge, but more often than not I use it in batch mode (via cron) to maintain a web log of various system processes. Comments and suggestions are welcome about that, too.

graudeejs
January 14th, 2009, 02:32
Here's script i'm working on, for burning CD's
http://killasmurf86.lv/data/download/burn.sh.bz2
It's still incomplete, and probably buggy.
I will be updating it....

It can burn DVD's, CD's, make Disk Images

It has fallowing dependencies:
mkisofs
growisofs
mplayer


EDIT:
I almost completely rewrote my script

EDIT:
it's not available any more

vermaden
January 14th, 2009, 08:55
Here's script i'm working on, for burning CD's
http://killasmurf86.lv/data/download/burn.sh.bz2
It's still incomplete, and probably buggy.
I will be updating it....

It can burn DVD's, CD's, make Disk Images
You may check mine scripts/wrapers for burning CD/DVD:
http://daemonforums.org/showthread.php?t=126

chalbersma
January 14th, 2009, 17:42
If you use Torsmo and have used any of tight configuration scripts lying around the web you've probably relized that the standard .torsmo_ip script used doesn't give you and ip address. Well there are many reasons for this but this will let you get it.


#!/bin/sh
# Torsmo IP config file
# Replace "dc0" with the name of your network connection
# chris@beastie.westminster-mo.edu
/sbin/ifconfig dc0 | awk '/inet / {split($2, x, / /); printf "%s", x[1]; exit;}'


Drop me an email if it doesn't work

vermaden
January 14th, 2009, 18:06
A script that will make a screenshot @ FreeBSD/OpenSolaris/Linux OS:


#! /bin/sh

DATE=$( date +%Y.%m.%d_%H:%M:%S )
APPS="scrot imlib2_grab import"
DIR=~/gfx/screenshots
FILE=${DIR}/vermaden_${DATE}.png

[ ${#} -ne 0 ] && FILE="${@}"

for I in ${APPS}
do
which ${I} 1> /dev/null 2> /dev/null && {
SHOT=${I}
break
}
done

[ -z $SHOT ] && {
echo "ER: no screenshot application in \$PATH"
echo "IN: provide one of [ scrot | import | imlib2_grab ] into your \$PATH"
exit 1
}

mkdir -p ${DIR} || {
echo "ER: cannot create ${DIR} dir"
exit 1
}

case ${SHOT} in
(import) import -display :0.0 -window root ${FILE} ;;
(*) ${SHOT} ${FILE} ;;
esac

paulfrottawa
February 21st, 2009, 05:41
It would be useful to have a copy button to lift some scripts. Just a thought

graudeejs
February 21st, 2009, 08:26
It would be useful to have a copy button to lift some scripts. Just a thought
open editor, select text in forum with mouse, push midle mouse button in text editor

or select text in forum Ctrl+C open editor, Ctrl+V

save script.... that's it

ivand58
March 19th, 2009, 20:33
Some backup tools have problems with long names. So we have to check the length of the path + file name. This can be done with:
find . -type f -exec sh -c 'echo -n \"$@\"\, ; echo -n $@ | wc -c' x {} \; | awk -F \, '{ printf "%s %s", $2, $1 "\n" }' | sort |tail

t4z3v4r3d
March 26th, 2009, 09:00
Some of people want to ping some hosts and find which host is up



#! /usr/local/bin/bash
clear

da="`date`"
range=${1}
ttl=${2}
count=${3}
sub=$4
us="`id -u`"
if [ $us != "0" ];then
echo "SORRY U MUST BE ROOT"
exit
fi

alive="/usr/home/t4z3v4r3d/alive.txt"
if [ "${#}" != 4 ] ; then
echo "EXAMPLE ${0} 127.0.0.1 2 1"
echo -e "TARGET IP Count TTL Subrange \n 127.0.0 1 1 254"
exit 0
fi

if test -f $alive ;then
echo -en "\033[1;32mFile OK Startting with PID:$$ \033[0;0m"
else
echo "$alive Not found creating it"
touch $alive
fi

#############################
## Chekc state for nom of tarets
for ((i=1 ; i < 100000 ; i++));do
if [ "`cat $alive | grep "\["$i"\]"`" != "" ];then
let "i=i+1"

else
let "i=$i-1"
echo "starting target nom form $i "
break
fi
done

#############################
line=2
ln=2
sb=0
pinger(){
while [ "$sb" -le "$sub" ];do
for ((counter=1 ; counter < 254 ;counter++));do
if [ "`ping -c $count -t $ttl $range.$sb.$counter | grep icmp_seq= `" != "" ];then
let "j=j+1"
let "ln=$j+2"
let "line=$j+2"
let "k=$i+$j-1"
let "a=a+1"
echo -e "\033[1;37m\033[3;2f[+]$range.$sb.$counter Alive [\033[1;32m$a\033[1;37m]\033[0;0m"
target[$k]=$range.$sb.$counter # >> $alive
else
let "d=d+1"
echo -e "\033[4;2f\033[1;31m[+]$range.$sb.$counter Dead [$d]\033[0;0m"
fi
done
let "sb=$sb+1"
done
echo -e "\033[4;1f.............................................. .................\033[0;0m"

}
## END SUB RANGE AND IP
chmod 666 $alive
pinger
let "l=$j+0"
if [ "$l" != "0" ];then
case $j in
0) some="No Target"
;;
1) some=" $j Taregt"
;;
*) some=" $j Targets "
;;
esac

echo "Scanning done and $some founded"

som1=0
while [ "$som1" -le "$j" ];do
echo -e "\033[1;37m${target[$som1]}\033[0;0m"
let "som1=som1+1"
done

else
echo "Cant find any target or pinging faild !"
fi

graudeejs
April 8th, 2009, 18:48
Here's script that i use to backup my FreeBSD to flash :D
you must have root permissions to run it.
you need flash or other unmounted drive with ufs on it labeled backup

to backup run
sudo backup.sh --backup all
or
sudo backup.sh --backup usr var
your partitions must be labeled, because this script uses only labels created with newfs -L label

Using partition labels has a lot of advantages.

it will save compressed dump images to /tmp, so it must be big enough.

for me it takes up to 1.8GB per download.
It compresses on the fly

modify DEFAULT_BAK_FS to match out ufs labels



#!/bin/sh


DEFAULT_BAK_FS='root var home www usr'


if [ "$USER" = 'root' ]; then
if [ -c /dev/ufs/backup ]; then

if [ "$1" = '--backup' ]; then
echo '*** starting backup ***'
echo

mkdir "/tmp/$(basename $0).$$"

echo '*** saving kernel configuration ***'
cat /usr/src/sys/i386/conf/killabsd | bzip2 > "/tmp/$(basename $0).$$/killabsd.bz2"

if [ "$2" = 'all' ]; then
for i in $DEFAULT_BAK_FS; do
echo "*** dumping $i ***"
dump -0Laf - "/dev/ufs/$i" | gzip > "/tmp/$(basename $0).$$/$i.dump.gz"
shift
done
else
while [ $2 ]; do
echo "*** dumping $2 ***"
dump -0Laf - "/dev/ufs/$2" | gzip > "/tmp/$(basename $0).$$/$2.dump.gz"
shift
done
fi

bakDate="$(date '+%Y-%m-%d')"

echo '*** Mounting ks86backup ***'
mount -o noatime /dev/ufs/backup /mnt

echo '*** Saving Backups ***'
if [ ! -d '/mnt/bak' ]; then mkdir '/mnt/bak'; fi

if [ ! -d "/mnt/bak/$bakDate" ]; then rm -Rf "/mnt/bak/$bakDate"; fi
mkdir "/mnt/bak/$bakDate"

cp "/tmp/$(basename $0).$$/"* "/mnt/bak/$bakDate/"

umount /mnt
echo '*** ks86backup unmounted ***'

echo '*** cleaning tmp ***'
rm -Rf "/tmp/$(basename $0).$$"
echo "*** backup $bakDate compleate ***"
exit 0
elif [ "$1" = '--restore' ]; then
echo 'not implemented yet'
exit 1
else
echo 'Err: unknown command'
exit 1
fi
else
echo "Err: backup drive ain't plugged"
exit 1
fi
else
echo "Err: you're not root"
exit 1
fi

echo "Err: you shouldn't naturally see this. A bug is somwhere."
exit 1

t4z3v4r3d
April 10th, 2009, 14:04
#!/usr/local/bin/bash
clear
echo "Looking for mountable devices"
if [ "`ls -c /dev/da* | grep s`" = "" ] ;then
echo -e "\033[1;31mNo such device for mounting\033[0;0m"
exit
fi

for (( count =0; count <5 ;count++ ));do
for ((counter=1 ;counter <7;counter++ ));do
if [ -c "/dev/da""$count"s"$counter" ];then
if [ ! -d /mnt/usb${count}-$counter ];then
echo "/mnt/usb${count}-$counter NOT EXITS CREATING IT ..."
mkdir /mnt/usb${count}-$counter
chmod -R 777 /mnt/usb${count}-$counter
chmod 666 /dev/da${count}s${counter}
fi
mount_msdosfs /dev/da${count}s${counter} /mnt/usb${count}-${counter}
fi
done
done
echo "_________________________________________"
echo
mount -p -w | grep da
echo "_________________________________________"


Only run this script and you can mount your storage with write permission in X.

graudeejs
April 10th, 2009, 14:15
#!/usr/local/bin/bash
clear
echo "Looking for mountable devices"
if [ "`ls -c /dev/da* | grep s`" = "" ] ;then
echo -e "\033[1;31mNo such device for mounting\033[0;0m"
exit
fi

for (( count =0; count <5 ;count++ ));do
for ((counter=1 ;counter <7;counter++ ));do
if [ -c "/dev/da""$count"s"$counter" ];then
if [ ! -d /mnt/usb${count}-$counter ];then
echo "/mnt/usb${count}-$counter NOT EXITS CREATING IT ..."
mkdir /mnt/usb${count}-$counter
chmod -R 777 /mnt/usb${count}-$counter
chmod 666 /dev/da${count}s${counter}
fi
mount_msdosfs /dev/da${count}s${counter} /mnt/usb${count}-${counter}
fi
done
done
echo "_________________________________________"
echo
mount -p -w | grep da
echo "_________________________________________"


Only run this script and you can mount your storage with write permission in X.

add to /etc/devfs.rules

[localrules=10]
add path 'da*' mode 0660 group users
add path 'md*' mode 0660 group users


add to /etc/devfs.conf

own acd0 root:users
perm acd0 0660

own cd0 root:users
perm cd0 0660

own mdctl root:users
perm mdctl 0660

own pass0 root:users
perm pass0 0660


add to /etc/rc.conf

devfs_system_ruleset="localrules"



do steps described above and you won't need to chmod devices anymore
also to mount msdosfs all you need to do, is create dir (for example ~/mnt)
and
mount -t msdosfs /dev/da0 ~/mnt
and you can read/write etc


p.s.
for more info about cd's/dvd's check
http://forums.freebsd.org/showthread.php?t=1195

t4z3v4r3d
April 12th, 2009, 08:45
Ok thank you but iwrote this scripts 2 years ago for training ;)
But thank you again . And i wanna lowest changes !.
Sorry for poor english

MG
August 17th, 2009, 00:59
Not really useful, but nostalgic:


#!/bin/sh

# Edit UNIX text files with old MSDOS editor
# Requires: - Dosbox installed
# - DOS binary EDIT.COM
# - X

EDITOR_BIN=/usr/files/EDIT.COM # fix your path
CURDIR=$(pwd)

mkdir -p /tmp/dostmp
ln -s $EDITOR_BIN /tmp/dostmp/edit.com

if [ $1 ];
then
cp $1 /tmp/dostmp/EDIT.TMP
cd /tmp/dostmp
dosbox -c "@mount c ." -c "@c:" -c "@c:\edit c:\EDIT.TMP" -c "@exit"
cd $CURDIR
(cat /tmp/dostmp/EDIT.TMP | tr -d '\015') > $1 #remove carriage returns
rm /tmp/dostmp/EDIT.TMP
else
cd /tmp/dostmp
dosbox -c "@mount c ." -c "@c:" -c "@c:\edit" -c "@exit"
fi

cd /tmp/dostmp
rm ./edit.com

# in case more files are saved:
# (these will get XXXXXXXX.XXX DOS-filenames)
for REST in *;
do
if [ -f $REST ];
then
(cat $REST | tr -d '\015') > $CURDIR/$REST
fi
done

rm -rf /tmp/dostmp


Use at own risk :beergrin

copypaiste
August 17th, 2009, 14:15
If you're an owner of a digital camera and like to fiddle with those JPEG files in your console as often as I do :P then this lil' piece of a shell-script of mine would be useful for you.
It provides batch changing the date/time of given JPEG files according to their EXIF values.



#!/bin/sh
#
# redate.sh
#----------------------------------------------------------------------
# This script changes modification and access time of the files
# in the current folder, according to the EXIF metadata found inside.
#
# No changes will be made in case no EXIF data could be found.
#
# Also it drops file permissions to 0640 mode
#
# Please be sure to have graphics/exiftags port installed before use.
#---------------------------------------------------------------------

exts="*.jpg *.jpeg *.JPG *.JPEG"
mask="0640"
exifcmd="/usr/local/bin/exiftags"
msg="Searching for ${exts} files..."




# Check for exiftags binary presense:
/usr/bin/which exiftags

if [ $? -ne 0 ]
then
printf "\n -> graphics/exiftags is not found in ${exifcmd}\n\n"
exit 1
else
printf "\n -> found exiftags binary (Ok!)"
fi




if [ $1 ]
then
exts=$1
msg="Searching for ${exts} files..."
fi


files=0
changed=0
failed=0

printf "\n${msg}\n"

for n in `ls ${exts} 2> /dev/null`

do

files=$((${files}+1))

exifd=`${exifcmd} ${n} 2> /dev/null | grep Created`


if [ "${exifd}" ]
then

exd=`echo ${exifd} | cut -d ' ' -f 3`

y=`echo ${exd} | cut -d ':' -f 1`
m=`echo ${exd} | cut -d ':' -f 2`
d=`echo ${exd} | cut -d ':' -f 3`

t=`echo ${exifd} | cut -d ' ' -f 4`

hr=`echo ${t} | cut -d ':' -f 1`
min=`echo ${t} | cut -d ':' -f 2`
sec=`echo ${t} | cut -d ':' -f 3`

printf "\n=> File: ${n} -> Exif Date: ${y}:${m}:${d} - Time: ${hr}:${min}:${sec} -> Set."

touchd="${y}${m}${d}${hr}${min}.${sec}"

touch -c -t ${touchd} ${n}

if [ $? -eq 0 ]
then
chmod ${mask} ${n}
changed=$((${changed}+1))
fi
else
{
printf "\n=> (!) File: ${n} -> No EXIF data -> Skipped."

failed=`echo "${failed}+1" | bc`
}
fi

done

echo
echo " -----------------------------------"
printf "Files processed: $files \n"
printf "Successfully set: $changed \n"
printf "Failed: $failed \n"
echo

exit 0

vermaden
August 18th, 2009, 11:47
usage: loop.sh image.iso /mnt/point

#! /bin/sh

[ ${#} -ne 2 ] && {
echo "usage: $( basename ${0} ) image.iso /mnt/point"
exit 1
}

__absolute() {
if [ -f /${1} ]
then
echo "${1}"
else
echo "$( pwd )/${1}"
fi
}

case $( uname ) in
(FreeBSD)
NODE=$( mdconfig -a -t vnode -f "${1}" )
mount -t cd9660 /dev/${NODE} "${2}"
;;

(SunOS)
FILE=$( __absolute "${1}" )
POINT=$( __absolute "${2}" )
lofiadm -d "${FILE}" 1> /dev/null
NODE=$( lofiadm -a "${FILE}" )
mount -F hsfs -o ro ${NODE} "${POINT}"
;;

(Linux)
mount -o loop "${1}" "${2}"
;;

(*)
echo "supported systems: FreeBSD Solaris Linux"
exit 1
;;
esac

graudeejs
September 1st, 2009, 10:39
#!/bin/sh
# Copyright (c) 2009, Aldis Berjoza <killasmurf86@gmail.com>
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following disclaimer
# in the documentation and/or other materials provided with the
# distribution.
# * Neither the name of the nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

# This scrip will create 'wlist' file, that will contain IP of all
# ftp servers found in ports collection
# You may use this script to generate ftp server whitlist for pf
#
# http://killasmurf86.blogspot.com

find /usr/ports -name Makefile > /tmp/.ftp_list_1
find /usr/ports/Mk -name bsd.*.mk >> /tmp/.ftp_list_1

for i in `cat /tmp/.ftp_list_1`; do
grep -e 'ftp://' $i >> /tmp/.ftp_list_2
done

sed 's/#.*$//g' /tmp/.ftp_list_2 | sed 's/^.*ftp:\/\///' | sed 's/\/.*$//' | sort | uniq - /tmp/.ftp_list_3

grep -E -e '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}' /tmp/.ftp_list_3 > /tmp/.ftp_list_4

for i in `cat /tmp/.ftp_list_3`; do
dig +short "$i" | grep -E -e '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}' >> /tmp/.ftp_list_4
done

sort /tmp/.ftp_list_4 | uniq - wlist
rm -f /tmp/.ftp_list_[1234]

exit

Here's script, I just wrote to generate ftp server white list used in ports.
I use generated list in my pf configuration, to enable ftp downloads

EDIT:
latest version can be downloaded from
http://aldis.git.bsdroot.lv/ftpwlist/

DutchDaemon
September 1st, 2009, 12:14
My 'portupdater' script for daily use. Requires ports-mgmt/portmaster and ports-mgmt/portaudit.

The script can be run from cron, which will invoke portsnap with a random sleep period of 0-60 minutes and does not require any intervention. It mails a summary to e.g. root.

It can also be run from the command-line when an extra argument is supplied (e.g. portupdater yes or portupdater now). This will make it run immediately, and with some extra functions that may require interaction.

The script will only update/maintain the ports tree and show a summary, it will not update ports. The ports that need updating are printed, of course.

The script can be made to work with ports-mgmt/portupgrade by just replacing the applicable commands. In fact, this script used to be portupgrade-based before I switched to portmaster.
#!/bin/sh
hostname=$(hostname)
date=$(/bin/date)

echo "
Updating portaudit first.
"
/usr/local/etc/periodic/security/410.portaudit

echo "
Portupdater for ${hostname} started at ${date}


========== Fetching latest ports snapshot from server. ==================
"

if [ $# -lt 1 ]
then
portvar="cron"
else
portvar="fetch"
fi

/usr/sbin/portsnap ${portvar} || exit 1

echo "
========== Updating ports tree with new snapshot. =======================
"
/usr/sbin/portsnap update || exit 1

echo "
============ Cleaning out all obsolete distfiles. =======================
"
/usr/local/sbin/portmaster -y --clean-distfiles || exit 1

if [ ${portvar} = "fetch" ]
then
echo "
Ah, you're actually here. Good.

Running some (possibly) interactive stuff.
"
/bin/sleep 5

echo "
============ Cleaning out stale ports. ==================================
"
/usr/local/sbin/portmaster -s || exit 1
echo "
============ Checking port dependencies. ================================
"
/usr/local/sbin/portmaster --check-depends || exit 1
echo "
============ Cleaning up /var/db/ports. =================================
"
/usr/local/sbin/portmaster --check-port-dbdir || exit 1
fi

echo "
=================== See which ports need updating. ======================
"
/usr/sbin/pkg_version -IvL '=' || exit 1

echo "
================= Warnings from /usr/ports/UPDATING. ====================
"
weekago=$( /bin/date -v-1w +%Y%m%d )
lastpkg=$( ls -D %Y%m%d -ltr /var/db/pkg | /usr/bin/tail -n1 | /usr/bin/tr -s " " "\t" | /usr/bin/cut -f 6 )
if [ ${weekago} -lt ${lastpkg} ]
then usedate=${weekago}
else usedate=${lastpkg}
fi
/usr/sbin/pkg_updating -d ${usedate}
echo "
See /usr/ports/UPDATING for further details.

========== Portupdater done. ============================================
"

bigearsbilly
September 28th, 2009, 19:14
how a bout this? convert code to a pretty html page
if you have gvim with syntax highlighting

gvim -c TOhtml -c w -c q -c q source_file

bigearsbilly
September 28th, 2009, 19:17
killasmurf...

dontcha just hate it when your license is longer than your script?
:)

I remember the good old days when one would put useful info at the
top of source files!

graudeejs
September 28th, 2009, 19:25
Well AT&T used to put their license on false program

And all it did was return 1


If you want I can make special edition for you.... I can make that script take more lines than license ;)

t4z3v4r3d
September 29th, 2009, 10:18
Hi
and a script for cvsup ...



#!/usr/local/bin/bash
clear
echo -e "\033[1;30mGetting fastest server adress\n\033[1;33mPlease wait ...\033[0;0m"
fastest_cvsup -c all >> /tmp/1
tail -n 3 /tmp/1 > /tmp/fs_cvs
echo -e "\033[1;32mGetting informations Done ...\nStarting update\033[0;0m"

cat << config > /root/stable_supfile.txt
################################################## #################
##### Generated by $USER @ `date` ######
################################################## #################
$(cat /tmp/fs_cvs | while read line ;do echo *default host=$(echo $line | awk {' print $3 '}); done)
*default base=/var/db
*default prefix=/usr
*default release=cvs tag=RELENG_$(uname -r | cut -d . -f 1)_$(uname -r | cut -d . -f2 | cut -d - -f 1)
*default delete use-rel-suffix
*default compress
src-all
config
cvsup -g -L 2 /root/stable_supfile.txt

nimnod
October 14th, 2009, 08:32
If you want to block known spam sources on your MX right at the firewall, not even bothering you MTA to check the incoming IPs you can use this script to put together a list of IPs to block.

Watch out: The script reloads your pf rules.
You should put:

table <spam.zen> persist file "/etc/spam.zen"
(...)

block quick inet from <spam.zen>

into your pf.conf for the whole thing to work.


#!/bin/sh

fetch -q -o /tmp/zendrop.data http://www.spamhaus.org/drop/drop.lasso

cat /tmp/zendrop.data | sed -e 's/;.*//' > /tmp/spam.zen
rm /tmp/zendrop.data
MD1=`md5 -q /tmp/spam.zen`
if [ -f /etc/spam.zen ]; then
MD2=`md5 -q /etc/spam.zen`
else
MD2="nof"
fi

echo $MD1 | grep "$MD2" > /dev/null
if [ $? -eq 1 ]; then
echo "New file: /tmp/spam.zen"
sleep .5
more /tmp/spam.zen
echo -n "Do you want to replace previous version of /etc/spam.zen ? yes/[no]: "
read reload
echo $reload | grep yes > /dev/null
if [ $? -eq 0 ]; then
# yes
mv /tmp/spam.zen /etc/
pfctl -qf /etc/pf.conf
echo "Your ZENDROP list has been updated."
else
# no
echo "Your ZENDROP list has not been updated."
fi
else
rm /tmp/spam.zen
echo "Your ZENDROP list is up-to-date."
fi

t4z3v4r3d
November 3rd, 2009, 09:03
Hi there.
Anybody has script for network monitoring ? such as BW monitor !

vermaden
November 3rd, 2009, 12:14
@t4z3v4r3d

Have you tried this:
systat -if 1

t4z3v4r3d
November 3rd, 2009, 19:15
Thank you .
Not yet but ill try .

anomie
November 3rd, 2009, 23:22
Save yourself from mistyping during jail creation

Runs through the basic jail creation steps, as described in jail. The idea is it helps you avoid changing the path by mistake on one of the steps or doing something else silly. (Requires that you've built world on your base system first.)

#!/bin/sh

#
# Very simple - feed it jpath and let it create / mount for you.
#
_jpath=/home/jail/basicjail

myprompt() {

echo "Step finished. Return code: ${_rc}"
echo '<press enter>'
read _foo

}

echo 'Creating jail path...'
mkdir -p ${_jpath}
_rc=${?} ; myprompt

echo 'Installing world to jail...'
cd /usr/src && make installworld DESTDIR=${_jpath}
_rc=${?} ; myprompt

echo 'Making distribution in jail...'
cd /usr/src && make distribution DESTDIR=${_jpath}
_rc=${?} ; myprompt

echo 'Mounting devfs for jail...'
mount_devfs devfs ${_jpath}/dev
_rc=${?} ; myprompt

exit 0

------------------------------

Automating the aide HIDS

Requires the security/aide and security/gnupg1 ports. After initializing (and signing!) your aide db, set up a root cronjob that runs this daily with the "check" argument.

#!/bin/sh

### Variable assignments ### ---------------------------------------------------

PATH=/bin:/usr/bin:/usr/local/bin
DB=/var/db/aide/databases/aide.db

### Functions ### --------------------------------------------------------------

init_aide_db() {

aide -i

if [ ${?} -ne 0 ] ; then
echo 'Initializing new db failed. Exiting now.'
exit 1
fi

echo "Finished initializing db. When ready to implement and sign the db,"
echo "please run: ${0} goprod"

}

implement_and_sign_db() {

echo 'Moving newly initialized db to production db...'
mv ${DB}.new ${DB}

if [ ${?} -ne 0 ] ; then
echo 'Unable to copy new db to prod. Exiting now.'
exit 1
fi

echo 'Signing db with GNUPG - password required...'
gpg -u 'System Admin' --detach-sign ${DB}

}

run_aide_check() {

# check signature
gpg --verify ${DB}.sig ${DB}

if [ ${?} -ne 0 ] ; then
echo "Signature check against ${DB} failed!!!"
exit 1
fi


aide -C

if [ ${?} -ne 0 ] ; then
init_aide_db
fi

}


### Main logic ### -------------------------------------------------------------

case "${1}" in

'init' ) init_aide_db ;;
'goprod' ) implement_and_sign_db ;;
'check' ) run_aide_check ;;
* ) echo "Usage: ${0} (init|goprod|check)" ; exit 1 ;;

esac


exit 0

------------------------------

See the most common squid proxy TCP denied hosts

I like to check in every now and then on which hosts end users are trying to access (and getting denied). This provides a quick, sorted list. Obviously requires an actively used www/squid service.

#!/bin/sh

# ----------------------------------------------
# Quick audit
# ----------------------------------------------

if [ ! -e "${1}" ] ; then
echo "Usage: ${0} squid_access_log"
exit 1
fi

_acheck=`echo ${1} | grep 'access.log'`

if [ -z "${_acheck}" ] ; then
echo "${0}: my author told me to only scan 'access.log' type files"
exit 1
fi

# ----------------------------------------------
# Variable assignment
# ----------------------------------------------

_squidlog=${1}
_of1=/tmp/tcp-squid-baz.txt
_of2=/tmp/tcp-squid-boo.txt


# ----------------------------------------------
# Main logic
# ----------------------------------------------

grep 'TCP_DENIED' ${_squidlog} | awk '{print $7}' | sort > ${_of1}

if [ ${?} -ne 0 ] ; then
echo "${0}: error during grep"
exit 1
fi

for I in `uniq ${_of1}` ; do

_cnt=`grep "${I}" ${_of1} | wc -l`
echo "${_cnt} : ${I}" >> ${_of2}

done

#
# Display results
#
sort -nr ${_of2}

#
# Cleanup
#
rm -f ${_of1} ${_of2}

exit 0

idle
November 7th, 2009, 22:21
Anti-ddos. Script for getting bots ips from httpd/nginx/etc log.
#!/usr/bin/perl -w

use strict;
use warnings;
use POSIX qw(strftime);

my $pattern = "\"GET \/ HTTP\/"; # request index page pattern
my $httpd_log = "/var/log/httpd-access.log"; # log file
my $ok = "1000"; # allowed connections per ip for $check_period
my $check_period = 1; # check period in hours

my $date = strftime("%d/%b/%Y:%H", localtime(time-$check_period*3600)); # date minus $check_period hours
my (%ips, $ip, $start);

open (LOG, $httpd_log) or die $!;
while (<LOG>) {
next unless m/$date/ || $start; # skipping old records
$start=1;
if (/^(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}).*$pattern/go) { # getting ips
$ips{$1}++;
}
}
close LOG;

foreach $ip (keys %ips) {
if ($ips{$ip} >= $ok) { #
next if $ip =~ /^127/; # skip local address
print "$ip = $ips{$ip}\n"; next; # comment out this line if you want to modify firewall rules and uncomment one of the following
#system("/sbin/pfctl -t bots -T add $ip"); # adding address to table <bots>
#system("/sbin/ipfw table 5 add $ip"); # adding address to table 5
#system("/sbin/iptables -A INPUT -s $ip -j REJECT"); # adding denying rule
}
}
The shortest way to generate the random password. The slowest, also. =)
egrep -aoim1 '[a-z0-9]{8,}' /dev/random

pat
November 8th, 2009, 05:37
I have a patchset against /usr/src (mostly low priority PRs waiting for approval) arranged in an overlay. This little function takes care of applying the patches after an update of src:

overlay="/home/pat/Projects/patchset"
find "${overlay}/usr/src/" -type f | \
while read patchfile; do \
srcdir=$(dirname ${patchfile});
srcdir=${srcdir##$overlay};
cd ${srcdir} && sudo patch < ${patchfile};
done

MG
November 14th, 2009, 21:52
#!/usr/local/bin/bash

# turns a text-file into keyboard-controlled menu (basic example)
# use <UP> and <DOWN> arrows to choose, <RETURN> to confirm, <ESC> to abort
# scrolling is nog supported yet, so the menu may not contain more lines than your terminal screen

if [ ! -f "$1" ]
then
printf "need input file\n"
exit
fi

OLDIFS=$IFS
NOCOLOR='\033[0m'
YELLOW='\033[1;33;40m'
CHOICE=1
LASTLINE=$(cat $1 | wc -l)
UP=$'\x1b[A'
DOWN=$'\x1b[B'
KEY=''
ASCII=""
ESC=""
END=0

function xy # cursor positioning
{
printf "\033[$2;$1f"
}

printf "\x1B[?25l" # hide terminal cursor
clear
cat $1

while [ $END = 0 ]
do
xy 0 $CHOICE
printf $YELLOW
cat $1 | head -n $CHOICE | tail -n 1 # highlight current option
IFS='' # don't convert any read chars to whitespace
read -s -n1 KEY
IFS=$OLDIFS
ASCII=$(printf "%d" "'$KEY'") # store ascii value of key

if [ "$ASCII" = "27" ] # function key processing
then
read -t0.1 -s -n2 ESC # store 2 more bytes containing the escape code
xy 0 $CHOICE
printf $NOCOLOR # remove highlighting
cat $1 | head -n $CHOICE | tail -n 1

if [ "$ESC" = "" ] # <ESC>
then
END=1
else
case $ESC in
"[A") # <UP>
if [ $CHOICE = 1 ]
then
CHOICE=$LASTLINE
else
(( CHOICE-=1 ))
fi
;;
"[B") # <DOWN>
if [ $CHOICE = $LASTLINE ]
then
CHOICE=1
else
(( CHOICE+=1 ))
fi
;;
esac
fi
fi

if [ $ASCII = 39 ] && [ "$KEY" != "'" ] # <RETURN>
then
xy 0 $(( $LASTLINE + 2 ))
printf "${NOCOLOR}you have chosen option $CHOICE:\n $(cat $1 | head -n $CHOICE | tail -n 1)\n\n"
END=1
fi

MG
November 16th, 2009, 20:16
#!/usr/local/bin/bash

if [ ! -f "$1" ]; then
(
(cat|cut -c5-) << EOF
.................................................. .................
txt2menu.sh - turn a textfile into a keyboard-controlled menu
1.1 (improved with pgup/pgdown and positioning/scrolling support)
.................................................. .................
start with:
#txt2menu.sh [file] [#line] [#column] [#width] [#height]
'line' and 'column' are the coords. of the upper left
corner of the menu box
run without parameters to view this example menu or use custom
file with default pos/size:
#txt2menu.sh /etc/motd
or with filename and 4 pos/size parameters:
#txt2menu.sh /etc/motd 10 10 50 20
.................................................. .................
menu control keys: <UP>,<DOWN>,<PGUP>,<PGDOWN>,<ESCAPE>,<RETURN>
exit code contains users choice or 0 when aborted
.................................................. .................
EOF
) > /tmp/demo.tmp
printf "\n\n\n\n\n\n\n\n\n\n\n\n\n\nthis is freeware\nby MG\n" >> /tmp/demo.tmp
CONTENT=/tmp/demo.tmp
else
CONTENT=$1
fi

stty -echo

CLEAR=1 # set to 0 to run over existing terminal content.
HEIGHT=18
WIDTH=70
COLUMN=5
LINE=3
OLDIFS=$IFS
NOCOLOR='\033[0m'
YELLOW='\033[1;33;40m'
CHOICE=1
LASTLINE=$(cat $CONTENT | wc -l)
KEY=''
ASCII=""
ESC_CODE=""
END=0
STARTLINE=1

if [ "$2" != "" ]; then LINE=$2; fi
if [ "$3" != "" ]; then COLUMN=$3; fi
if [ "$4" != "" ]; then WIDTH=$4; fi
if [ "$5" != "" ]; then HEIGHT=$5; fi
if [ $LASTLINE -lt $HEIGHT ]; then HEIGHT=$LASTLINE; fi
if [ $CLEAR = 1 ]; then clear; fi
function cur_xy {
printf "\033[$2;$1f"
}

function printmenu {
sed -n "${STARTLINE},$((STARTLINE+HEIGHT-1))p" $1 | awk '{
printf $0
width="'"$WIDTH"'"-length($0);
for (i=1; i<=int(width); i++) printf "^";
print ""
}'
}

function out_at_xy {
(
COL=$1
LINE=$2
shift
shift
while [ "$1" != "" ]; do
printf "\033[$LINE;${COL}f"
printf "$1"
shift
(( LINE+=1 ))
done
) | tr '^' ' '
}

printf "\x1B[?25l" # hide cursor
out_at_xy $COLUMN $LINE $(printmenu $CONTENT | tr ' ' '^')

while [ $END = 0 ]; do
printf $YELLOW
cur_xy $COLUMN $((LINE+(CHOICE-STARTLINE)))
ACTIVE_LINE=$(head -n$CHOICE $CONTENT | tail -n1)

if [ "$ACTIVE_LINE" != "" ]; then
printf "$ACTIVE_LINE"
else
printf "o"
fi
IFS=''
read -s -n1 KEY
IFS=$OLDIFS
ASCII=$(printf "%d" "'$KEY'")
if [ "$ASCII" = "27" ]; then
read -t0.0001 -s -n2 ESC_CODE
printf $NOCOLOR
cur_xy $COLUMN $((LINE+(CHOICE-STARTLINE)))

if [ "$ACTIVE_LINE" != "" ]; then
printf "$ACTIVE_LINE"
else
printf "."
fi

if [ "$ESC_CODE" = "" ]; then # just <ESCAPE>
END=1
else
case $ESC_CODE in
"[A") # <UP>
(( CHOICE-=1 ))
if [ $CHOICE -lt $STARTLINE ]; then
if [ $CHOICE -lt 1 ]; then
CHOICE=1
else
(( STARTLINE-=1 ))
out_at_xy $COLUMN $LINE $(printmenu $CONTENT | tr ' ' '^')
fi
fi
;;
"[B") # <DOWN>
(( CHOICE+=1 ))
if [ $CHOICE -gt $LASTLINE ]; then
CHOICE=$LASTLINE
fi
if [ $CHOICE -gt $((STARTLINE+HEIGHT-1)) ]; then
(( STARTLINE+=1 ))
out_at_xy $COLUMN $LINE $(printmenu $CONTENT | tr ' ' '^')
fi
;;
"[5"|"[I") # <PGUP>
(( CHOICE-=25 ))
if [ $CHOICE -lt 1 ]; then
CHOICE=1
fi
if [ $CHOICE -lt $STARTLINE ]; then
STARTLINE=$CHOICE
if [ $STARTLINE -lt 1 ]; then
STARTLINE=1
fi
out_at_xy $COLUMN $LINE $(printmenu $CONTENT | tr ' ' '^')
fi
;;
"[6"|"[G") # <PGDOWN>
(( CHOICE+=25 ))
if [ $CHOICE -gt $LASTLINE ]; then
CHOICE=$LASTLINE
fi
if [ $CHOICE -gt $((STARTLINE+HEIGHT-1)) ]; then
STARTLINE=$((CHOICE-HEIGHT+1))
out_at_xy $COLUMN $LINE $(printmenu $CONTENT | tr ' ' '^')
fi
;;
esac
fi
fi
if [ $ASCII = 39 ] && [ "$KEY" != "'" ]; then # <RETURN>
END=1
fi
read -t0.0001 -s -n10 # don't remember more keys
done

printf "\x1B[?25h" # unhide cursor
cur_xy 0 $(( $LINE+$HEIGHT+3 ))
stty echo

if [ $ASCII = 27 ]; then # final result message, delete this for further use
printf "aborted.\n\n"
CHOICE=0
else
printf "${NOCOLOR}you have chosen option $CHOICE:\n$YELLOW$(cat $CONTENT | head -n $CHOICE | tail -n 1)$NOCOLOR\n\n"
fi

rm -rf /tmp/demo.tmp
exit $CHOICE

tangram
November 17th, 2009, 12:36
I have a patchset against /usr/src (mostly low priority PRs waiting for approval) arranged in an overlay. This little function takes care of applying the patches after an update of src:

overlay="/home/pat/Projects/patchset"
find "${overlay}/usr/src/" -type f | \
while read patchfile; do \
srcdir=$(dirname ${patchfile});
srcdir=${srcdir##$overlay};
cd ${srcdir} && sudo patch < ${patchfile};
done

Do you use this as a standalone script that you run before rebuilding your kernel or world? Or do place this on make.conf?

I'm asking this because I also apply 2 patches to /usr/src and wanted to reapply the patches whenever I synchronize sources.

graudeejs
November 18th, 2009, 01:00
#!/usr/bin/perl

use warnings;
use strict;
package wrapper;

if (defined $ARGV[0]) {
$ARGV[0] =~ s/%([[:xdigit:]]{2})/pack('c', hex($1))/ge;
if ($ARGV[0] =~ /^mailto:/) {
my $email;
my $subject;
if ($ARGV[0] =~ /\?subject=.*/) {
($email, $subject) = $ARGV[0] =~ /^mailto:(.*)\?subject=(.*)/;
# system("FvwmCommand \"Function Start_Mailer -s '$subject' -- '$email'\"");
system("urxvtc -e mutt -s '$subject' -- '$email'");
} else {
($email) = $ARGV[0] =~ /^mailto:(.*)/;
# system("FvwmCommand \"Function Start_Mailer -- '$email'\"");
system("urxvtc -e mutt -- '$email'");
}
}
elsif ($ARGV[0] =~ /^irc:\/\//) {
my $addr;
my $port;
($addr, $port) = $ARGV[0] =~ /^irc:\/\/(.*):\+(\d{1,5})/;
# system("FvwmCommand 'Function Start_chat --connect=$addr --port=$port '");
system("urxvtc -e irssi --connect=$addr --port=$port");
}
}
exit;


Here's my little wrapper scipt I just wrote.
I commented out original lines that I use (fvwm & my config specific) and replaced them with more generic lines

replace urxvtc with any terminal that you use.

you can use this wrapper with firefox. In Application preferences, where you can select default apps for various things, for mailto: and irc: you can select this wrapper script.
It will launch mutt or irssi in virtual terminal on X, when you click on link (either mailto:... or irc:...)

I think it's pretty useful.
Of course you can customize to use it for other email/irc clients, and even extend it's usage to IM....

Hope you like it ;)


P.S.
Thanks to SirDice (http://forums.freebsd.org/member.php?u=1677) for this post (http://forums.freebsd.org/showpost.php?p=49500&postcount=2)

EDIT:
one more thing... Why I like it?
Because If I have to reply to some pr, I don't have to fill to: and subject lines....
subject line was pain for me with previous wrapper


EDIT:
fixed bug

pat
November 18th, 2009, 07:30
Do you use this as a standalone script that you run before rebuilding your kernel or world? Or do place this on make.conf?

I'm asking this because I also apply 2 patches to /usr/src and wanted to reapply the patches whenever I synchronize sources.

Actually it's only a shell function (minus the header).
I would just love to see something like this properly implemented in make.conf.

Ruler2112
November 18th, 2009, 22:45
I'm cross-posting to this thread, as the script I wrote may well be of use to somebody for a different purpose. I intentionally wrote it to be as generic as possible. Basically, it will update a local file to that of a network copy, based on whatever you set the variables to. It'll also keep the n most recent backups of the file downloaded. You can see it as part of the 'Emerging Threats' thread (http://forums.freebsd.org/showpost.php?p=49726&postcount=23).

graudeejs
November 19th, 2009, 15:22
fixed bug in script
http://forums.freebsd.org/showpost.php?p=49504&postcount=52

ohauer
December 26th, 2009, 12:03
/usr/sbin/portsnap update || exit 1
cd /usr/ports || exit 1
make fetchindex || exit 1


Is there a special reason for

cd /usr/ports || exit 1
make fetchindex || exit 1

since portsnap has already updated the index file to match the current portsnap.

DutchDaemon
December 26th, 2009, 20:36
Yeah, that script has seen quite a few lifecycles and organic development (cvsup -> csup -> portsnap, portupgrade -> portmaster), and there may be some superfluous stuff in it. I'll give it a slight overhaul.

tuan
December 27th, 2009, 00:42
Hello,

I tried to reuse your script, and changed just one thing, but for some reason, my modification is not correct: I need to su on the remote machine before copying the keys, but when I enter the password for su, the remote machine does not accept it. Does anyone have an idea by chance ?

Your original script was :

#!bin/sh

HOSTS="host1 host2 host3"

KEYFILE=id_rsa # careful, change to not overwrite default!
PRVKEYFILE=~/.ssh/${KEYFILE}
PUBKEYFILE=${PRVKEYFILE}.pub
TMPKEY=${KEYFILE}.tmp

ssh-keygen -b 2048 -t rsa -f $PRVKEYFILE

for HOST in $HOSTS; do
echo $HOST ###
scp ${PUBKEYFILE} ${HOST}:~/${TMPKEY} && echo OK && \
ssh ${HOST} "cat ${TMPKEY} >> ~/.ssh/authorized_keys && rm ~/${TMPKEY}" && echo OK
done

and I just added (in bold) :

for HOST in $HOSTS; do
echo $HOST ###
scp ${PUBKEYFILE} ${HOST}:~/${TMPKEY} && echo OK && \
ssh ${HOST} "su" && echo OK && "cat ${TMPKEY} >> ~/.ssh/authorized_keys && rm ~/${TMPKEY}" && echo OK

Ruler2112
January 8th, 2010, 00:24
I just posted a script I wrote (http://forums.freebsd.org/showthread.php?t=10110) intended to be used by people who run mail servers to detect when somebody tries a brute-force method to guess passwords. Thought I should link it in here for completeness.

ta0kira
January 8th, 2010, 15:57
In bash I use alias recall='history | egrep' so that I can do something like recall ssh. Not sure if there's a build-in way to do that.
Kevin barry

DutchDaemon
January 8th, 2010, 16:04
In bash I use alias recall='history | egrep' so that I can do something like recall ssh. Not sure if there's a build-in way to do that.
Kevin barry

Bash has reverse history searching:

ctl-r ssh

will give you the last history entry containing 'ssh', and every subsequent ctl-r will give you the one before that.

ta0kira
January 8th, 2010, 16:20
Bash has reverse history searching:

ctl-r ssh

will give you the last history entry containing 'ssh', and every subsequent ctl-r will give you the one before that.Thanks. I use ! quite a bit, but I ssh to a lot of different places, calling a lot of different remote commands, so it's nice to see all of them at once.
Kevin Barry

graudeejs
January 11th, 2010, 22:47
I wrote this script to scan files MUCH faster....
It was inspired by one-liner that I wrote for my GF to scan 47 pages.
She scanned them in about 15 min

You can export files to different format, and set starting counter... Very useful if you scan more than 2 days same book for example

I think many of you will find this script very useful

#!/bin/sh

if [ "$1" = "--help" ]; then
cat << EOF
USAGE:
`basename $0` [file_format [start_page]]

WHERE:
file_format is any format supported by ImageMagick (default jpg)
start_page is used to set counter (default 0)
EOF
exit 0
fi

Format=${1:-"jpg"}
i=${2:-"0"}

while read -p 'Press Enter to scan. Press q and then Enter to stop ' a && [ "$a" != "q" ] && [ "$a" != "Q" ]; do
echo " Scanning..."
scanimage | convert - `printf "%0.3d.$Format" $i`
i=`expr $i + 1`
done

if [ "$Format" = "pdf" ]; then
echo "TIP: you can use print/pdftk to convert all scanned pdf's to singe file:"
echo " pdftk \`ls *.pdf\` output output_file_name.pdf"
fi

exit 0


EDIT
latest version available at
http://aldis.git.bsdroot.lv/scan/

Ruler2112
January 20th, 2010, 23:25
Just posted another script (http://forums.freebsd.org/showthread.php?t=10523) in the userland coding forum. This one will spawn a new shell for you in the directory of the port you pass as a parameter.

LeFroid
February 21st, 2010, 04:43
Heres a few simple scripts I wrote.

Heres a basic script to play any video in your ~/Videos dir

play.py

#!/usr/bin/env python

import sys
import os

# what to play the video with
player = "vlc"
# arguments, ex 'play "myvid.avi"'
video = sys.argv[1]
# home dir
home = os.path.expanduser('~')

# combine strings
execStr = player+" "+home+"/Videos/"+video
# run execStr
os.system(execStr)


this one is a simple c++ tool to install a port (as root). i'm still not good at c++ so this probably should be written better

you use it like "./port_tool MYPORT" as root

sysinfo.h (i copied this from somewhere)

#ifndef SYSINFO_H
#define SYSINFO_H

#define WINDOWS 0
#define BSD 1
#define APPLE 2
#define INTEL 3

#if defined( _WIN64 )
#define PLATFORM WINDOWS
#elif defined ( __WIN32__ ) || defined( WIN32 ) || defined( _WIN32 )
#define PLATFORM WINDOWS
#elif defined( __APPLE_CC__ )
#define PLATFORM APPLE
#elif defined( __INTEL_COMPILER )
#define PLATFORM INTEL
#else
#define PLATFORM BSD
#endif

#endif


ports.h

#ifndef PORTS_H
#define PORTS_H
#include <iostream>
using namespace std;

class Ports
{
public:
void SearchPort(string pName);
void InstallPort(string pName);
};
#endif


ports.cpp

#include "ports.h"
#include "sysinfo.h"

void Ports::SearchPort(string pName)
{
#if PLATFORM == BSD
string install;
cout << "Locations: " << endl;
string cmd = "/usr/bin/whereis " + pName;
system(cmd.c_str());
cout << "Would you like to install? (y/n) ";
cin >> install;
if ( install == "y"|| install == "Y" || install == "yes" || install == "YES
{
InstallPort(pName);
}else{
exit(EXIT_SUCCESS);
}
#else
cout << "What are you thinking??" << endl;
#endif
}

void Ports::InstallPort(string pName)
{
#if PLATFORM == BSD
string install = "cd /usr/ports/*/"+pName+" && make install clean";
system(install.c_str());
#else
cout << "Install FreeBSD!" << endl;
#endif
}

int main(int argc, char *argv[])
{
Ports pt;
if(argc < 2)
{
cout << "Usage: " << argv[0] << " PORTNAME" << endl;
}else{
cout << "NOTICE: must be root to install any ports" << endl;
string prog = argv[1];
pt.SearchPort(prog);
}
}

idle
March 9th, 2010, 14:57
this one is a simple c++ tool to install a port (as root). i'm still not good at c++ so this probably should be written better



That is a big one. :D

What is the difference from code below?


#!/bin/sh
make install clean -C /usr/ports/$1

LeFroid
March 10th, 2010, 04:54
That is a big one. :D

What is the difference from code below?


#!/bin/sh
make install clean -C /usr/ports/$1

I prefer c++ :P

sixtydoses
March 11th, 2010, 14:15
Scripts were inspired by DD's portupdater (http://forums.freebsd.org/showpost.php?p=39092&postcount=37) script. DD is using portmaster and am using portupgrade, hence the modification. Else I'd be more than happy just to use his original script. Probably one day I'll switch to portmaster and DD's original script will come in handy. Thanks much, Dutch.

Requires ports-mgmt/portupgrade, ports-mgmt/portaudit and x11/zenity (optional).

updatetree - Run as cronjob every night at 0300.
If portsnap is already running, portsnapcron will only update its compressed snapshot and the INDEX files. Applies the same if portupgrade or some other 'make' process is running. Else, portsnap will fetch and update the ports tree.

#!/bin/sh

hostname=$(hostname)
date=$(/bin/date)

echo "
Portupdater for ${hostname} started at ${date}
"

running=`/bin/ps auxww | /usr/bin/grep -E "portsnap|portupgrade|make" | /usr/bin/grep -v grep`


if [ -n "$running" ]
then
echo "
========== Fetching and update latest ports snapshot from server. ==================
"
portvar="-I cron update"
else
echo "
========== Fetching and update ports tree in ${hostname}. ==================
"
portvar="cron update"
fi

/usr/sbin/portsnap ${portvar} || exit 1


echo "
========== Portupdater done. ============================================
"




portupdater - Run as cronjob once a week at 0400.
Will run portaudit, portsclean, update the ports database and check which ports that need updating. I included a dialog box (x11/zenity) to display the number of ports that need updates and remind me to read /usr/ports/UPDATING because sometimes my fingers are faster than my brain..

#!/bin/sh

hostname=$(hostname)
date=$(/bin/date)


echo "
Updating portaudit first.
"
/usr/local/etc/periodic/security/410.portaudit


echo "
======================= Cleaning out all obsolete distfiles. =======================
"

/usr/local/sbin/portsclean -CDDLP || exit 1



echo "
======================= Update ports database file. =======================
"

/usr/local/sbin/portsdb -u || exit 1


echo "
======================= See which ports need updating. =======================
"

OIFS=$IFS
IFS='
'

oldports=$(/usr/local/sbin/portversion -vl '<')

count=0

for i in $oldports
do
count=`/bin/expr "$count" + 1`
echo $i
done

IFS=$OIFS


echo "
Number of ports need to be updated: $count.
"


echo "
======================= Warnings from /usr/ports/UPDATING. =======================
"

/usr/bin/grep -B 1 AFFECTS: /usr/ports/UPDATING | /usr/bin/head -20


echo "
See /usr/ports/UPDATING for further details.

============================== Portupdater done. ==============================
"

/usr/local/bin/odmsg ''"$count"' ports need updating. Read /usr/ports/UPDATING before upgrading.' & 2>/dev/null


./odmsg
I've always had this script in my box for quite sometime so that my remote user can get my attention by prompting me a message.
e.g.: odmsg 'Tada!'

#!/bin/sh


# Set up the Display
export DISPLAY=:0

# Wake up the screen because it has probably fallen asleep
/usr/local/bin/xset s off
/usr/local/bin/xset -dpms
/usr/local/bin/xset s reset
/usr/local/bin/xscreensaver-command -deactivate > /dev/null


/usr/local/bin/zenity --info --text="$1" 2>/dev/null &


# Allow the screensaver and power saving mode to take effect now that the message has been acknowledged.
/usr/local/bin/xset s on
/usr/local/bin/xset +dpms

Thorny
March 11th, 2010, 14:31
Hello,

i'm using the following script to update all jails after an major-update of the FreeBSD Host-System (for example after updating from version 7 to 8):
http://www.meisterderspiele.de/upgrade-jails-thorny.html

It's quite helpfull if you have a bunch of systems to update.

graudeejs
March 14th, 2010, 20:52
Here's script to make Really Big screenshots.
This can be used only in FVWM, you need to load FvwmCommandS module
This script will switch to each page and create screenshot, after I created screenshot of each page, it will merge them into one big screenshot, containing virtual desk.

Note don't confuse virtual pages with virtual desks :D
virtual pages are in virtual desks :)


#!/bin/sh

# this script will create screenshot of each virtual page in fvwm
# then it will merge them into one big jpg
# then it will switch to Sx Sy page and open screenshot with Start_viewer
# fvwm function
#
# this script requires fvwm module FvwmCommandS to be loaded
#
# To integrate in Fvwm, you can do something like this
#
# Exec exec $[FVWM_SCRIPTS]/RealBigScreenshot.sh $[desk.pagesx] $[desk.pagesy] $[page.nx] $[page.ny]

X=${1:-"1"} # page count X
Y=${2:-"1"} # page count Y
Sx=${3:-"0"} # from which pagex we ran this scipt
Sy=${4:-"0"} # from which pagey we ran this scipt

for y in `jot $Y 0`; do
for x in `jot $X 0`; do
FvwmCommand "GotoPage $x $y"
import -quality 95 -window root /tmp/$$_x${x}_y${y}.jpg
xnames="$xnames /tmp/$$_x${x}_y${y}.jpg"
done

convert +append $xnames /tmp/$$_y${y}.jpg
rm -f $xnames
xnames=""
ynames="$ynames /tmp/$$_y${y}.jpg"
done

if [ ! -d ${HOME}/pic/screenshots ]; then
mkdir -pf ${HOME}/pic/screenshots
fi

fileName="${HOME}/pic/screenshots/$(date '+%Y.%m.%d_at_%H.%M.%S')-RealBig.jpg"
convert -append $ynames $fileName
rm -f $ynames

FvwmCommand "GotoPage $Sx $Sy"

exec FvwmCommand "Function Start_viewer $fileName"

exit


here's example screenshot (Warning this jpg is 1.9MB)
http://www.failiem.lv/thumb.php?i=iwmzvq&n=2010.03.14_at_20.32.29-RealBig.jpg (http://www.failiem.lv/down.php?i=iwmzvq&n=2010.03.14_at_20.32.29-RealBig.jpg)


I needed this for my homework in databases :D
The database data in screenshot are all fake

EDIT:
latest script version can be found at
http://aldis.git.bsdroot.lv/fvwm-bluth/

rambetter
March 16th, 2010, 23:58
Hi, I have a couple of scripts that I'm proud of.

The first is similar to ``pkg_delete'', but it also performs a ``make rmconfig'' on the package you are removing. I call this script ``pkg_clean_delete'':

#!/bin/sh

if [ $# -ne 1 ]; then
echo "Exactly one argument must be specified" 1>&2
exit 1
fi
PACKAGE=$1
if [ -e "$PACKAGE" ]; then
echo "'$PACKAGE' is a file; avoid that" 1>&2
exit 1
fi
ORIGIN=`pkg_info -qo "$PACKAGE"`
if [ $? -ne 0 ]; then
exit 1
fi
if pkg_delete "$PACKAGE"; then
cd "/usr/ports/$ORIGIN"
make clean
make rmconfig
exit 0
fi
exit 1


I have another script that addresses a real problem I've had. My servers are in a data center, and for some reason, when I reboot my servers, it sometimes takes 60 seconds or so for the network to start working. I run ntpd on my servers. My /etc/ntp.conf file uses DNS names that need to be resolved to IP addresses when ntpd starts. The problem is that usually, the network is not working by the time ntpd starts, and ntpd cannot perform the DNS resolution. ntpd then gets into a funny state where two of its processes show up in ps, yet it never finishes resolving DNS, and never works. I need to shut down ntpd and then restart it after the system comes up in order for it to work.

To fix this issue, I wrote a script that waits for the network to become functional before continuing in the startup scripts. The file is ``/usr/local/etc/rc.d/waitfornetwork'' and its contents are:


#!/bin/sh

# PROVIDE: waitfornetwork
# REQUIRE: NETWORKING
# BEFORE: named

. /etc/rc.subr

: ${waitfornetwork_enable:=NO}
name=waitfornetwork
rcvar=`set_rcvar`
stop_cmd=":"
start_cmd="waitfornetwork_start"

waitfornetwork_start()
{
echo "Waiting for network to initialize."
for i in 0 1 2 3 4 5 6 7 8 9; do
if ping -c 1 192.203.230.10 | grep -q "^1 packets transmitted, 1 packets received, 0\.0% packet loss$"; then
return 0
fi
done
warn "Network still seems bo be down."
return 1
}

load_rc_config ${name}
run_rc_command "$1"

The IP address that I'm pinging is one of the root name servers on the West Coast (U.S.A.). This forces services such as named and ntpd to wait until the network comes up before they start. If the network never comes up, the script exits after a few ping attempts.

morbit
March 19th, 2010, 16:17
Extremely simple port updating/cleaning "script".

#!/bin/sh

portsnap fetch update && portmaster -a && \
pkg_cleanup && portmaster --check-port-dbdir && \
portmaster --check-depends && echo removed distfiles: && \
rm -vrf /usr/ports/distfiles/* && echo removed workfiles: && \
rm -vrf /usr/ports/*/*/work && portmaster -l | grep installed


Suitable to be terminated at pkg_cleanup stage if no fresh ports were built.

I like to be reminded which ports are leaves.

rm /usr/ports/*/*/work is redundant, if portmaster is always used.

PS. "portmaster --packages-build --delete-build-only -a" combination is extremely useful, it uses packages for build dependencies, and deletes them afterward.

ckester
March 19th, 2010, 19:13
This began in the thread about favorite aliases, but it's really more about the simple script I wrote to cd to the directory containing the source for a given command.

I setup the following alias

~/.cshrc

alias src source $HOME/bin/cdsrc


which uses this script

~/bin/cdsrc

#!/bin/csh

set PORTSDIR = /usr/ports

set d = `whereis -sq $1`

if ( "X$d" == "X" ) then
set d = `pkg_info -q -W $1`
if ( "X$d" == "X" ) then
echo "No source directory found for $1"
else
set p = `pkg_info -q -o $d`
if ( "X$p" == "X" ) then
echo "No source directory found for $1"
else
cd ${PORTSDIR}/$p
endif
endif
else
cd $d
endif


It works whether the command is from ports or the system.

It also uses pkg_info's origin switch to find the correct port directory if the command was installed by a package whose name is not the same as the command's.

So src top will take you to /usr/src/usr.bin/top, and src sponge will take you to /usr/ports/sysutils/moreutils.

graudeejs
March 26th, 2010, 13:40
I use this function in my fpfw scripts to add new rules.
The advantage is that it's easier to find which rule wasn't added if there was problem.
This function should be used to only add rules with numbers


#!/bin/sh
cmd="/sbin/ipfw -q"

# add rule to ipfw
# arguments:
# $1 = rule number
# rest args = rule itself
add_rule() {
no=$1
shift
$cmd add $no $* || echo "ERR add_rule: '$cmd add $no $*'" >&2
}


example usage

add_rule 00030 fwd 127.0.0.1,spamd tcp from any to me smtp 'in'


example output
ipfw: getsockopt(IP_FW_ADD): Invalid argument
ERR add_rule: '/sbin/ipfw -q add 00030 fwd 127.0.0.1,spamd tcp from any to me smtp in'

graudeejs
March 27th, 2010, 18:08
I had to write simple bash {ye, right} addressbook for university.
Well I brought this to brand new level :D
This is like 100 times more complex than it was required, but it was fun

This script is only 159 lines of code (including license), 129 lines without license

ladies and gentleman, let me introduce you to my very simple address book written entirely in sh.
Current limitations:
* no spaces in values (even if you quote them). Comment is exception
* can't use | character

~/bin/ashbook:
#!/bin/sh

# Copyright (c) 2010, Aldis Berjoza <aldis@bsdroot.lv>
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# 1. Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following disclaimer
# in the documentation and/or other materials provided with the
# distribution.
# 3. Neither the name of the nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#

address_book="$HOME/.ashbook"
save_backup=1 # saves backup when removing record if set

awk_output_format='
{
split($0, f, "|");
if( f[1] ) print " name: " f[1];
if( f[2] ) print " surname: " f[2];
if( f[3] ) print " email: " f[3];
if( f[4] ) print " phone: " f[4];
if( f[5] ) print " address: " f[5];
if( f[6] ) print " date: " f[6];
if( f[7] ) print " homepage: " f[7];
if( f[8] ) print " code: " f[8];
if( f[9] ) print " comment: " f[9];
print "";
}'


if [ ! -f $address_book ]; then
touch $address_book
if [ $? -ne 0 ]; then
echo "ERR: can't create file $address_book" >&2
exit 1
fi
fi

help() {
version=1.0
prog_name=$(basename $0)
cat >&2 << EOF
$prog_name v$version is a very simple addressbook written in sh

$prog_name usage:
$prog_name {add | find | rm} key1=value1 [key2=value2 [...]]
$prog_name list

Where key can be any of are:
name, surname, code, phone, address, position, email, homepage, date,
comment

Comment key is special and must be last key used. Comment value may
contain spaces.

Values and commands are case sensetive, keys are not.

Use of | character is forbidden as it's used as field seperator in
addressbook.

EOF
exit 1
}


if [ "$1" = 'add' ]; then
func='add'
elif [ "$1" = 'find' ]; then
func='find'
elif [ "$1" = 'list' ]; then
awk "$awk_output_format" $address_book
exit 0
elif [ "$1" = 'rm' ]; then
func='rm'
else
help
fi
shift

if [ $# -eq 0 ]; then
help
exit 1
fi


while [ $# -gt 0 ]; do
key=$(echo $1 | sed 's/=.*//' | tr 'QWERTYUIOPASDFGHJKLZXCVBNM' 'qwertyuiopasdfghjklzxcvbnm')
value=$(echo $1 | sed 's/.*=//')

case $key in
'name' | 'surname' | 'code' | 'phone' | 'address' | 'position' | 'email' | 'date' | 'homepage' )
eval `echo "$key=$value"`;
;;

'comment' )
comment=$(echo $* | sed 's/.*=//')
break
;;

*)
echo "ERR: key '$key' invalid. Ignoring" >&2
;;
esac
shift
done

find_record="${name:-.*}|${surname:-.*}|${email:-.*}|${phone:-.*}|${address:-.*}|${date:-.*}|${homepage:-.*}|${code:-.*}|${comment:-.*}"

if [ $func = 'add' ]; then
if [ $(grep -e "$find_record" $address_book) ]; then
echo 'ERR: looks like this record already exists' >&2
exit 1
fi;
echo "$name|$surname|$email|$phone|$address|$date|$homep age|$code|$comment" >> $address_book
echo "INFO: Record added"
exit 0
elif [ $func = 'find' ]; then
grep -e "$find_record" -x $address_book | awk "$awk_output_format"
exit 0
elif [ $func = 'rm' ]; then
found=`grep -e "$find_record" -x $address_book`
if [ "$found" != "" ]; then
echo "$found" | awk "$awk_output_format"
echo "Do you really want to delete above entries? [y|n]"
read delete
if [ "$delete" = 'y' ] || [ "$delete" = 'Y' ]; then
cp -f $address_book ${address_book}.bak
grep -e "$find_record" -x -v ${address_book}.bak > ${address_book}
if [ ! $save_backup ]; then
rm -f ${address_book}.bak
fi
echo
echo "INFO: Record(s) deleted"
fi
else
echo "INFO: No match found"
fi
exit 0
fi


exit 1

# vim:tabstop=4:shiftwidth=4:


if you think this is any good, please let me know (via pm) and I'll consider improving it and maybe even creating port

Latest version available at:
http://aldis.git.bsdroot.lv/ashbook/

ckester
March 27th, 2010, 20:07
I had to write simple bash {ye, right} addressbook for university.
Well I brought this to brand new level :D
This is like 100 times more complex than it was required, but it was fun


One of the first lessons I learned when I began my software career many years ago is to never add features that aren't in the spec -- at least, not unless you get the client's agreement and understanding that the project might be delayed or have additional bugs as a result.

Even if it's an in-house job. My first programming job (late 80's) was at an avionics company. I spent a lot of time adding bells and whistles to what was expected to be a quick and dirty program. It was a lot of fun, and I was sure it would impress my boss and anyone else who saw it. But as a result, I missed out on another assignment that I really really wanted. When I asked why he hadn't given it to me, my boss said it was because I was still busy on that other thing. He'd thought I'd have the first job done in a day or two, freeing me up in plenty of time to do the plum assignment. :x

graudeejs
March 27th, 2010, 20:29
Ye, but simplicity of original task simply offend my level of knowledge

graudeejs
March 27th, 2010, 22:18
ah, one thing about ashbook script. For now you can't add address with spaces :(
I'll see if I can fix this later

you can search partial strings with for example

$ ashbook find name=killa.*


then again, this won't work

$ ashbook find name=.*smurf86


EDIT:
http://aldis.git.bsdroot.lv/ashbook/

gcooper@
March 28th, 2010, 06:36
Heres a few simple scripts I wrote.

Heres a basic script to play any video in your ~/Videos dir

play.py

#!/usr/bin/env python

import sys
import os

# what to play the video with
player = "vlc"
# arguments, ex 'play "myvid.avi"'
video = sys.argv[1]
# home dir
home = os.path.expanduser('~')

# combine strings
execStr = player+" "+home+"/Videos/"+video
# run execStr
os.system(execStr)




Use exec family functions so the python script isn't looming in the background after your player has been executed and thus you don't get funky interactions with other applications in terms of signal handling, you don't have unnecessary overhead, etc.
os.path.join is preferred over os.path.sep concatenation.
You aren't properly error checking sys.argv to make sure that at least one argument has been specified.

gcooper@
March 28th, 2010, 09:50
chroot_me:

#!/bin/sh

SRCBASE=${SRCBASE:-/usr/src}
[ -d "${DESTDIR}" -a -d "${SRCBASE}" ] || exit $?

export UNAME_s=$(uname -s)
export UNAME_m=${UNAME_m:-$(uname -m)}
export UNAME_p=${UNAME_p:-$(uname -p)}
REVISION=$(cd "${SRCBASE}/sys/conf" && grep REVISION= newvers.sh | cut -f2 -d'"')
BRANCH=$(cd "${SRCBASE}/sys/conf" && grep BRANCH= newvers.sh | head -n1 | cut -f2 -d'"')
export UNAME_r="$REVISION-$BRANCH"
export OSVERSION=$(awk '/\#define.*__FreeBSD_version/ { print $3 }' "$SRCBASE/sys/sys/param.h")
export UNAME_v="$UNAME_s $UNAME_r #0: $(date -v1m -v+1y) root@$HOSTNAME:$SRCBASE/sys/$UNAME_p/compile/GENERIC"

cp -L /etc/resolv.conf "$DESTDIR/etc/resolv.conf"
[ -c "$DESTDIR/dev/zero" ] || mount -t devfs dev "$DESTDIR/dev"

d=$DESTDIR
s=$SRCDIR

unset DESTDIR SRCBASE

chroot "$d" /bin/sh

# XXX: exiting immediately and trying to unmount $DESTDIR/dev doesn't always work... hmmm...
sleep 10

umount -f "$DESTDIR/dev"


make_usb:

#!/bin/sh
#
# A simple script for creating memory disks.
#
# Some of the logic was adapted from release/scripts/make-memstick.sh -- e.g.
# make_usb (thanks kensmith@!)
#

TEN_MB_IN_1K=$((10 * 1024))

# Reporting functions. Nothing much to see here...
die() {
echo >&2 "${0##*/}: ERROR: $*"
exit 1
}
info() {
echo "${0##*/}: INFO: $*"
}

# Usage
usage() {
echo "usage: ${0##*/} [-f mtree-file] input-directory image"
exit 1
}

# Clean up all consumed memory disks.
cleanup() {
set +e
trap : 0 1 2 15
if [ "x${md_unit}" != x ]; then
info "cleaning up memory disk"
mdconfig -d -u ${md_unit}
fi
rm -f "${tempfile}"
}

# Create a complete USB image.
#
# 1 - Input directory.
# 2 - Output image (for USB stick).
make_usb() {

# In order to use mdconfig(1) you should be root -- I realize this is
# overly conservative, but I'd rather not make this too complicated...
if [ "x$(id -ru)" != x0 ] ; then
die "you must be root when executing make_usb"
fi

[ $# -eq 2 ] || usage

[ -d "$1" ] || die "input directory - $1 - doesn't exist"

set -e

tempfile=$(mktemp /tmp/usb.XXXXXXXX)

trap "[ \$? -ne 0 ] && rm -f '$output_image'; cleanup" 0 1 2 15

in_dir=$1
output_image=$2

#sed -e '/^vfs.root.mountfrom.*/d' -i "" "$in_dir/boot/loader.conf"
#echo 'vfs.root.mountfrom="ufs:/dev/da0a"' >> "$in_dir/boot/loader.conf"

#makefs -o -O,1,-b,4096,-f,512,-o,space${inode:+,-i,${inode}} -f 1% \

# Don't want to append to the existing image; this is what happens by
# default with mdconfig(1), because we used -t vnode.
rm -f "$output_image"

makefs_args="${tempfile} ${in_dir}"
if [ "x$mtreefile" != x ]; then
makefs_args="-x -F $mtreefile $makefs_args"
fi
makefs -f 1% $makefs_args

#
# Calculate the needed file size for the mounted image.
#
# The calculation is done as shown for the following reason (as verbatim
# from: .../release/scripts/make_memstick.sh):
#
# Use $BLOCKSIZE for transfers to improve efficiency. When
# calculating how many blocks to transfer "+ 2" is to account for
# truncation in the division and to provide space for the label.
#
block_count=$(( $(stat -f '%z' "$tempfile") / $TEN_MB_IN_1K + 2))

# Create the backing file.
dd if=/dev/zero of=$output_image bs=$TEN_MB_IN_1K count=$block_count

# Create a new memory disk.
md_unit=$(mdconfig -a -t vnode -f "$output_image")
# Partition and label the sucker. Add appropriate bootloader bits to
# the partition table and slices.
fdisk -BIq /dev/${md_unit}
bsdlabel -Bw /dev/${md_unit}
# Sync the contents on the temporary file to the memory disk.
dd "if=$tempfile" of=/dev/${md_unit}a bs=$TEN_MB_IN_1K conv=sync

}

# Parse available options and commands.

mtreefile=

while getopts "f:" option; do
case "$option" in
f)
if [ ! -f "$OPTARG" ] ; then
die "mtree file specified - $OPTARG - doesn't exist or isn't a regular file!"
fi
mtreefile=$OPTARG
;;
*)
usage
;;
esac
done

shift $(( OPTIND - 1 ))

make_usb $@


/etc/rc for an automated install with a predefined payload (was using it for make_usb generated images before my project `changed direction'):

#!/bin/sh
#
# A first-time boot rc script which goes in, labels the disks appropriate to
# the config files, newfs's the sucker, then mounts, unwraps the payload, and
# does a basic sanity check to ensure that the system is bootable and
# functional.
#

DESTDIR=${DESTDIR:-/mnt}
export PATH=/bin:/sbin:/usr/bin:/usr/sbin
export PKG_PATH=/packages

debug() {
echo "${0##*/}: DEBUG: $@"
}

info() {
echo "${0##*/}: INFO: $@"
}

# functions adlibbed from install/stage/etc/rc.

clear_swap() {
# This always errors out when wiping the entire device; I don't care if
# it does or not...
info "Creating swap partition"
dd if=/dev/zero of=/dev/$1s1b bs=1m 2>/dev/null || :
swapon /dev/$1s1b
}

cleanup_mountpoints() {
trap : 0 1 2 15
set +e
mounted_destdir=$(mount | awk '$3 != "/" && $3 !~ /^\/dev/ { print $1 }')
until [ "x${mounted_destdir:-}" = x ]; do
umount -f ${mounted_destdir}
mounted_destdir=$(mount | awk '$3 != "/" && $3 !~ /^\/dev/ { print $1 }')
sleep 1
done
[ "x${md_unit}" != x ] && mdconfig -d -u ${md_unit}

}

# Do all `post-install' configuration actions, like generate /etc/fstab, etc.
#
# 1 - Disk
configure_system() {
generate_fstab $1
clear_swap $1
}

# Clear all of the data off of a disk.
#
# 1 - Disk
format_disk() {
fdisk -BIq $1 2>/dev/null >/dev/null
}

# Generate /etc/fstab based on the filesystems mounted under ${DESTDIR}.
#
# 1 - Disk
generate_fstab() {

old_IFS=$IFS

IFS="
"

echo "/dev/$1s1b none swap sw 0 0" > "${DESTDIR}/etc/fstab"

for i in $(mount); do

i=$(echo "$i" | sed -e 's# on##g' -e 's#(.*)$##g' -e 's#mnt/*##g')

case "$i" in
/dev/$1*)
echo "$i ufs rw 1 1" >> "${DESTDIR}/etc/fstab"
;;
esac

done

IFS=$old_IFS

}

# Is the disk real?
#
# 1 - Disk
isa_real_disk() {
[ -c /dev/$1 ]
}

# Label a disk according to a seemingly logical scheme
label_disk() {

disklabel -w -r -B /dev/${1}s1 auto

tmp_label=$(mktemp /tmp/disklabel.XXXXXX)

cat <<EOF > $tmp_label
a: 4G 16 4.2BSD 2048 16384
b: $(( $(sysctl -n hw.physmem) / 1024 / 1024 ))M * swap
d: 4G * 4.2BSD 2048 16384
e: 8G * 4.2BSD 2048 16384
f: * * 4.2BSD 8192 65536
EOF

disklabel -R /dev/${1}s1 $tmp_label

rm -f $tmp_label

}

mount_disk() {

for i in 1a: 1d:usr 1e:var 1f:usr/home; do

partition="/dev/${1}s$(echo "$i" | cut -d: -f1)"
mountpoint="${DESTDIR}/$(echo "$i" | cut -d: -f2)"

debug "Mounting ${partition} on $mountpoint"

test -d "$mountpoint" || mkdir -p "$mountpoint"
mount $partition "$mountpoint"

done

}

newfs_disk() {
for i in /dev/${1}s1[adef]; do
newfs -O2 -m 8 -o time $i >/dev/null
done
}

stage_install() {

info "Installing base"

# Copy over the contents of the media to $DESTDIR , skipping over a
# select set of directories (but not /packages because pkg_add would
# fold in on itself if it's not present based on the value of
# getcwd(3), as pkg_add(1) -C chroots into $DESTDIR, and chroot(2)
# does not actually modify the value of the current directory returned
# by getcwd(3)).
#
# XXX (garrcoop): 1. --exclude for tar(1) should work in this regard,
# but it doesn't 100% in this case (for some reason). 2. -C for cpf
# should work as well, but doesn't.
(cd / ; tar -cpf - $(ls -d * | grep -E -v 'dist|mnt') | tar xpf - -C "$DESTDIR")

# Override the USB copies of files with their dist/ bretheren.
(cd /dist ; tar -cpf - . | tar xpf - -C "$DESTDIR")

sed -e '/^vfs.root.mountfrom/d' -i "" "$DESTDIR/boot/loader.conf"

if [ -d "$PKG_PATH" ] ; then

info "Installing packages"

mount -t devfs dev $DESTDIR/dev

mountpoints="$DESTDIR/dev $mountpoints"

# XXX (garrcoop): pkg_add(1) barfs with exit code 1 even when
# -F and -f are specified; this needs to be fixed.
(find "$PKG_PATH" -type f | xargs -n 4 pkg_add -C "$DESTDIR" -Ff || :) 2>/dev/null >/dev/null

rm -Rf "$DESTDIR/$PKG_PATH"

info "Packages installed"

fi

info "Install complete"

}

wipe_disk() {
info "Wiping disk $1"
dd if=/dev/zero of=/dev/$1 bs=1m count=1 2>/dev/null || :
}

set -e

md_unit=$(mdconfig -a -t malloc -s $(( 16 * 1024 * 1024 )) )
newfs /dev/$md_unit >/dev/null
mount -t ufs /dev/$md_unit /tmp
trap cleanup_mountpoints 0 1 2 15

# Wait for the devices to be detected.
i=0
while [ $i -lt 15 ] && ! isa_real_disk "$1" ; do
# Avoid RAIDs, memory disks, and SCSI disks.
set -- $(sysctl -n kern.disks | awk '{ for (i=1; i <= NF; i++) { if ($i !~ /ar|da|md|mf[0-9]+/) { disks = disks " " $i } } } END { print disks }')
sleep 2
: $(( i += 1 ))
done

if [ "x$1" = x ] ; then
echo "${0##*/}: ERROR: didn't find a configurable harddisk."
exit 1
else

for step in wipe format label newfs mount; do
debug "Calling ${step}_disk on $1"
eval "${step}_disk $1"
done

stage_install
configure_system $1

cleanup_mountpoints

read -p "Remove the CD / USB media and press Enter to continue " j
init 6

fi


Certain hacks are in place for our specific environment, but you're free to use this in whatever way you deem appropriate.

All stuff here BSD licensed of course :P.

Ruler2112
March 31st, 2010, 23:12
One of the first lessons I learned when I began my software career many years ago is to never add features that aren't in the spec -- at least, not unless you get the client's agreement and understanding that the project might be delayed or have additional bugs as a result.

Even if it's an in-house job.

My brother was fired from his job last year because of just this. He wrote what the person wanted, then expanded it to include cool features. By the time he was done adding stuff that he thought would be useful, it was so complex that the person it was for couldn't figure out how to use it. They went around 2-3 times, trying to get it to be what the person wanted, but he really didn't know what he wanted it to do and my brother was guessing based on varied and vague descriptions. (This didn't come out until much later.) It was an in-house job and because it didn't do what was wanted, the person had him fired. :( My brother has always ripped on me for spending time doing system requirements engineering and getting the document explaining what the system will do initialed on all but the simplest of projects; if he were to have done so, he would not have been fired IMO.

Sorry to go off-topic - this is an important concept for new coders to grasp. More and better isn't always better.

gcooper@
April 4th, 2010, 22:16
Yes. Making life easier is nice, but simplicity is always key; otherwise the added support and complexity is just unruly and a pain.

gcooper@
April 4th, 2010, 22:20
Delete empty @pkgdep lines created by unknown source (portmaster?, ports?):

find /var/db/pkg/ -name +CONTENTS -mindepth 2 -maxdepth 3 | xargs -J % -n 1 sed -i "" -E -e '/^@pkgdep *$/d' %

graudeejs
June 10th, 2010, 22:58
I just developed playlist randomization for my playd (in pure sh)

this function takes 1 argument (maximal value to return) and return random number 0 to $1

playd_rnd() {
# arg1 Max value
a=$(dd if=/dev/random of=/dev/stdout bs=1 count=4 2>/dev/null | od -D -An)
b=$(echo "$1 / 4294967296 * $a" | bc -l | sed 's/\..*$//')
if [ "$b" ]; then
echo $b
else
echo 0
fi
}

vermaden
June 10th, 2010, 23:32
@killasmurf86

You should accomplish the same with that one-liner:
% expr ${RANDOM} % 10 + 1

... where 10 is maximum, You may generalize that into:
% expr ${RANDOM} % ${MAX} + 1

ProFTP
June 10th, 2010, 23:44
simple script to correct MySQL database tables

http://www.x0.org.ua/blog/user/1/view/39
#!/usr/bin/perl

use DBI;

my $db_name = 'mysql';

# user from db
my $db_user = 'root';
my $db_pass = '';
my $db_type = 'mysql';
my $db_host = 'localhost';

my $dbh = DBI->connect(
"DBI:$db_type:database=$db_name;host=$db_host",
$db_user, $db_pass,
{
RaiseError => 1,
PrintError => 1
}
) || die $DBI::errstr;

my $sth = $dbh->prepare( 'select Db from db' );
$sth->execute();
my $loop_data;
push @{$loop_data}, $_ while $_ = $sth->fetchrow_hashref();

$sth->finish();
$dbh->disconnect();

foreach my $ii ( @{$loop_data} ) {

my $db_name = $ii->{Db};

my $dbh = DBI->connect(
"DBI:$db_type:database=$db_name;host=$db_host",
$db_user,
$db_pass

);

my $loop_data2;

eval {

my $sth = $dbh->prepare('show tables');
$sth->execute();

while ( my @row = $sth->fetchrow_array ) {

die "bad table name: $row[0]" unless $row[0] =~ /^[w_]+$/;
push @{$loop_data2}, $row[0];

}

};

next if ($@);

foreach $_ ( @{$loop_data2} ) {
$dbh->do( qq{REPAIR TABLE $_ } );
}

$dbh->disconnect();

}

ProFTP
June 10th, 2010, 23:46
My Collection scripts (Russian language)
http://unixforum.org.ua/index.php?topic=23928

Alt
June 11th, 2010, 01:02
Another script for fixing all MYSQL tables in all databases (without shutdown):
#!/bin/sh
# Written by Alt 2010. Beer-ware license xD

M_LOGIN="root"
M_PASS="YoUrPaSsWoRd"

DBS=`echo 'show databases;' | /usr/local/bin/mysql -p$M_PASS -u$M_LOGIN | /usr/bin/grep -v Database | /usr/bin/grep -v information_schema | /usr/bin/xargs echo `
for DB in $DBS; do
echo "DB $DB"
TBLS=`echo 'show tables;' | /usr/local/bin/mysql -p$M_PASS -u$M_LOGIN $DB | /usr/bin/grep -v Tables | /usr/bin/xargs echo `
for TBL in $TBLS; do
echo -n " Tbl $TBL .. "
echo "repair table $TBL quick;" | /usr/local/bin/mysql -p$M_PASS -u$M_LOGIN $DB | /usr/bin/grep -v Msg_type
done
done
/usr/local/bin/mysqladmin -p$M_PASS -u$M_LOGIN flush-tables

ProFTP
June 11th, 2010, 01:15
i think from the beginning we should see whether the table is corrupted ...! (because for a long time ...)
... and then correct ...
but it is not essential ...

graudeejs
June 11th, 2010, 05:18
@killasmurf86

You should accomplish the same with that one-liner:
% expr ${RANDOM} % 10 + 1

... where 10 is maximum, You may generalize that into:
% expr ${RANDOM} % ${MAX} + 1

uhhh, man.... and I had to invent new method just because I couldn't find anything how to get random number

EDIT:
I noticed, that your solution only generates random numbers up till 2^15 [at lest so it seams].
My solution [current implementation] can generate number up 2^32, and I don't see problems making even bigger numbers (just need to modify a bit)

john_doe
June 11th, 2010, 09:27
You should accomplish the same with that one-liner:
% expr ${RANDOM} % 10 + 1It will not work in sh. Use jot, e.g.
jot -r 1 0 $(((1 << (8 * 4)) - 1))
where 4294967295 is max of 4 bytes of /dev/random

And the function can be reduced to
playd_rnd() { jot -r 1 0 $1; }

graudeejs
June 11th, 2010, 10:13
It will not work in sh. Use jot, e.g.
jot -r 1 0 $(((1 << (8 * 4)) - 1))
where 4294967295 is max of 4 bytes of /dev/random

And the function can be reduced to
playd_rnd() { jot -r 1 0 $1; }

I can't believe that this was in front of my nose all the time :D

graudeejs
July 9th, 2010, 10:31
Here's script that will create zfs snapshots and remove snapshots older than $age seconds
http://aldis.git.bsdroot.lv/zfSnap

This script should be used by cron or something like that

More info:
read this thread http://forums.freebsd.org/showthread.php?t=15737

EDIT:
read wiki http://wiki.bsdroot.lv/zfsnap

t4z3v4r3d
July 10th, 2010, 13:33
Hello . I'm trying to write a graph er ! script ... and its not good to present .:d
How can i do that ?

#!/usr/bin/env bash
clear
# this can be temperature or something else
# Total line number is 33 !

temp_array=( "" 32 31 31 30 29 28 28 35 37 38 38 39 40 40 41 48 45 44 43 42 40 39 36 )
# THE h line len=32 ! so i should get diffz between start and stop line ! (negatively)
size="${#temp_array[@]}"
### "Y"
for ((l=1 ; l < $size ; l++ ));do
let "l2=l+$l"
for ((t=1 ; t <= ${temp_array[$l]} ;t++));do
let "temp=50-${temp_array[$l]}"
echo -en "\033[${temp};"$l2"f\033[1;31m *\r \033[0;0m"
echo "${temp_array[$l]}"
done
done
echo -e "\033[0;0m"
### "X"
for ((k=1 ; k < 32 ; k++ ));do
echo -en "\033[32;$kf\033[32;"$k"d\033[1;31m |\033[0m"
done
echo

Dereckson
July 10th, 2010, 17:36
I wrote this TCL script to copy photos from my memory card to my hard disk.

It copies only new pictures and, if the $GrabPhotos(enableresize) preference is set to 1, will call ImageMagick to create resized version (I found it's quicker to browse 1600x1200 and convenient to have 800x600 versions to send to your contacts).


#!/usr/local/bin/tclsh8.5
#
# GrabPhotos.tcl -- Photo memory card helper
# Sébastien Santoro aka Dereckson <dereckson@gmail.com>
#

# # # # # # # # # # # # #
# General configuration #
# # # # # # # # # # # # #

# Where to copy the pics?
set GrabPhotos(targetdir) "~/docs/pics/albums"
# Where are the pics (e.g. your memory card location)?
set GrabPhotos(sourcedir) "/mount/flashmedia"

# On the memory card, where are the pics ?
# set GrabPhotos(picsdir) "" to disable DCIM-like directories lookup
set GrabPhotos(picsdir) DCIM

# If 1, work with any subdirectory from the source
set GrabPhotos(recursive) 1

# Prints an header with credits
set GrabPhotos(printcredits) 0

# verbose prints script action, debug extra details
set GrabPhotos(verbose) 1
set GrabPhotos(debug) 0

# When debug is 1, that also implies verbose to 1, discarding your verbose value
# To disable this behavior, comment the following line (putting a # in front of it) :
if $GrabPhotos(debug) {set GrabPhotos(verbose) 1}

# # # # # # # # # # # # # # # # # # # # #
# Specific configuration :: resize code #
# # # # # # # # # # # # # # # # # # # # #

#This part is if you want to create resised versions with ImageMagick

set GrabPhotos(enableresize) 1
set GrabPhotos(resizeddir) "~/docs/pics/albums/_resized"
set GrabPhotos(sizes) "75x56 800x600 1600x1200"
set GrabPhotos(jpegquality) 80
set GrabPhotos(convert) "/usr/local/bin/convert"
set GrabPhotos(mogrify) "/usr/local/bin/mogrify"

# # # # # # # # # # # # #
# General configuration #
# # # # # # # # # # # # #

# Now, if you just want a copy or a resizing, it's operate as is. Just run it.
# The following code is fully customisable and commented to help you to
# adapt it for your needs.

# # # # # # # # # # # #
# File types handlers #
# # # # # # # # # # # #

# By default, this script handles .jpg files.
# You can add handlers, just creating a proc named handler_ext,
# where ext is the file lowercase extension.
# The file argument is the complete path to the file

# This handlers copy .jpg files to $GrabPhotos(targetdir)/YYYY/YYYY-MM folders
# and then create thumbnails version

proc handler_jpg {file} {
global GrabPhotos

#Gets created time of the file, and then YYYY and MM values
set ctime [get_created_time $file]
set YYYY [clock format $ctime -format "%Y"]
set MM [clock format $ctime -format "%m"]

#Gets the target directory. Creates it if needed
set targetdir "$GrabPhotos(targetdir)/$YYYY/$YYYY-$MM"
if $GrabPhotos(debug) {puts "\nTarget: $targetdir"}
create_directory $targetdir

#Copies file if it doesn't exist
copy_file $file $targetdir

#Calls resize code if enabled
if $GrabPhotos(enableresize) {resize $file "$YYYY/$YYYY-$MM"}
}

# # # # # # # # #
# Plugs in code #
# # # # # # # # #

proc resize {file subdir} {
global GrabPhotos
if $GrabPhotos(verbose) {puts "Generating resized version from $file"}
foreach size $GrabPhotos(sizes) {
set targetdir "$GrabPhotos(resizeddir)/$subdir/$size"
create_directory $targetdir
set targetfile "$targetdir/[get_filename $file]"
if ![file exists $targetfile] {
#copy_file $file $targetdir
exec -- $GrabPhotos(convert) [file nativename $file] -resize $size -quality $GrabPhotos(jpegquality) [file nativename $targetfile]
}
}
}

# # # # # # # # # # #
# Helper procedures #
# # # # # # # # # # #

proc copy_file {file targetdir} {
global GrabPhotos
set fileExists [file exists "$targetdir/[get_filename $file]"]

if $GrabPhotos(debug) {
#DEBUG print
puts -nonewline "Copying $file to $targetdir"
if $fileExists {
puts " \[skipped, already exists\]"
} {
file copy $file $targetdir
puts " \[ok\]"
}
} elseif !$fileExists {
file copy $file $targetdir
}
}

proc create_directory {dir} {
global GrabPhotos
if ![file exists $dir] {
if $GrabPhotos(verbose) {puts "Creating $dir"}
file mkdir $dir
}
}


proc get_created_time {file} {
file stat $file test
return $test(ctime)
}

proc get_filename {file} {
lindex [file split $file] end
}

proc parse {directory} {
global GrabPhotos

if $GrabPhotos(verbose) {puts "Parsing $directory"}

#Get files in this directory
foreach file [glob -nocomplain -directory $directory *] {

#Another directory, parses it if recursive mode enabled
if {[file isdirectory $file] && $GrabPhotos(recursive)} {
parse $file
} {
#A regular file, gets the extension and check if we've an handler
set ext [string tolower [string range [file extension $file] 1 end]]
set handlerproc [info procs handler_$ext]
if {$handlerproc != ""} {
#An handler exists
if $GrabPhotos(debug) {puts "Calling $handlerproc $file"}
$handlerproc $file
} {
#File unhandled by a proc
if $GrabPhotos(verbose) {puts "Ignored file: $file"}
}
}
}

}

proc print_credits {} {
puts "__________________________________________________ _________________"
puts "GrabPhotos 0.1 :: the photo memory card helper"
puts "__________________________________________________ _________________"

}

proc print_usage {} {
puts "Usage: GrabPhotos <source>"
}

# # # # # # # # # #
# Procedural code #
# # # # # # # # # #
if {$argc == 0} {
if {![info exists GrabPhotos(sourcedir)]} {
print_credits
print_usage
exit
}
} {
# Gets sourcedir from argument
set GrabPhotos(sourcedir) [lindex $argv 0]
}

if {![file isdirectory $GrabPhotos(sourcedir)]} {
puts stderr "Fatal error: $GrabPhotos(sourcedir) isn't a directory."
exit
}


if $GrabPhotos(printcredits) {
print_credits
}

# Go to $GrabPhotos(picsdir) (by default DCIM) directory, if it exists
# If not, we stay in current $GrabPhotos(sourcedir) (by default the script argument)
if [file isdirectory "$GrabPhotos(sourcedir)/$GrabPhotos(picsdir)"] {
set GrabPhotos(sourcedir) "$GrabPhotos(sourcedir)/$GrabPhotos(picsdir)"
}

parse $GrabPhotos(sourcedir)

Andres
July 26th, 2010, 17:44
The version in shells/tcshrc is missing a few things, like tmux/screen terminfo:

set echo_style = 'both'
set title = '$USER@$HOST:ar $cwd'

switch ($TERM)
case {dtterm,rxvt,screen,xterm}*:
alias cwdcmd 'echo -n "\e]2;'$title'\a"'
breaksw
case sun*:
alias cwdcmd 'echo -n "\e]l'$title'\e\\"'
breaksw
case vt[24]20*:
alias cwdcmd 'echo -n "\e]0;'$title'\a\e\\"'
breaksw
default:
alias cwdcmd 'unalias cwdcmd'
unset title
endsw

cwdcmd

ProFTP
August 2nd, 2010, 04:17
[Perl] example upload photos to a server with thumbnail previews

files are not uploaded to the server, php programmers could not solve this problem simply wanted to change hosting :)

#!/usr/bin/perl

# @author Dmitriy Shilenko <q7u5@ukr.net>
# ProFTP

use warnings;
use strict;
use CGI;
use DBI;
use Image::Magick;

use CGI::Carp qw(fatalsToBrowser); # used only for tests
# use Data::Dumper;
# $CGI::POST_MAX = 100000000 # maximum file upload size for safety

my $form = new CGI;


# print $form->header; #Print HTML header. this is mandatory



my $p;
%{$p} = $form->Vars;

if (!$p || !%{$p}) {

print $form->header( -charset => "utf8" );
#print `pwd`;
print 'This is perl, my name is Satan666 :)';
exit;

}



my @a = qw (cid date obj name fam phone age addr project edu more icq status b1 b2 b3 b4 b5 b6 b7 b8 b9 b10 b11 b12 b13 b14 b15 b16 b17 b18 b19 b20 b21 b22 b23 b24);

@a = map { $p->{$_} || '' } @a;

# print Dumper \@a;
# exit;

my $db_name = '';
# user from db
my $db_user = '';
my $db_pass = '';
#
my $db_type = 'mysql';
my $db_host = 'localhost';

my $prefix = ''; # prefix table...

my $web_home = "/home/files/";


my $dbh = DBI->connect(
"DBI:$db_type:database=$db_name;host=$db_host",
$db_user, $db_pass,
{
RaiseError => 1,
PrintError => 1
}
) || die $DBI::errstr;


$dbh->do('INSERT INTO '.$prefix.'_base (cid,date,obj,name,fam,phone,age,addr,project,edu, more,icq,status,b1,b2,b3,b4,b5,b6,b7,b8,b9,b10,b11 ,b12,b13,b14,b15,b16,b17,b18,b19,b20,b21,b22,b23,b 24)

VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,? ,?,?,?,?,?,?,?,?,?,?,?,?)
', undef, @a );

my $id_db = $dbh->{mysql_insertid};

my $hash;

my @hash;

# 1..8 foto's
for (0..8) {

my $key = "foto".($_ == 0 ? "" : $_);
my $id_file = $_ == 0 ? 1 : ($_+1);


if ( my $UPLOAD_FH = $form->param($key) ) {

uploadfile($UPLOAD_FH,$id_db, $id_file );
$hash->{$key} = '/file/'.$id_db.'_'.$id_file.'.jpg';


}


}




# print Dumper $hash;


$dbh->do('UPDATE '.$prefix.'_base SET '.( join ", ", map { $_ .' = ? ' } keys %$hash ).' WHERE id='.$id_db.' LIMIT 1', undef, values %$hash ) if ($hash && %$hash);





##this is the only way to send msg back to the client

## print "<script>parent.callback('upload file success')</script>";





sub uploadfile {

my ($UPLOAD_FH,$id_last, $id_name) = @_;

my $newfilename = $web_home."or_".$id_last."_".$id_name.".jpg";

# umask 0000; #This is needed to ensure permission in new file

open (IMG, ">$newfilename"); binmode IMG; print IMG while (<$UPLOAD_FH>); close (IMG); chmod 0644, $newfilename;

image_thumbnail('100', '100', $newfilename, $web_home."".$id_last."_".$id_name.".jpg");

};




sub image_thumbnail {

my ($ix, $iy, $file_name, $file_name_out) = @_;

my $photo = Image::Magick->new;
$photo->Read($file_name);


my ($ox, $oy, $oc, $ic, $nx, $ny, $geo);
($ox,$oy)=$photo->Get('columns','height');
if (($ox > $ix)||($oy > $iy)) {
$oc = $ox/$oy; $ic = $ix/$iy;
if ($oc < $ic) {$ny = $iy; $nx=int(($ox/$oy)*$iy);}
elsif ($oc > $ic) {$nx = $ix; $ny=int(($oy/$ox)*$ix);}
else {$nx = $ix; $ny = $iy;}}
else {$nx=$ox;$ny=$oy;}



$geo = 'geometry';
$photo->Resize(geometry=>$geo, width=>$nx, height=>$ny);

$photo->Write($file_name_out);

}

$dbh->disconnect();

# redirect:

print $form->redirect( -uri => 'site.com', -status => 301 );


exit;

interesting:


$dbh->do('UPDATE '.$prefix.'_base SET '.( join ", ", map { $_ .' = ? ' } keys %$hash ).' WHERE id='.$id_db.' LIMIT 1', undef, values %$hash ) if ($hash && %$hash);


my (http://unixforum.org.ua/index.php?topic=23928.15) blog (http://www.x0.org.ua/blog/user/1/view/44)

da1
September 8th, 2010, 12:11
I was searching for a ftp version of sshguard and I couldn't find one. Therefore, I wrote the following. Tested and working with pure-ftpd and pf on 8.0,8.1:
It is not hard to adapt it for ipf or ipfw with other ftp softwares out there.


grep="/usr/bin/grep"
awk="/usr/bin/awk"
uniq="/usr/bin/uniq"
ftpguard="/etc/ftpguard.pf"
table="ftpguard"
pfctl="/sbin/pfctl"


if [[ -z $1 ]];then
echo "Usage: grep_ip_from_file <file_name>"
else
$grep "\[ERROR\]\ Too\ many\ authentication\ failures" $1 | $awk '{print $6}' | $grep -o '[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}'| $uniq | while read IP
do
for i in $IP;
do
if [[ $i != `$grep $i $ftpguard` ]];
then
echo $i >> $ftpguard
$pfctl -t $table -T add $i
fi
done
done
fi

The script expects that you have a entry in pf.conf like:
table <ftpguard> persist file "/etc/ftpguard.pf"
[...]
block in quick on $ext_if proto tcp from <ftpguard> to any port { 21, other ftp related ports } label "ftp bruteforce"

and
-rw------- 1 root wheel 264 Sep 6 12:19 /etc/ftpguard.pf

I use crontab to scan /var/log/messages every 10 minutes:
*/10 * * * * root /path to a folder/ftpguard.sh /var/log/messages &> /dev/null
Pls note that I have appended &> /dev/null because I do not want to receive mails about this.


Hope it comes handy for some one.

graudeejs
October 1st, 2010, 00:12
I wrote perl script to convert /usr/src/sys/kern/syscalls.master to lang/fasm include file

http://aldis.git.bsdroot.lv/asm4FreeBSD/tree/scripts/FreeBSD_syscalls4fasm.pl
here's output:
http://aldis.git.bsdroot.lv/asm4FreeBSD/tree/include/syscalls.fasm

rbelk
November 14th, 2010, 05:20
After getting asked to many times on how to update the ports system, I wrote the following script. I hope some one finds it useful. If anyone finds an issue, or makes an addition, please forward them back to me. I might submit this to to "portmaster" author and see if he would include it in his port.

I added this script to root's bin directory and chmod'ed it to 0700.


#!/bin/sh
#================================================= ==============================
#
# FILE: pmm
#
# USAGE: pmm
#
# DESCRIPTION: A menu driven Shell script for ports management
#
# OPTIONS: None
# REQUIREMENTS: /bin/sh, /usr/sbin/pkg_version, /usr/local/bin/portmaster
# BUGS: ---
# NOTES: ---
# AUTHOR: $Author: rbelk $
# COMPANY: OnlyBSD
# VERSION: $Header: /root/bin/RCS/pmm,v 1.4 2010/11/14 03:35:36 rbelk Exp $
# CREATED: $Date: 2010/11/14 03:35:36 $
# REVISION: $Revision: 1.4 $
# LOG: $Log: pmm,v $
# LOG: Revision 1.4 2010/11/14 03:35:36 rbelk
# LOG: added the pkg_version requirement
# LOG:
# LOG: Revision 1.3 2010/11/14 03:33:26 rbelk
# LOG: cleaned up the comments
# LOG:
# LOG: Revision 1.2 2010/11/14 03:30:19 rbelk
# LOG: Update the RCS comments section
# LOG:
#================================================= ==============================

while :
do
clear
echo "P O R T S - M A I N T I A N C E - M E N U"
echo ""
echo "NOTE: You must first do the following steps for PMM to run correctly"
echo "- Install the ports tree with the command /usr/sbin/portsnap fetch extract"
echo "- Install portmaster: cd /usr/ports/ports-mgmt/portmaster; make install clean"
echo "- Add the next line to roots crontab"
echo " 0 1 * * * /usr/sbin/portsnap cron"
echo ""
echo "1. Update the ports tree"
echo "2. List ports that need to be upgraded"
echo "3 Update the installed ports"
echo "4. Cross-check and update dependency information for all ports"
echo "5. Delete stale distfiles of ports not installed anymore"
echo "6. Delete stale packages in the package directory"
echo "7. Delete stale ports that used to be depended on"
echo "8. Delete stale entries in /var/db/ports"
echo ""
echo "Q - Quit"
echo ""
echo -n "Please enter option [1 - 8, Q] "
read opt
case $opt in
1) echo "- Updating the ports directory";
old_time=`ls -lt /usr/ports/UPDATING | awk '{print $6" "$7" "$8}'`
/usr/sbin/portsnap update
new_time=`ls -lt /usr/ports/UPDATING | awk '{print $6" "$7" "$8}'`
if [ "$old_time" != "$new_time" ]
then
echo ">>>>>> A T T E N T I O N ---------------------------------------------------"
echo " /usr/ports/UPDATING has Changed"
echo " PLEASE READ BEFORE CONTINUING"
echo " You might have an installed port that needs attention"
echo " When you are sure everything is OK, start PMM again and proceded to step 2"
echo ">>>>>> A T T E N T I O N ---------------------------------------------------"
exit 1;
fi
echo ""
echo ">>>> Your Next Option is '2' <<<<";
echo "Press [enter] key to continue. . .";
read enterKey;;
2) echo "- Listing of ports that need to be upgraded";
/usr/sbin/pkg_version -o -I -L= | awk '{print $1}'
echo ""
echo '>>>> Your Next Option is "3" <<<<';
echo "Press [enter] key to continue. . .";
read enterKey;;
3) echo "- Updating the installed ports";
# /root/bin/update_ports
/usr/local/sbin/portmaster -a
echo ""
echo ">>>> Your Next Option is "4" <<<<";
echo "Press [enter] key to continue. . .";
read enterKey;;
4) echo "- Cross-checking and updating dependency information for all ports";
/usr/local/sbin/portmaster --check-depends
echo ""
echo ">>>> Your Next Option is "5" <<<<";
echo "Press [enter] key to continue. . .";
read enterKey;;
5) echo "- Deleting stale distfiles of ports not installed anymore";
/usr/local/sbin/portmaster --clean-distfiles
echo ""
echo ">>>> Your Next Option is "6" <<<<";
echo "Press [enter] key to continue. . .";
read enterKey;;
6) echo "- Deleting stale packages in the package directory";
/usr/local/sbin/portmaster --clean-packages
echo ""
echo ">>>> Your Next Option is "7" <<<<";
echo "Press [enter] key to continue. . .";
read enterKey;;
7) echo "- Deleting stale ports that used to be depended on";
/usr/local/sbin/portmaster -s
echo ""
echo ">>>> Your Next Option is "8" <<<<";
echo "Press [enter] key to continue. . .";
read enterKey;;
8) echo "- Deleting stale entries in /var/db/ports";
/usr/local/sbin/portmaster --check-port-dbdir
echo ""
echo ">>>> Your ports tree should be updated <<<<";
echo "Press [enter] key to continue. . .";
read enterKey;;
Q) echo "Bye $USER";
exit 1;;
*) echo "$opt is an invaild option. Please select option between 1-8, or Q only";
echo "Press [enter] key to continue. . .";
read enterKey;;
esac
done

vermaden
November 14th, 2010, 13:41
@rbelk

Nice scripts mate, here are my thoughts:

1)
diff(1) between old and new UPDATING instead of ATTENTION
3)
add addtional options like
3.1 (do not ask for anything - automatic mode)
3.2 (use packages if available: -PP option)
3.3.(other usefull portmaster options)
GENERAL)
consistency, use name 'ports' or 'packages' everywhere instead of mixing, example:
echo "6. Delete stale **packages** in the package directory"
echo "7. Delete stale **ports** that used to be depended on"

kpedersen
November 14th, 2010, 15:59
Because I like to compile as little software as possible from ports on my already overheating IBM X60 Thinkpad, I devised this little script to run from inside a port folder and tell me a list of package names that I need before this one port will compile.
This does a job which `make missing` fails to do because that lists all the ports to build the dependencies too. I just want the packages. `make run-depends-list' & 'make build-depends-list` don't quite cut it either because they don't take into account ports that are already installed. Also none of them list the package names.

So.. Hopefully I have justified the existence of my script enough... :)


#ifdef NEVER
g++ $0 -o "$HOME/.port_depends"
"$HOME/.port_depends"
rm "$HOME/.port_depends"
exit
#endif

#include <iostream>
#include <exception>
#include <vector>
#include <string>

using namespace std;

vector<string> packages;
vector<string> ports;

void execute_fetch_list(string command, vector<string>* results)
{
char output[100];
FILE* p = NULL;
string line;

p = popen(command.c_str(), "r");

if(p == NULL)
{
throw exception();
}

while(fgets(output, sizeof(output), p) != NULL)
{
line = output;
results->push_back(line.substr(0, line.length() - 1));
}

if(pclose(p) != 0)
{
throw exception();
}
}

string execute_fetch(string command)
{
char output[100];
FILE* p = NULL;
string line;
vector<string> results;

p = popen(command.c_str(), "r");

if(p == NULL)
{
throw exception();
}

while(fgets(output, sizeof(output), p) != NULL)
{
line = output;
results.push_back(line.substr(0, line.length() - 1));
}

if(pclose(p) != 0)
{
throw exception();
}

return results.at(results.size() - 1);
}

void inspect_port(string port)
{
vector<string> depends;
string package;

for(int portIndex = 0; portIndex < ports.size(); portIndex++)
{
if(ports.at(portIndex) == port)
{
return;
}
}

ports.push_back(port);
execute_fetch_list("make -C " + port + " run-depends-list", &depends);

for(int dependIndex = 0; dependIndex < depends.size(); dependIndex++)
{
inspect_port(depends.at(dependIndex));
}

package = execute_fetch("make -C " + port + " package-name");

for(int packageIndex = 0; packageIndex < packages.size(); packageIndex++)
{
if(packages.at(packageIndex) == package)
{
return;
}
}

cout << package << endl;
}

void safe_main(int argc, char* argv[])
{
vector<string> runDepends;
vector<string> buildDepends;

//populate installedPackages
execute_fetch_list("pkg_info | awk '{print $1}'", &packages);

execute_fetch_list("make build-depends-list", &buildDepends);
execute_fetch_list("make run-depends-list", &runDepends);

for(int dependIndex = 0; dependIndex < buildDepends.size(); dependIndex++)
{
inspect_port(buildDepends.at(dependIndex));
}

for(int dependIndex = 0; dependIndex < runDepends.size(); dependIndex++)
{
inspect_port(runDepends.at(dependIndex));
}
}

int main(int argc, char* argv[])
{
try
{
safe_main(argc, argv);
}
catch(exception& e)
{
cout << "Exception: " << e.what() << "." << endl;
}

return 0;
}




To get working, copy to your PATH, chmod +x and just make sure that it ends in .cpp or the automatic compiling wont work.. :p

Enjoy :)

rbelk
November 14th, 2010, 18:37
@rbelk

Nice scripts mate, here are my thoughts:


diff(1) between old and new UPDATING instead of ATTENTION

add addtional options like
3.1 (do not ask for anything - automatic mode)
3.2 (use packages if available: -PP option)
3.3.(other usefull portmaster options)

consistency, use name 'ports' or 'packages' everywhere instead of mixing, example:
echo "6. Delete stale **packages** in the package directory"
echo "7. Delete stale **ports** that used to be depended on"

Vermaden, thanks for the feedback. I have a question though. What do you mean by "UPDATING instead of ATTENTION" in your first request. I am checking the /usr/ports/UPDATING to see if it was updated and displaying an attention message.

I also fixed the second request about ports/packages. The 3.1 and 3.2 request can't happen, it's a portmaster thing. I might make a separate script for installing packages. But I am looking into adding other options to pmm.

kpedersen
November 21st, 2010, 02:33
I call this script "Just stay connected you ****!"


#!/bin/sh

ROUTER="192.168.0.1"
IP="192.168.0.4"

while true; do
echo "Pinging ${ROUTER}..."
ping -o -t 10 ${ROUTER} > /dev/null 2>&1

if [ $? != 0 ]; then
echo "Router did not respond, reconnecting..."
ifconfig wlan0 inet ${IP} netmask 255.255.255.0
ifconfig wlan0 down
route add default ${ROUTER} > /dev/null 2>&1
wpa_supplicant -i wlan0 -c /etc/wpa_supplicant.conf -B > /dev/null 2>&1
else
echo "Router responded"
fi

sleep 30
done


This also has the added bonus of my laptop connecting back to the wireless even if the wireless switch has been turned off and on again.

Kinda horrid but it is the only way I currently know which will sort itself out after the iwi (intel 2200bg) has a firmware error etc...

vermaden
November 21st, 2010, 12:18
Vermaden, thanks for the feedback. I have a question though. What do you mean by "UPDATING instead of ATTENTION" in your first request. I am checking the /usr/ports/UPDATING to see if it was updated and displaying an attention message.
Instead of checking IF it changed, display WHAT have changed, like that:
# cd /usr/ports
# cp UPDATING /tmp
# portsnap fetch update
# diff UPDATING /tmp/UPDATING | cut -c 2-1000 | sed -e 1d | sed -e :a -e '$d;N;2,4ba' -e 'P;D'
20101120:
AFFECTS: users of x11-toolkits/gtk20 and x11-toolkits/gtkmm24
AUTHOR: FreeBSD GNOME Team <gnome@FreeBSD.org>

In the GNOME 2.32 release. gdk-pixbuf2 has been split off from gtk20,
and atkmm has been split off from gtkmm24. To upgrade please use the
following instructions:

Portmaster users:

# pkg_delete -f gtkmm-2.20\* gtk-2.20\*
# portmaster -a

Portupgrade users:

# pkgdb -fF
# pkg_deinstall -fO gtkmm-2.20\* gtk-2.20\*
# portupgrade -aOW

20101118:
AFFECTS: users of editors/emacs-devel
AUTHOR: Ashish SHUKLA <ashish@FreeBSD.org>

Due to a bug when upgrading from 24.0.50.101606, everything
installed by other ports in "${PREFIX}/share/emacs" gets removed.

Before upgrading:

* Please backup custom configurations in "${PREFIX}/share/emacs".
* After upgrading reinstall any ports that may have had files in the
"${PREFIX}/share/emacs" directory.

Apologies for this inconvenience.


I also fixed the second request about ports/packages. The 3.1 and 3.2 request can't happen, it's a portmaster thing.
Its just matter of adding another case with portmaster and its arguments, its needless to create separate scripts for that ;)

rbelk
November 22nd, 2010, 23:42
Thanks Vermaden for the input. I have added your suggestions and put the script up on Google Code. Here's the URL, PMM (http://code.google.com/p/pmmenu/)
Anyone can file a bug report or feature request on the PMM site.
When I modify this script I will post updates to this thread.

vermaden
November 23rd, 2010, 09:39
Welcome.

graudeejs
December 3rd, 2010, 14:04
I've udpated my ftpwlist script. This also fixes some bugs :)
http://hg.bsdroot.lv/aldis/ftpwlist/

teckk
December 13th, 2010, 21:28
A small script that I have used to convert a directory of audio files from any of .ra .rm .ram or .wma to .mp3 files with the same name.
It uses mplayer to dump the audio to .wav
It uses lame to encode the .wav to .mp3
It keeps the original audio file
It removed the .wav file.

#!/bin/sh
# Change file type references accordingly. This will change .ra .ram .rm .wma to .mp3
# Uses Mplayer to dump to .wav. Encode with lame to mp3

for i in *.ra
do
if [ -f "$i" ]; then
rm -f "$i.wav"
mkfifo "$i.wav"

# Mplayer options here
mplayer -vc dummy -vo null -ao pcm:file="$i.wav" "$i" &
dest=`echo "$i"|sed -e 's/ra$/mp3/'`

# Lame options here
lame --resample 16 -b 16 "$i.wav" "$dest"

# Remove the mt .wav file
rm -f "$i.wav"
fi
done

ProFTP
December 21st, 2010, 03:21
mac.txt
/121.conf:NETIF="ifname=eth0,mac=00:18:51:23:9E:B3,host_ifname=veth 121.0,host_mac=00:18:51:E1:A5:51,bridge=vmbr0"
./101.conf:NETIF="ifname=eth0,mac=00:18:51:1C:67:42,host_ifname=veth 101.0,host_mac=00:18:51:F5:63:28,bridge=vmbr0"
./151.conf:NETIF="ifname=eth0,mac=00:18:51:AE:93:C1,host_ifname=veth 555.0,host_mac=00:18:51:5A:EC:85,bridge=vmbr1"
./106.conf:NETIF="ifname=eth0,mac=00:18:51:FE:3B:14,host_ifname=veth 106.0,host_mac=00:18:51:D1:76:D2,bridge=vmbr0"
./555.conf:NETIF="ifname=eth0,mac=00:18:51:AE:93:C1,host_ifname=veth 555.0,host_mac=00:18:51:5A:EC:85,bridge=vmbr1"
./111.conf:NETIF="ifname=eth0,mac=00:18:51:20:60:D4,host_ifname=veth 111.0,host_mac=00:18:51:4E:5A:24,bridge=vmbr1"
./108.conf:NETIF="ifname=eth0,mac=00:18:51:22:A8:2B,host_ifname=veth 108.0,host_mac=00:18:51:65:AD:AF,bridge=vmbr1"
./126.conf:NETIF="ifname=eth0,mac=00:18:51:93:2A:0A,host_ifname=veth 126.0,host_mac=00:18:51:77:D4:1B,bridge=vmbr0"
./102.conf:NETIF="ifname=eth0,mac=00:18:51:F6:85:E5,host_ifname=veth 102.0,host_mac=00:18:51:99:49:34,bridge=vmbr0"
./103.conf:NETIF="ifname=eth0,mac=00:18:51:68:07:A0,host_ifname=veth 103.0,host_mac=00:18:51:8F:1E:19,bridge=vmbr0"
./104.conf:NETIF="ifname=eth0,mac=00:18:51:30:42:9C,host_ifname=veth 104.0,host_mac=00:18:51:E0:BD:5B,bridge=vmbr0"
./107.conf:NETIF="ifname=eth0,mac=00:18:51:76:76:92,host_ifname=veth 107.0,host_mac=00:18:51:BA:2A:EA,bridge=vmbr1"
./110.conf:NETIF="ifname=eth0,mac=00:18:51:F6:85:E5,host_ifname=veth 102.0,host_mac=00:18:51:99:49:34,bridge=vmbr0"


perl -MData::Dumper -0x0a -lne '$hash->{$1}++ while $_ =~ /(((?:(\d{1,2}|[a-fA-F]{1,2}){2})(?::|-*)){6})/smg; END { print Dumper $hash }' maс.txt



$VAR1 = {
'00:18:51:93:2A:0A' => 1,
'00:18:51:1C:67:42' => 1,
'00:18:51:FE:3B:14' => 1,
'00:18:51:99:49:34' => 2,
'00:18:51:65:AD:AF' => 1,
'00:18:51:F5:63:28' => 1,
'00:18:51:BA:2A:EA' => 1,
'00:18:51:F6:85:E5' => 2,
'00:18:51:4E:5A:24' => 1,
'00:18:51:76:76:92' => 1,
'00:18:51:E0:BD:5B' => 1,
'00:18:51:E1:A5:51' => 1,
'00:18:51:D1:76:D2' => 1,
'00:18:51:30:42:9C' => 1,
'00:18:51:AE:93:C1' => 2,
'00:18:51:77:D4:1B' => 1,
'00:18:51:8F:1E:19' => 1,
'00:18:51:23:9E:B3' => 1,
'00:18:51:5A:EC:85' => 2,
'00:18:51:22:A8:2B' => 1,
'00:18:51:20:60:D4' => 1,
'00:18:51:68:07:A0' => 1
};




MAC regex: http://www.perlmonks.org/?node_id=83405

graudeejs
December 25th, 2010, 05:00
I wrote this script (adjust as needed) to debug cgi module without using web server
Adjust red lines. Note: It ain't perfec, but it helps A Lot

testcgi.sh
#!/bin/sh

URL="http://example.com/edit?id=8394"
cookie_="SID=b96846d846asdd68a4sd6848asdasd"
post_="url_title=test&url_description=test&url=test&public=Y&submit=Update"
export SERVER_PORT="80"
cgi_name="./Linx.pl"

#=================================================

get_=`echo $URL | sed -e s'/.*?//'`
post=$(echo "$post_" | sed -f urlencode.sed)

if [ $post_ ]; then
export REQUEST_METHOD="POST"
else
export REQUEST_METHOD="GET"
fi
export SERVER_PROTOCOL=`echo $URL | sed -e 's#://.*$##'`
export SERVER_NAME=`echo $URL | sed -E -e 's#^.+//##' -e 's#/.*$##'`
export PATH_INFO=`echo $URL | sed -E -e 's#\?.*##' -e 's#^.*://##' -e "s#^$SERVER_NAME##"`
export CONTENT_LENGTH=`expr "$post" : '.*'`
export QUERY_STRING=$(echo "$get_" | sed -f urlencode.sed)
export HTTP_COOKIE="$cookie_"

echo $post | $cgi_name


urlencode.sed

s/%/%25/g
#s/\$/%24/g
#s/&/%26/g
#s/+/%26/g
s/,/%2c/g
#s/\//%2f/g
#s/:/%3a/g
#s/;/%3b/g
#s/=/%3d/g
#s/\?/%3f/g
#s/@/%40/g
s/ /%20/g
s/"/%22/g
s/</%3c/g
s/>/%3e/g
s/#/%23/g
s/{/%7b/g
s/}/%7d/g
s/|/%7c/g
s/\\/%5c/g
s/\^/%5e/g
s/~/%7e/g
s/\[/%5b/g
s/\]/%5d/g
s/`/%60/g
s/ /%09/g

graudeejs
December 27th, 2010, 00:00
Oneliner to send some zfs snapshots (that contain "bak" in snapshot name) to remote host and compress them with xz
I compressed snapshots on target pc, because pc that was sending snapshots was much slower.
Link between was direct 1Gbps connection

# for i in `zfs list -t snapshot -H | grep bak | awk '{print $1'}`; do zfs send $i | ssh backup.pc xz \> `echo $i | sed 's#/#__#g'`.xz; done


This requires sh compatible shell and configured ssh with pub/private key authorization

darkshadow
February 8th, 2011, 00:52
While using video down loader plug-in for Firefox , youtube-dl script ,and gnash I had many problem and sometime they refuse to download the video , I wrote this small script with only one dependence wget (no php perl or any thing else), I hope you will enjoy it :).

Usage:

./script-name vid-url

carlton_draught
March 21st, 2011, 05:07
This script, called "status_beep", will cause the PC speaker in FreeBSD to beep after success or failure of a long script. e.g.
status_beep 2 "portmaster -a"

I realize that for example, portmaster puts its status (e.g. 1/2) in the terminal title bar, but it's nice to be able to minimize and not be distracted by a lengthy build while working on other stuff (even away from the computer), but be diverted back instantly with a failure beep if something hasn't worked. Or a success beep, so that you can continue with whatever it was you were doing.

I put the beeping functionality first in my zxfer, but then I thought that there is a need to have this sort of thing in a lot of different applications, not just backups. E.g. updating ports, encoding, etc. In the spirit of Unix, it's nice to have small applications that can use or be used by other applications. And this way I can get the functionality I want without having to pester someone. Enjoy. :)

!/bin/sh

# This program is used to execute another program and sound a beep on completion,
# with a tune corresponding to the exit status of the program's execution.

beep_type=$1
line_to_execute=$2

#
# Print out usage information
#
usage() {
cat <<EOT
usage:
# status_beep beep_type line_to_execute

Where beep_type is a "1" or a "2".
1 beeps on failure, 2 beeps on success or failure.
And line_to_execute is a unix shell command, e.g "portmaster -a"

Example:
# status_beep 2 "portmaster -a"

EOT
}

# main program starts here

# syntax error testing
if [ "$beep_type" != "1" -a "$beep_type" != "2" ]; then
echo "You must specify a beep type."
usage
exit 1
fi


if [ "$line_to_execute" = "" ]; then
echo "You must specify a line to execute."
usage
exit 1
fi

# load the speaker kernel module if not loaded already
speaker_km_loaded=$(kldstat | grep -c speaker.ko)
if [ $speaker_km_loaded = "0" ]; then
kldload "speaker"
fi

# Execute the line we are trying to execute
$line_to_execute

# Beep appropriately
if [ $? -eq 0 ]; then
# Success
if [ "$beep_type" = "2" ]; then
echo "T255CCMLEG~EG..." > /dev/speaker # success sound
fi
else
# Failure
echo "T150A<C.." > /dev/speaker # failure sound
fi

exit 0

vermaden
March 23rd, 2011, 08:38
If you are an Openbox user, then this script will generate a 'recent used files' submenu, like in CrunchBang Linux, but without need for additional GAWK package.

Use that in menu.xml file:
grep recent ~/.config/openbox/menu.xml
<menu id="recent" label="recent" execute="openbox_recent.sh" />

#! /bin/sh

LC_ALL=C
MAX=48
COUNT=0
echo "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
echo "<openbox_pipe_menu>"
tail -r ~/.recently-used.xbel \
| grep -E "(href|exec)" \
| while read I
do
case $(( ${COUNT} % 2 )) in
(0) CMD=$( echo "${I}" | grep -o -E "&apos;.*&apos;" | sed -e s/'&apos;'//g | cut -d % -f 1 | sed 's/[ ]*$//') ;;
(1) echo "${I}" | grep href 1> /dev/null 2> /dev/null || continue
FILE=$( echo "${I}" | tr ' ' '\n' | grep href | cut -d \" -f 2 | sed -e s/%22/\'/g -e s/%3C/\</g -e s/%3E/\>/g -e s/%20/\ /g -e s/'file:\/\/'//g )
echo " <item label=\"$( echo ${FILE} | sed -e s/_/__/g -e 's,.*/,,' ) ($( echo ${CMD} | sed -e s/_/__/g ))\">"
echo " <action name=\"Execute\">"
echo " <command>${CMD} '${FILE}'</command>"
echo " </action>"
echo " </item>"
;;
esac
COUNT=$(( ${COUNT} + 1 ))
[ ${COUNT} -lt $(( 2 * ${MAX} )) ] || break
done
echo " <separator />"
echo " <item label=\"clear\">"
echo " <action name=\"Execute\">"
echo " <command>rm -f ~/.recently-used.xbel</command>"
echo " </action>"
echo " </item>"
echo "</openbox_pipe_menu>"



EDIT:

I have also added info which application would be used.

graudeejs
March 25th, 2011, 14:41
Here are my scripts for installing FreeBSD:
http://hg.bsdroot.lv/aldis/install-scripts/summary

Currently only 2 scripts, available:

for installing base FreeBSD with ZFS on my laptop
for adding packages



probably more will come

carlton_draught
April 23rd, 2011, 02:51
Here is my vb2wiki.perl script. It is useful for converting one of these forum posts (e.g. a howto) to Google Code wiki format. I wrote it so that it adequately converts howtos as I write them. Your writing style might use vbulletin forum markup in ways I don't and tags that I don't, and may not give correct output in those cases. In which case, you can either modify the script or write things in the style I do or use the same subset of vbulletin forum markup that I do.

#!/usr/local/bin/perl
# Copyright (c) 2011 Ivan Nash Dreckman
# All rights reserved.
# BSD 2 clause license: see http://www.freebsd.org/copyright/freebsd-license.html
# Version: 0.1, 20110423
#
# Program name: vb2wiki
# Converts vbulletin forum post to Google Code wiki format
# usage: # ./vb2wiki vb_post.txt
# output: vb_post.wiki
#
use strict;
use warnings;

# Read the input file argument, and change/add .wiki extension
my $input_file = "";
chomp($input_file=$ARGV[0]);
$_ = $input_file;
if (/\./)
{
s/\.[^.]+$/.wiki/g;
}
else
{
$_ = "$_.wiki"
}
my $output_file = $_;


open(INFO, $input_file);
my @lines = <INFO>;
close(INFO);
my @newlines = ();

foreach $_ (@lines)
{
chop $_;
$_ = &translate_size($_,"5","=");
$_ = &translate_size($_,"4","==");
$_ = &translate_size($_,"3","===");
$_ = &translate_cmd($_);
$_ = &translate_url($_);
$_ = &translate_file($_);

# translate bold tag
s/\[B\]/*/g;
s/\[\/B\]/*/g;

# translate italic tag
s/\[I\]/_/g;
s/\[\/I\]/_/g;

# translate CODE tag
s/\[CODE\]/{{{\n/g;
s/\[\/CODE\]/\n}}}/g;

push(@newlines,"$_\n");
}

@lines = ();

my @list_type = "nolist";
my $amount_to_indent=1;

# translate numbered and bulleted lists
foreach $_ (@newlines)
{
chop $_;
if (/\[LIST\]/)
{
push(@list_type,"bullet");
}
elsif (/\[LIST=1\]/)
{
push(@list_type,"numbers");
}
elsif (/\[\/LIST\]/)
{
pop(@list_type);
}
else
{
my $spaces_to_indent = (@list_type - 1) * 2;
if (/\[\*\]/)
{
s/\[\*\]//g;
my $space = ' ' x $spaces_to_indent;
if ("$list_type[$#list_type]" eq "bullet")
{
$_ = "$space* $_";
}
elsif ("$list_type[$#list_type]" eq "numbers")
{
$_ = "$space# $_";
}
else
{
print "Bad list\n";
exit 1;
}

}
push(@lines,"$_\n");
}
}

open(INFO, ">$output_file");
print INFO @lines;
close(INFO);
# end of main part


# functions
sub translate_size
{
$_ = $_[0];
# print "this $_\n";
if (/\[SIZE="$_[1]"\]/)
{
s/\[SIZE="$_[1]"\]/$_[2]/g;
s/\[\/SIZE\]/$_[2]/g;
}
$_;
}


sub translate_url
{
$_ = $_[0];
if (/\[URL="/)
{
s/\[URL="/\[/g;
s/"\]/ /g;
s/\[\/URL\]/]/g;
}
$_;
}


# This works using the code block method
sub translate_cmd
{
$_ = $_[0];
if (/\[CMD="/)
{
s/\[CMD="/{{{\n/g;
s/"\]/ /g;
s/\[\/CMD\]/\n}}}/g;
}
$_;
}


sub translate_file
{
$_ = $_[0];
if (/\[FILE\]/)
{
s/\[FILE\]/<font color="green">/g;
s/\[\/FILE\]/<\/font>/g;
}
$_;
}

vivek
April 25th, 2011, 01:38
Set apache / nginx DocumentRoot permission to read and root only.
#!/bin/sh
_dir="${1:-.}"
_fperm="0444"
_dperm="0445"
_ugperm="root:root"
chown -R "${_ugperm}" "$_dir"
chmod -R "${_fperm}" "$_dir"
find "$_dir" -type d -print0 | xargs -0 -I {} chmod $_dperm {}


Go to vhost like
cd /home/httpd/domains/e/example.com && ~/bin/drootreadonly
cd /home/httpd/domains/f/freebsd.org && ~/bin/drootreadonly
~/bin/drootreadonly /path/to/vhost/http

graudeejs
April 25th, 2011, 15:28
Here are scripts I wrote, to search and open manpages in www/surf web frowser

http://hg.bsdroot.lv/aldis/dot.fvwm/file/tip/bin/man_cache.sh
http://hg.bsdroot.lv/aldis/dot.fvwm/file/tip/bin/man_menu.sh

More info here (http://forums.freebsd.org/showpost.php?p=132254&postcount=324)

graudeejs
May 22nd, 2011, 20:11
Wrote a small perl script dicewaregen (http://hg.bsdroot.lv/aldis/dicewaregen/) that generates a Diceware dictionary that you can use to create secure passwords.

More info about Diceware: http://world.std.com/~reinhold/diceware.html.

When I have more time, I will update the script so it can output nice LaTeX documents with an easy-to-print dictionary :)

Also submitted port: security/p5-dicewaregen (not available yet).

graudeejs
May 22nd, 2011, 23:28
Wrote small perl script dicewaregen (http://hg.bsdroot.lv/aldis/dicewaregen/) that generated Diceware dictionary that you can use to create secure password

More info about Diceware: http://world.std.com/~reinhold/diceware.html

When I have more time, I will update script so it can output nice LaTeX document with easy-to-print dictionary :)

Also submitted port: security/p5-dicewaregen (not available yet)

I couldn't resist and added support for LaTeX output :)

vermaden
June 13th, 2011, 13:05
The script below will generate system status line using the dzen2 package like that:
http://ompldr.org/vOTFpcQ

Some DZEN2 documentation:
http://dzen.geekmode.org/dwiki/doku.php?id=dzen:command-and-option-list
http://dzen.googlecode.com/svn/trunk/README

dzen.sh
#! /bin/sh

date +"^fg(#aaaaaa)date: ^fg(#eeeeee)%Y/%m/%d/%A/%H:%M" | tr '[A-Z]' '[a-z]' | tr -d '\n'

echo -n " ^fg(#dd0000)| ^fg(#aaaaaa)cpu: ^fg(#eeeeee)"

CPU=0
top -b 8 \
| sed 1,8d \
| grep -o -E "[0-9]+\.[0-9]+%" \
| awk -F '.' '{print $1}' \
| while read I
do
CPU=$(( ${CPU} + ${I} ))
echo ${CPU}
done | tail -1 | tr -d '\n'

echo -n "%/"

sysctl -n dev.cpu.0.freq | tr -d '\n'

echo -n "MHz/"

sysctl -n dev.cpu.0.temperature | awk -F '.' '{print $1}' | tr -d '\n'

echo -n "C ^fg(#dd0000)| ^fg(#aaaaaa)load: ^fg(#eeeeee)"

sysctl -n vm.loadavg | tr -d -c ' [0-9].' | sed -e 's/\(.*\)./\1/' -e 's/^.\{1\}//g' | tr ' ' '/' | tr -d '\n'

echo -n " ^fg(#dd0000)| ^fg(#aaaaaa)ps: ^fg(#eeeeee)"

sysctl vm.vmtotal | grep -m 1 Processes | grep -o -E ":\ [0-9]+" | tr -d ' :' | tr '\n' '/' | sed 's/\(.*\)./\1/' | tr -d '\n'

echo -n " ^fg(#dd0000)| ^fg(#aaaaaa)mem: ^fg(#eeeeee)"

MEM_PAGE=$( sysctl -n hw.pagesize )
MEM_SIZE=$(( $( sysctl -n vm.stats.vm.v_page_count ) * ${MEM_PAGE} / 1024 / 1024 ))
MEM_INCT=$(( $( sysctl -n vm.stats.vm.v_inactive_count ) * ${MEM_PAGE} / 1024 / 1024 ))
MEM_FREE=$(( $( sysctl -n vm.stats.vm.v_free_count ) * ${MEM_PAGE} / 1024 / 1024 ))
MEM_USED=$(( ${MEM_SIZE} - ${MEM_FREE} ))

echo -n "$(( 100 * ${MEM_USED} / ${MEM_SIZE} ))%/$(( ${MEM_INCT} + ${MEM_FREE} ))M"

echo -n " ^fg(#dd0000)| ^fg(#aaaaaa)ip: ^fg(#eeeeee)$( if_ip.sh )"

echo -n "^fg(#dd0000)| ^fg(#aaaaaa)vol/pcm: ^fg(#eeeeee)$( ( mixer -s vol 2> /dev/null || echo - ) | cut -d ':' -f 2 )/$( ( mixer -s pcm 2> /dev/null || echo - ) | cut -d ':' -f 2 )"

echo -n " ^fg(#dd0000)| ^fg(#aaaaaa)fs: ^fg(#eeeeee)"

zpool list storage | tail -1 | awk '{print $5 "/" $4}' | tr -d '\n'

echo -n " ^fg(#dd0000)| ^fg(#aaaaaa)bat: ^fg(#eeeeee)$( battery.sh 0 0 )"

# KEEP THIS - [ENTER] AT THE END IS NEEDED
echo

Other needed scripts are:
if_ip.sh
#! /bin/sh

ifconfig | grep -v 127.0.0.1 | grep -q "inet " || {
echo -n "none "
exit 1
}

for I in $( ifconfig -l | sed s/lo0//g )
do
ifconfig ${I} | grep -q "inet " && {
echo -n "${I}/"
ifconfig ${I} | grep "inet " | awk '{print $2}' | tr '\n' ' '
}
done

battery.sh
#! /bin/sh

__exit() {
echo "ER: such battery not exist"
exit 1
}

__time() {
acpiconf -i ${1} 1> /dev/null 2> /dev/null || __exit
OUTPUT=$( acpiconf -i ${1} )
if echo "${OUTPUT}" | egrep -q "present|unknown"
then
echo -n "0:0"
else
TIME=$( echo "${OUTPUT}" | grep "time" | awk '{print $3}' )
HOUR=$( echo "${TIME}" | awk -F':' '{print $1}' )
MINS=$( echo "${TIME}" | awk -F':' '{print $2}' )
echo -n "${HOUR}:${MINS}"
fi
}

__sum() {
TOTAL=0
for I in ${@}
do
HOUR=$( echo ${I} | awk -F':' '{print $1}' )
MINS=$( echo ${I} | awk -F':' '{print $2}' )
TOTAL=$(( ${TOTAL} + ${MINS} + ${HOUR} * 60 ))
done
if [ ${TOTAL} -gt 720 ]
then
echo -n "[calculating]"
else
MINS=$(( ${TOTAL} % 60 ))
[ ${MINS} -lt 10 ] && MINS="0${MINS}"
echo -n "$(( ${TOTAL} / 60 )):${MINS}"
fi
}

__info() {
acpiconf -i ${1} 1> /dev/null 2> /dev/null || __exit
OUTPUT=$( acpiconf -i ${1} )
if echo "${OUTPUT}" | grep -q "present"
then
echo "[gone]"
exit
fi
if ! echo "${OUTPUT}" | grep -q "unknown"
then
__sum $( __time ${1} )
echo -n " "
fi
PERCENT=$( echo "${OUTPUT}" | grep -i "remaining capacity" | awk '{print $3}' )
if [ ${AC} -eq 1 ]; then
STATE=$( echo "${OUTPUT}" | grep rate | awk '{print $3}' )
if [ ${STATE} -eq 11 -a "${PERCENT}" = "100%" ]
then
echo "(${PERCENT}) [charged]"
else
echo "(${PERCENT}) [charging]"
fi
else
echo "(${PERCENT}) [discharging]"
fi
}

__infolite() {
acpiconf -i ${1} 1> /dev/null 2> /dev/null || __exit
OUTPUT=$( acpiconf -i ${1} )
if echo "${OUTPUT}" | grep -q "present"
then
echo "[gone]"
exit
fi
if ! echo "${OUTPUT}" | grep -q "unknown"
then
__sum $( __time ${1} )
fi
PERCENT=$( echo "${OUTPUT}" | grep -i "remaining capacity" | awk '{print $3}' )
if [ ${AC} -eq 1 ]; then
STATE=$( echo "${OUTPUT}" | grep rate | awk '{print $3}' )
if [ ${STATE} -eq 11 -a "${PERCENT}" = "100%" ]
then
echo "${PERCENT}/+"
else
echo "${PERCENT}/+"
fi
else
PERC_INT=$( echo ${PERCENT} | tr -d '%' )
[ ${PERC_INT} -lt 11 ] && {
echo "/\${color #dd0000}${PERCENT}\${color}/-"
} || {
echo "/${PERCENT}/-"
}
fi
}

AC=$( sysctl -n hw.acpi.acline )

case ${#} in

(0)
if [ ${AC} -eq 1 ]
then
echo "[A/C]"
exit 0
fi
__sum $( __time 0 ) $( __time 1 )
echo
;;

(1)
__info ${1}
;;

(2)
__infolite ${1}
;;

(*)
echo "usage: $( basename ${0} ) [BATTERY]";
exit 1;
;;

esac


Usage (in ~/.xinitrc file):

while sleep 1
do
dzen.sh
done | dzen2 -fn '-*-fixed-medium-*-*-*-*-100-*-*-*-*-iso8859-2' -bg "#333333"

UNIXgod
July 4th, 2011, 22:02
This is my jail supervisor. It's a simple script that transverses all the running jails on the system and sends a status report email to the administrator on what ports need updating.

I like to leave little easter eggs in my scripts. It also generates a fortune to give a lonely admin the incentive to read the report =)

My servers name is HAL9000 hence the fun wrapped quotes from the space odyssey.

#!/bin/sh
################################################## ########################
# Title : jsvisor - BSD jail superviser
# Author : Stuart Gerstein <UNIXgod@ruby<no-spam>programmer.net>
# Date : 2010-09-19
# Requires : FreeBSD
# Category : File Utilities
################################################## ########################
# Description
# o "jsvisor" simply runs pkg_version or portversion on currently
# running jails. It will generate an email to be sent to the admin.
# o NOTES: jsvisor will prefer portversion over pkg_version furthermore
# when portversion is not present in the jail pkg_version is used.
# Examples:
# This utility is meant for use by the cron(8) facility.
# enter administrators email under the variable ADMIN below
################################################## ########################


ADMIN=YOU@YOUREMAIL.NET # THIS NEEDS TO BE SET

J=`jls | tail -n +2 | awk '{print $1}'`
host=`hostname`

pkg_v=/usr/sbin/pkg_version
portv=/usr/local/sbin/portversion

x=1
jailportversion() {
for I in $J; do
echo "************************************************** ******************************" #80 char
jwhich=`jls | tail -n +2 | awk '{print $3}' | head -${x} | tail +${x}`
if (jexec $I [ -x $portv ]);
then
echo "Executing `basename ${portv}` in jail: ${jwhich}";
echo "${jwhich}'s JID is ${I}"; echo;
jexec $I ${portv} -vL=; echo;
else
echo "Executing `basename ${pkg_v}` in jail ${jwhich}";
echo "${jwhich}'s JID is ${I}"; echo;
jexec $I ${pkg_v} -v -l '<'; echo;
fi
x=`expr ${x} + 1`
done
}
degenerated=`jailportversion`

# uncomment below when testing
#cat <<EOF
mail -s "'${host} jail ports version output" ${ADMIN} <<EOF
Generating summery of UNIX jails
`hostname` at `date`.
****************************
There are currently `jls | tail +2 | wc -l | awk '{print $1}'` running jails:
`jls -d`
****************************
HAL9000: This mission is too important for me to allow you to jeopardize it.

${degenerated}

`/usr/games/fortune -a`

HAL9000: Do you want me to repeat the message, Dr. Floyd?
EOF

vermaden
July 5th, 2011, 08:25
... mostly an update for this post: http://forums.freebsd.org/showpost.php?p=137284&postcount=122

http://ompldr.org/vOWQwNA

~/scripts/xmobar.sh
#! /bin/sh

date +"<fc=#AAAAAA>date:</fc> <fc=#EEEEEE>%Y/%m/%d/%A/%H:%M</fc>" | tr '[A-Z]' '[a-z]'
echo -n " <fc=#dd0000>|</fc> <fc=#aaaaaa>cpu:</fc> <fc=#eeeeee>"
top -b -o res | awk 'NR>8 { gsub(/%/,"",$0); CPU+=$11; } END { split(CPU,cpu,"."); print cpu[1]; }'
echo -n "%/"
sysctl -n dev.cpu.0.freq
echo -n "MHz/"
sysctl -n dev.cpu.0.temperature | awk -F '.' '{print $1}'
echo -n "C</fc> <fc=#dd0000>|</fc> <fc=#aaaaaa>load:</fc> <fc=#eeeeee>"
sysctl -n vm.loadavg | awk '{ print substr($2,0,3) "/" substr($3,0,3) "/" substr($4,0,3) }'
BOOT=$( sysctl -n kern.boottime | awk 'match($0, / sec = [0-9]+/) { $0 = substr($0, RSTART, RLENGTH); print $3 }' )
DATE=$( date +%s )
echo -n " <fc=#dd0000>|</fc> <fc=#aaaaaa>uptime:</fc> <fc=#eeeeee>$( date -r $(( ${DATE} - ${BOOT} - 3600 )) +"%k:%M" | tr -d ' ' )</fc>"
echo -n "</fc> <fc=#dd0000>|</fc> <fc=#aaaaaa>ps:</fc> <fc=#eeeeee>"
sysctl -n vm.vmtotal | awk 'match($0, /Processes/) { gsub(/\)/,"",$11); print $3 "/" $6 "/" $9 "/" $11 }'
echo -n "</fc> <fc=#dd0000>|</fc> <fc=#aaaaaa>mem:</fc> <fc=#eeeeee>"
MEM_PAGE=$( sysctl -n hw.pagesize )
MEM_SIZE=$(( $( sysctl -n vm.stats.vm.v_page_count ) * ${MEM_PAGE} / 1024 / 1024 ))
MEM_INCT=$(( $( sysctl -n vm.stats.vm.v_inactive_count ) * ${MEM_PAGE} / 1024 / 1024 ))
MEM_FREE=$(( $( sysctl -n vm.stats.vm.v_free_count ) * ${MEM_PAGE} / 1024 / 1024 ))
MEM_USED=$(( ${MEM_SIZE} - ${MEM_FREE} - ${MEM_INCT} ))
echo -n "$(( 100 * ${MEM_USED} / ${MEM_SIZE} ))%/$(( ${MEM_USED} ))M"
echo -n "</fc> <fc=#dd0000>|</fc> <fc=#aaaaaa>ip:</fc> <fc=#eeeeee>$( if_ip.sh )</fc>"
echo -n "<fc=#dd0000>|</fc> <fc=#aaaaaa>vol/pcm:</fc> <fc=#eeeeee>$( mixer -s vol | awk -F ':' '{printf("%s",$2)}' )/$( mixer -s pcm | awk -F ':' '{printf("%s",$2)}' )</fc> "
echo -n "<fc=#dd0000>|</fc> <fc=#aaaaaa>fs:</fc> <fc=#eeeeee>"
zpool list storage | awk 'END{print $5 "/" $4}'
echo -n "</fc> <fc=#dd0000>|</fc> <fc=#aaaaaa>bat:</fc> <fc=#eeeeee>$( battery.sh )</fc>"

~/scripts/xmobar_loop.sh
#! /bin/sh

while sleep 2
do
echo -n ' '
xmobar.sh | tr -d '\n'
echo
done | xmobar ~/.xmobarrc &

~/scripts/if_ip.sh
#! /bin/sh

case $( ifconfig | grep -c "inet " ) in
(1)
echo -n "none "
exit 0
;;
(*)
for I in $( ifconfig -l | sed s/lo0//g )
do
ifconfig ${I} | awk -v INTERFACE=${I} 'match($0, /inet /) { printf("%s/%s ",INTERFACE,$2) }'
done
;;
esac

~/scripts/battery.sh
#! /bin/sh

LIFE=$( sysctl -n hw.acpi.battery.life )
case $( sysctl -n hw.acpi.acline ) in
(1)
echo "AC/${LIFE}%"
;;
(0)
TIME=$( sysctl -n hw.acpi.battery.time )
HOUR=$(( ${TIME} / 60 ))
MINS=$(( ${TIME} % 60 ))
[ ${MINS} -lt 10 ] && MINS="0${MINS}"
echo "${HOUR}:${MINS}/${LIFE}%"
;;
esac

EDIT: I forgot the ~/.xmobarrc file ;)

~/.xmobarrc
Config { font = "xft:inconsolata:size=10:antialias=true"
, bgColor = "#222222"
, fgColor = "grey"
, border = NoBorder
, borderColor = "#bb00dd"
, position = Static { xpos=1 , ypos=1, width=1438, height=11 }
, lowerOnStart = True
, commands = [ Run StdinReader ]
, sepChar = "%"
, alignSep = "}{"
, template = "%StdinReader% "
}

graudeejs
July 5th, 2011, 09:12
@ Vermaden,

Why do you do it dzen style? (not that it's better or worse, but it makes things complicated)
xmobar, can read some config file (which is haskell file) and call all your wild scripts from there, with custom delays, avoiding custom loops in sh.

Check this out:
xmobar.hs (http://hg.bsdroot.lv/aldis/dot.xmonad/file/tip/xmobar.hs) (in Run lines, last argument is update interval in seconds*10 [That is for 1 second, you write 10])
mixer.sh (http://hg.bsdroot.lv/aldis/dot.xmonad/file/tip/bin/mixer.sh)
layout.sh (http://hg.bsdroot.lv/aldis/dot.xmonad/file/tip/bin/layout.sh)
colorload.sh (http://hg.bsdroot.lv/aldis/dot.xmonad/file/tip/bin/colorload.sh)

Note that StdinReader, will does what it says it do: read stdin, and write to xmobar.

You can also have some parts aligned to left, center, right :)
If you need more info, let me know

For this to work, you pass filename of xmobar.hs as argument for xmobar, when you exec it

vermaden
July 5th, 2011, 09:49
Why do you do it dzen style?
Because its not more comfortable for me mate, for example:
Run Com "uname" ["-s","-r"] "" 360000
... if if would allow me to do it that way:
Run Com "uname -s -r" 360000
then it would be fine for me, I would add my 'pipes' here, but with requirement for every argument to be in '"' its PITA for me to put every functionality into separate script while I can have everything in one place.

Yes the argument that putting some less important values into less recent updates will save some CPU power is true, but these 'probes' of mine are very light and consume very little CPU power.

I juts do not want to spread all that 'monitoring' into dozens of little scripts.

graudeejs
August 4th, 2011, 23:06
Today I practiced ruby and wrote v0.0.1 of uncue script

http://hg.bsdroot.lv/aldis/uncue

Right now it's pretty basic script. The purpose of uncue is to uncue. In otherword to split media (currently only audio) files with cue sheet.

I will keep developing this scipt further.
My biggest goal (to split audio files) is however almost achieved.

Some highlights:

Tries to check cue file
Tries to find files to uncue
Keeps metadata
Has bugs :)

I think for my first Ruby script it's pretty good. Especially that I've only spent one day, to write it :)

NOTE: This is so very alpha.... in case you try to uncue your media files, don't throw avay originals for now.

It should be relatively save as long as, cue sheet, has one FILE command and only AUDIO tracks...

Currently it accepts only 1 command line argument, and that argument must be cue filename.
Script depends on multimedia/ffmpeg and lang/ruby19

graudeejs
August 5th, 2011, 21:50
unclue 0.0.2 should be pretty safe to use
http://hg.bsdroot.lv/aldis/uncue

Found a Major bug (in both 0.0.1 and 0.0.2) .... it will be fixed in 0.0.3

graudeejs
August 7th, 2011, 18:28
I was improving my desktop scripts and update agentsCtl.sh script
http://hg.bsdroot.lv/aldis/wmscripts/file/tip/agentCtl.sh

The main purpose of this script was to make sure, that gpg-agent and ssh-agend only run one instance.
I rewrote it pretty well (I think)

As side effect, if you add

eval `"$WMSCRIPTS_DIR/agentCtl.sh" start all`

to your ~/.xinitrc and ~/.shrc I can share agents across X11 and console. Also I can share them accross Logouts :)

In few minutes I will adopt this script to be able to work with csh & frieds

graudeejs
August 25th, 2011, 15:48
Here's script that will exec and then refresh www/uzbl every time some subdirectory is modified.
Useful for web development (Ide from http://railscasts.com/episodes/264-guard), It by no means is a substitute. I was just interested in writing something similar


#!/bin/sh

DIR_REFRESH_TIMEOUT=300

LOCK_FILE=".web-dev-uzbl.tmp"
DEFAULT_CONFIG="${XDG_CONFIG_HOME:-$HOME/.config}/uzbl/config"

updated_dirlist() {
find . -type d | grep -v '/\.' > "$LOCK_FILE"
}

last_updated() {
cat "$LOCK_FILE" | xargs -n 1 ls -d -D %s -l | awk '{print $6}' | sort | tail -n 1
}


if [ -f "$LOCK_FILE" ]; then
rm -f "$LOCK_FILE"
sleep 3
fi

updated_dirlist > "$LOCK_FILE"

{
[ -f "$DEFAULT_CONFIG" ] && cat "$DEFAULT_CONFIG"
echo "uri $1"

LAST_UPDATED=0
i=0
while [ -f "$LOCK_FILE" ]; do
sleep 1
LAST_UPDATED_NOW=`last_updated`
if [ $LAST_UPDATED -lt $LAST_UPDATED_NOW ]; then
echo reload_ign_cache
LAST_UPDATED=$LAST_UPDATED_NOW
fi

i=$(($i+1))
if [ $i -gt $DIR_REFRESH_TIMEOUT ]; then
updated_dirlist
i=0
fi

done

exit

} | uzbl-browser -c -

# vim: set ts=4 sw=4 :

expl
August 25th, 2011, 22:31
It would work 1000 times more efficient and responsive/reliable if you wrote this using kevent api.

graudeejs
August 26th, 2011, 00:25
It would work 1000 times more efficient and responsive/reliable if you wrote this using kevent api.

Inefficient - yes, in-responsive - absolutely not

expl
August 26th, 2011, 19:24
Instant event handler will be very significantly (thousands of times) more responsive than a time out and compare based mechanism. Maybe not so significant in human noticeable units but it will be literally many times more :D.

kpn43
September 8th, 2011, 16:42
I made this script only for myself and couple of friend first, but soon it became much bigger project than I planned so why not share it with everyone. It script for doing much of admin/maintenance stuff within one simple command.

You can find it here: http://kpn.kahvipannu.fi/admin

All opinions and ideas etc. are welcome, but since I'm not on this forum on regular basis it would be nice to get feedback with email.

vermaden
October 4th, 2011, 15:04
Usage:

% dd < /dev/zero > FILE bs=1m count=100
100+0 records in
100+0 records out
104857600 bytes transferred in 2.234466 secs (46927368 bytes/sec)

% ls -lh FILE
-rw-r--r-- 1 vermaden vermaden 100M 2011.10.04 15:00 FILE

% mdconfig.sh -c FILE
IN: created vnode at /dev/md0

% mdconfig.sh -l
md0 vnode 100M /usr/home/vermaden/FILE

% mdconfig.sh -d 0
IN: deleted vnode at /dev/md0

Code:
#! /bin/sh

__usage() {
NAME="$( basename ${0} )"
echo "usage: $( basename ${0} ) OPTION FILE|DEVICE"
echo
echo "options: -l --list - list existing vnode(s)"
echo " -c --create - create new vnode"
echo " -d --delete - delete existing vnode"
echo
echo "examples: ${NAME} -c ~/FILE"
echo " ${NAME} -d 0"
echo " ${NAME} -l"
echo
exit 1
}

[ ${#} -eq 2 -o ${#} -eq 1 ] || __usage

case ${1} in
(-l|--list)
sudo mdconfig -l -v
;;

(-c|--create)
[ -f ${2} ] || {
echo "ER: file '${2}' does not exist"
echo
__usage
}
echo -n "IN: created vnode at /dev/"
sudo mdconfig -a -t vnode -f ${2}
;;

(-d|--delete)
[ -c /dev/md${2} ] || {
echo "ER: device '/dev/md${2}' does not exist"
echo
__usage
}
sudo mdconfig -d -u ${2}
echo "IN: deleted vnode at /dev/md${2}"
;;

(*)
__usage

esac

graudeejs
October 16th, 2011, 20:24
I had enough of updating vim plugins and help tags manually, so I wrote 2 scripts:

This script updates my plugins by downloading tar.gz from github:
update_plugins.sh modified and renamed: https://github.com/graudeejs/dot.vim/blob/master/github_plugin_update.sh

And this script updates all help tags for all doc directories in ~/.vim/
https://github.com/graudeejs/dot.vim/blob/master/update_tags.sh


EDIT, I updated scripts.... so now there's also Makefile:
https://github.com/graudeejs/dot.vim/blob/master/Makefile

enjoy!

frijsdijk
October 29th, 2011, 13:38
Hi
and a script for cvsup ...

Did you know there is csup for quite a while already? Much quicker..

SNK
November 7th, 2011, 19:08
#!/bin/sh
# Hosts file updater
# Originally written by Andy Short circa 2002
HFSERVER="http://hostsfile.mine.nu.nyud.net"
HFILE="hosts.zip"
ORIGFILE="/etc/hosts.original"

echo "
=============================== IMPORTANT ===============================
This script will fetch the lastest set of hosts from
$HFSERVER/$HFILE and append it to your
original hosts file.

Your original hosts file will be renamed to $ORIGFILE.

As a side-effect of this script, any persistent changes you wish to make
to the hosts file should be made to $ORIGFILE because
/etc/hosts will be respawned from (i) $ORIGFILE and (ii) the
set of hosts from the server, each time this script is run.
-------------------------------------------------------------------------
"

if [ ! -f "$ORIGFILE" ] ; then
echo "Backing up your original hosts file."
cp /etc/hosts $ORIGFILE
fi

echo "
======================== Fetching and Extracting ========================

Fetching $HFILE from $HFSERVER.
"

fetch -o /tmp/$HFILE $HFSERVER/$HFILE

if [ ! -f "/tmp/$HFILE" ] ; then
echo "Error in fetching the set of hosts."
exit 1
fi

tar Oxf /tmp/$HFILE | tr -d '\r' > /tmp/hosts

if [ ! -f "/tmp/hosts" ] ; then
echo "Error in extracting the set of hosts."
exit 1
fi

if ! grep -c "banner" /tmp/hosts > /dev/null; then
echo "The fetched set of hosts does not seem to contain relevant hosts."
exit 1
fi

echo "
========================= Respawning /etc/hosts =========================

From (i) $ORIGFILE and (ii) the set of hosts from the server."

cat $ORIGFILE > /etc/hosts

cat <<END >> /etc/hosts &&
#================================================= ============
# This hosts file has been modified with a set of hosts
# obtained from $HFSERVER.
#
# As a side-effect of this script, any persistent changes you
# wish to make to the hosts file should be made to
# $ORIGFILE because /etc/hosts will be respawned
# from (i) $ORIGFILE and (ii) the set of hosts from
# the server, each time this script is run.
#================================================= ============
END

cat /tmp/hosts >> /etc/hosts
rm -f /tmp/hosts
rm -f /tmp/hosts.zip

echo "
======================== Update process complete ========================
"

This script will download a (regularly updated) list of more than 95,000 hostnames used for advertising/etc. and append it to your /etc/hosts file. In subsequent runs, /etc/hosts will be respawned from a copy of your original hosts file (saved to /etc/hosts.original) and the fetched list.

There are several versions of this script online, but all for Linux. So I adapted one for FreeBSD: changed shells/bash to sh, and removed its dependence on ftp/wget, archivers/unzip, and converters/unix2dos.

Comments are welcome: I am new to shell scripting.

-edit-

Please note that the list is quite comprehensive. It includes, e.g.: 127.0.0.1 clients2.google.com
127.0.0.1 clients3.google.com
127.0.0.1 clients4.google.com
127.0.0.1 clients5.google.com These hosts are used to install extensions for Chromium. So uncomment these if necessary.

idle
November 7th, 2011, 19:39
list of more than 95,000 hostnames

Whats wrong with named?

SNK
November 7th, 2011, 19:46
Whats wrong with named?

Can you be more specific? The purpose is to block those hosts.

idle
November 7th, 2011, 21:47
SNK
named - Internet domain name server.
DNS server, that came to substitute hosts file those days, when the quantity of hosts began to grow.

zeroseven
November 8th, 2011, 11:31
I've been reading up on scripting with the bourne shell... I mashed face agains the wall for a few hours putting together a script to check latency on FreeBSD cvsup servers for fetching/updating ports.


#!/bin/sh

#start with cvsup1.freebsd.org
server=1

#intended to error check at the end, haven't implemented yet
fastest=-1

#some absurd latency to compare to initially
seed=2000.0

echo "Pinging cvsup servers..."
while [ $server -le 18 ]
do
speed=`ping -nqt 4 cvsup$server.freebsd.org | \
grep 'round-trip*' | awk '{n=split($4,array,"/"); print array[2];}'`
if [ "$speed" != "" ]
then
result=`echo "$speed < $seed" | bc -l`
if [ "$result" -eq 1 ]
then
seed=$speed
fastest=$server
fi
fi
server=`expr $server + 1`
done;
echo "cvsup$fastest.freebsd.org"


Obviously, this only works for US servers at this point...

Edit: Adding to this, I may have a question for clarification. I came across a few comments on random forums searching for answers, and while looking for the answer to floating point comparison in sh, I noticed a comment talking about how bc returns 1 for true and 0 for false and how it was not "bashlike"... This confused me, but agreed with a statement I read elsewhere, how bash and other GNU implementations of software have catered to poor coding and standards, enforcing worse habits. I guess, I immediately thought of C/C++ that treat 1 or any other non zero value as true and 0 as false. This would make sense as to why other programs such as bc, return 1 for true and 0 for false... Right? Why would bash be any different?

graudeejs
November 8th, 2011, 13:14
Because There is no Unix in Linux

wblock@
November 8th, 2011, 16:44
I've been reading up on scripting with the bourne shell... I mashed face agains the wall for a few hours putting together a script to check latency on FreeBSD cvsup servers for fetching/updating ports.

Remember that lowest latency is not necessarily the fastest. Might want to compare with sysutils/fastest_cvsup.

zeroseven
November 8th, 2011, 17:17
Remember that lowest latency is not necessarily the fastest. Might want to compare with sysutils/fastest_cvsup.

Haha.. I knew there was probably a tool for this, I just didn't put in the legwork to try and find it... Really, I was just looking for an excuse to get my hands dirty with a shell script.. I know some C/C++ and and have a little experience with some other languages. I'm just now starting to read up on things like grep, sed, awk and sh scripting.

graudeejs
December 16th, 2011, 18:07
Here's userscript to switch youtube to html5=1 automatically

// ==UserScript==
// @include http://youtube.com/*
// @include http://*.youtube.com/*
// ==/UserScript==

var l = window.location.href;
var a = l.split('?');
var base_address = a[0];
var params = a[1].split('&');

var html5 = false;
for (var i = 0; i < params.length; i++) {
if (params[i].match(/^html5=/)) {
html5 = true;
break;
}
}

if (html5 == false) {
params.push('html5=1');
var address = [base_address, params.join('&')].join('?');
window.location.href = address;
}