Useful scripts

Dr_Phoenix

Member

Thanks: 8
Messages: 22

#1
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

Code:
#!/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

Code:
#!/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
 

graudeejs

Son of Beastie

Thanks: 686
Messages: 4,611

#3
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)
Code:
#!/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

Active Member

Thanks: 24
Messages: 124

#4
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.

Code:
#! /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

Well-Known Member

Thanks: 72
Messages: 365

#5
I collect my useful scripts in the sysutils/bsdadminscripts port:

sysutils/bsdadminscripts/pkg-descr said:
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.
sysutils/automounter/pkg-descr said:
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.
Code:
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,dmask=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.
 

Dara

New Member

Thanks: 1
Messages: 18

#6
Small script to clean out old amavisd-new stuff if it dosent do a good job by itselft..


mailclean.sh
Code:
#!/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..
 

harisman

New Member

Thanks: 3
Messages: 7

#8
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.

Code:
 #!/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
 

danger@

Administrator
Staff member
Administrator
Moderator
Developer

Thanks: 342
Messages: 980

#10
simple solution is to add the following line into the .cshrc:

Code:
alias rm 'mv -i \!* ~/.Trash'
and create ~/.Trash/ directory.
 

bsddaemon

Active Member

Thanks: 14
Messages: 101

#11
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@

Administrator
Staff member
Administrator
Moderator
Developer

Thanks: 342
Messages: 980

#12
bsddaemon said:
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 :)

bsddaemon said:
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

Active Member

Thanks: 14
Messages: 101

#13
danger@ said:
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:

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

graudeejs

Son of Beastie

Thanks: 686
Messages: 4,611

#15
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/
 

kamikaze

Well-Known Member

Thanks: 72
Messages: 365

#17
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.
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:
Code:
#!/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

New Member

Thanks: 4
Messages: 9

#18
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.

Code:
#!/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

Active Member

Thanks: 6
Messages: 170

#19
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.

Code:
#!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.
 

chalbersma

Member

Thanks: 3
Messages: 92

#22
Torsmo's .torsmo_ip script

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.

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

vermaden

Son of Beastie

Thanks: 1,011
Messages: 2,673

#23
Universal screenshot

A script that will make a screenshot @ FreeBSD/OpenSolaris/Linux OS:

Code:
#! /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
 

graudeejs

Son of Beastie

Thanks: 686
Messages: 4,611

#25
paulfrottawa said:
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
 
Top