Useful scripts

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... :)

Code:
#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 :)
 
vermaden said:
@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.
 
I call this script "Just stay connected you ****!"

Code:
#!/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...
 
rbelk said:
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:
Code:
# 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 ;)
 
Thanks Vermaden for the input. I have added your suggestions and put the script up on Google Code. Here's the URL, PMM
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.
 
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.

Code:
#!/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
 
mac.txt
Code:
/121.conf:NETIF="ifname=eth0,mac=00:18:51:23:9E:B3,host_ifname=veth121.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=veth101.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=veth555.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=veth106.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=veth555.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=veth111.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=veth108.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=veth126.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=veth102.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=veth103.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=veth104.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=veth107.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=veth102.0,host_mac=00:18:51:99:49:34,bridge=vmbr0"


Code:
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

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

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

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

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
Code:
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
 
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
Code:
# 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
 
shell script to download youtube video

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
 

Attachments

  • stable-dwonloadvid.txt
    3 KB · Views: 363
status_beep

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. :)

Code:
!/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
 
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
Code:
<menu id="recent" label="recent" execute="openbox_recent.sh" />

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

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.

Code:
#!/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;
  }
  $_;
}
 
Set apache / nginx DocumentRoot permission to read and root only.
Code:
#!/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
Code:
cd /home/httpd/domains/e/example.com && ~/bin/drootreadonly
cd /home/httpd/domains/f/freebsd.org && ~/bin/drootreadonly
~/bin/drootreadonly /path/to/vhost/http
 
DZEN2 config for FreeBSD system status

The script below will generate system status line using the dzen2 package like that:
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
Code:
#! /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
Code:
#! /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
Code:
#! /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):
Code:
while sleep 1
do
  dzen.sh
done | dzen2 -fn '-*-fixed-medium-*-*-*-*-100-*-*-*-*-iso8859-2' -bg "#333333"
 
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.

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

... mostly an update for this post: http://forums.freebsd.org/showpost.php?p=137284&postcount=122

vOWQwNA


~/scripts/xmobar.sh
Code:
#! /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>$( [FILE]if_ip.sh[/FILE] )</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>$( [FILE]battery.sh[/FILE] )</fc>"

~/scripts/xmobar_loop.sh
Code:
#! /bin/sh

while sleep 2
do
  echo -n ' '
  xmobar.sh | tr -d '\n'
  echo
done | xmobar ~/.xmobarrc &

~/scripts/if_ip.sh
Code:
#! /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
Code:
#! /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
Code:
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% "
       }
 
@ 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 (in Run lines, last argument is update interval in seconds*10 [That is for 1 second, you write 10])
mixer.sh
layout.sh
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
 
killasmurf86 said:
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.
 
Back
Top