Category Archives: Script

For the truly paranoid

HeaderI’ve been reinstalling my system as of late (been way too along a comin’) and I realized that I hadn’t set up a firewall yet. This, in turn, had me think how many ports were open. I was up too late and probably had too many cokes by then. I had given myself a dead simple root password so that I could finish the install and began getting that tightening, turning, wretching in the belly feeling. I couldn’t help thinking that, “This could be the time that some random joe comes along and finds a nice open gate”. Doesn’t make much sense now, but decided then to build a script that toggles a 20 character random password to relieved my paranoia. Here it is for anyone who can find use of it. Oh, and I did get my install done.

#!/bin/bash
# randompass - toggle between random and known passwords for users

# User passwords to protect
users=(root todd akau)

# Program name from it's filename
prog=${0##*/}

# Text color variables
txtund=$(tput sgr 0 1)          # Underline
txtbld=$(tput bold)             # Bold
bldred=${txtbld}$(tput setaf 1) #  red
bldblu=${txtbld}$(tput setaf 4) #  blue
bldwht=${txtbld}$(tput setaf 7) #  white
txtrst=$(tput sgr0)             # Reset
info=${bldwht}*${txtrst}        #
pass=${bldblu}*${txtrst}
warn=${bldred}!${txtrst}

# Check if users exist, if they don't remove from the users array
list="${users[@]/%/|}"    # Puts array to list, add pipe after each user
users=($(grep -Eo "^(${list// })\>" /etc/shadow)) # strip spaces, end of word

# Password generation
passgen=$(< /dev/urandom tr -dc A-Za-z0-9/.$ | head -c20 | xargs | cat)

# Variables for current passwords
for user in ${users[@]}; do
  eval "curpw$user=\$(grep \$user /etc/shadow | awk -F : '{print \$2}')"
done

# Save original passwords (first run)
for save in ${users[@]}; do
  if [ ! -f /root/pass$save ]; then
    grep $save /etc/shadow | awk -F : '{ print $2 }' > /root/pass$save
    echo "$pass Saved ${txtund}$save${txtrst} password"
  fi
done

case $1 in
  h ) echo " $prog <*u>- toggle random and known passwords. u - update known"
      ;;
  u ) echo "$warn Be sure no random passwords are set before updating passwords!"
      echo -n "Update known passwords file(s)? "
      read update
      if [[ $update == [Yy] ]]; then
        for known in ${users[@]}; do
          grep $known /etc/shadow | awk -F : '{ print $2 }' > /root/pass$known
          echo "$pass Updated ${txtund}$known${txtrst} password"
        done
        else
        echo " Passwords not updated"
        exit
      fi
      ;;
  * ) if [[ "$curpwroot" == "$(cat /root/passroot)" ]]; then
        for u in ${users[@]}; do
          usermod -p $passgen $u
          echo "$pass Generated password for ${txtund}$u${txtrst}."
        done
        else
        for u in ${users[@]}; do
          usermod -p $(cat /root/pass$u) $u
          echo "$pass Restored password for ${txtund}$u${txtrst}."
        done
      fi
      ;;
esac

movietime – Stop Powersaving to Watch a Movie

Getting down to watching you favorite movie on your computer? Start the movie, sit down, grab your snack and ten or so minutes later the screen goes blank. This happens in Linux because the desktop has built-in defaults for display power management (DPMS) and screensaving. Timeout settings can vary from distribution to distribution but they all got them. Here’s a basic script that can toggle DPMS and screensaving on and off.

Xorg Server Settings

You can set the values of blank, standby, suspend, and off in the the xorg server configuration file. The defaults are: 15, 20, 30, and 40 minutes. Personally I like to set these to better match how I use my computer:

Section "Monitor"
  Identifier  "Monitor0"
  Option      "DPMS"    "true"  # display power management on (true/false)
EndSection

Section "ServerFlags"
  Option "BlankTime"    "13"    # LED still on, no + (0 disables)
  Option "StandbyTime"  "15"    # turns off LED
  Option "SuspendTime"  "0"     # turns off LED, and most power
  Option "OffTime"      "50"    # turns off all power
EndSection

BlankTime is just a cheap screensaver and only real use for me is to tell me that I forgot to disable dpms while watching a movie. Doing this saves me a few seconds that StandbyTime requires to turn on the display again. SuspendTime and StandbyTime are nearly the same thing so I don’t bother setting SuspendTime.

Movietime

Here’s movietime. Movietime should work with just about any type of desktop environment (at least any system with dbus installed which really all of them do). If you aren’t familiar with having your own scripts and how to run them, take a look at this page).

#!/bin/bash
# movietime - disables power savings to watch movies.

# Movietime options
#  Resume time - resume normal display pm and suspend after set time.
# 0 = disabled, time in minutes
resumetime=0
if [ $resumetime = 0 ]; then 
  resumetime=1440 # Re-enable resume after a full day
fi

# Check that values for 'resumetime' are numbers
if [ $(echo $resumetime | sed 's/^[-+0-9][0-9]*//' | wc -c) != 1 ]; then
  echo "$warn variable 'resumetime' is not a number.  Exiting."
  exit
fi

# Name of suspend script
tmploc="/tmp"
suspinhscript="$tmploc"/"movietime-suspend-inhibit"

# Program name from it's filename.
prog=${0##*/}

# Text color variables
txtund=$(tput sgr 0 1)          # Underline
txtbld=$(tput bold)             # Bold
bldblu=${txtbld}$(tput setaf 4) #  blue
bldwht=${txtbld}$(tput setaf 7) #  white
bldred=${txtbld}$(tput setaf 1) #  red
txtrst=$(tput sgr0)             # Reset
info=${bldwht}*${txtrst}        # Feedback
pass=${bldblu}*${txtrst}
warn=${bldred}*${txtrst}

# Check that Xorg server is running
if [[ -z $(ps aux | grep /usr/bin/X) ]]; then
  echo "$warn The Xorg server is not running."
  exit
fi

# Check if user is regular user
if [ $(whoami) == "root" ]; then
  echo "$warn You are the root user, must be a regular user."
  exit
fi

# Current DPMS times (in minutes)
dispdpms=$(xset -q | grep "DPMS is" | awk '{ printf $3 }') # Enab. or Disb.
dispstand=$(xset -q | grep "^  Standby: " | awk '{ printf $2/60 }')
dispsusp=$(xset -q | grep "^  Standby: " | awk '{ printf $4/60 }')
dispoff=$(xset -q | grep "^  Standby: " | awk '{ printf $6/60 }')
dispblank=$(xset -q | grep "^  timeout:  " | awk '{ printf $2/60 }')

# Resume time in hours
resumetimehr=$(echo "scale=1;${resumetime}/60" | bc)

# Display help
case $1 in
  -h | --help | h | help )
    # Help message.
    echo
    echo "  $prog disables screen blanking and screensaver to allow viewing a video.  Running the program again will enable them.  If the 'resumetime' variable is set after that time $prog will resume normal powersaving values." | fmt -c -w 76
    echo

    # Display current values of power management and movietime.
    suspinhtest=$(ps aux | grep -v grep | grep $suspinhscript)
    suspinhval=$([ -n "$suspinhtest" ] && echo "Disabled" || echo "Desktop settings")
    
    # DPMS disabled information
    echo "   ${txtbld}Current settings ${txtrst}(in minutes, 0 = disabled):"
    if [[ "$dispdpms" == "Disabled" ]]; then
      echo "   DPMS:         $dispdpms"
      echo "   Suspend:      $suspinhval"
    fi

    # DPMS enabled information
    if [[ "$dispdpms" == "Enabled" ]]; then
      echo "   DPMS:         $dispdpms"
      echo "   DPMS times:   Blank: ${dispblank}; Standby: ${dispstand}; Suspend: ${dispsusp}; Offtime: ${dispoff}"
      echo "   Suspend:      $suspinhval"
    fi
    echo
    echo "   ${txtbld}$prog settings${txtrst}:"
    echo "   Resume after: $resumetimehr hours"
    echo
    exit
    ;;
  [a-g,i-z,A-G,I-Z,0-9,-]* )
    echo " Use '-h' for help"
    exit
    ;;
esac

# Suspend inhibit script (must be run as seperate process)
suspinhibit () {
    echo '#!/bin/bash
    for time in $(seq 1 '$resumetime'); do
    # Simulate user activity every minute
    dbus-send --print-reply --type=method_call --dest=org.freedesktop.ScreenSaver /ScreenSaver org.freedesktop.ScreenSaver.SimulateUserActivity
    sleep 60
    done'
}

# Toggle powersaving
if [[ "$dispdpms" == "Enabled" ]] && [ -z "$suspinhtest" ]; then
  # Disable blanking, screen power saving
  xset s off; xset -dpms
  # Create script in tmp
  suspinhibit > "$suspinhscript"
  # Make script executable
  chmod u+x "$suspinhscript"
  # Run script
  nohup "$suspinhscript" &> /dev/null &
  echo "$pass $prog started, powersaving disabled."
else
  # Enable blanking, screen power saving
  xset s on; xset +dpms
  # Kill script
  if [ -n $suspinhtest ]; then
    echo "$info $prog stopped, powersaving enabled."
    kill -s 9 $(pgrep movietime-susp) &> /dev/null
  fi
fi

Turn off all cellphones and enjoy the show!

Apple Trailers Fix

HeaderAs some of you may have found out or read about, Apple trailer downloads for Linux are currently broken. Apple has implemented a Quicktime user agent check prior to downloading. Personally I agree with the decision because Apple is concerned about the quality of reproduction (though Apple trailers still play with an odd hue on Windows – think this has to do with Quicktime not correctly reading Window’s color setting – but I’m getting off topic). This means that movie players plugins for web browsers (like gecko-mediaplayer and totem) will no longer work. Until gstreamer gets a patch that fix’s this, here’s a script that can download them manually. To use the script, right-click on the download link and copy it to the clipboard then append it after the atget script.

You can comment wget line and uncomment the mplayer line to directly play the trailer. The mplayer line needs to have a cache to be sure the video is downloaded before it start or errors will occur (200MB should be enough for just about and video on the site).

Credits

  • Thanks to Ian on stack overflow, who help me figure out how to prepend a regex search.

Installing Perl Modules Manually

HeaderIf you do Perl programming or if a program you have needs a perl module, you could download and compile it manually but the easier way would be to use CPAN (the Comprehensive Perl Archive Network).

CPAN

First thing you should do is see if your distribution has it in it’s packages repository so that it can be easily added/removed. If it isn’t, be sure you have perl installed and start the cpan shell:

perl -MCPAN -e shell

Then upgrade the local CPAN module database:

install Bundle::CPAN
reload cpan

Then to install (for example HTML::Template):

install HTML::Template
exit

Once the database is downloaded you don’t need to use the shell anymore to add a module:

perl -MCPAN -e 'install HTML::Template'

A Better Link

Update: This script has been updated, look at it, here.

Week of bash scripts – rps and commentstrip

These two scripts will respectively: find if a program is running, and strip-comments from text files. The first is useful if you need to see if the program is running or if you need to kill the process with it’s id, comment strip is a good tool to use if posting configurations on forums as often developers or advanced users already know what the settings actually do.

rps

aspire ~/.scripts:
rps geany
todd      1827  0.1  0.3 184576 28616 ?        S    May31   1:05 geany

commentstrip

Commentstrip will display the output to the terminal. If you got xclip installed the ‘c’ option can be used to copy the output to the clipboard.

The final day of week of bash scripts… phew! I’d like to thank everyone that posted comments, and to those that stopped by this week.

Week of bash scripts – grok and cdf

These two scripts are two different find commands. The first (grok) will list all files in a directory recursively that contain a matched string; the second will locate a file/folder and the change to it’s directory. Neither of these are mine (though slightly edited), I’ve gotten them from the Arch forums where they have a great thread called Post your handy self made command line utilities.

Grok

This one is by rebugger and I call it grok. Syntax is:

grok <string> <*location>

If no location is given it uses the current directory.

aspire ~:
grok 127.0.0.1 /etc/
 Searching...
/etc/dnsmasq.conf
/etc/dnsmasq.conf.pacorig
/etc/hosts
/etc/NetworkManager/dispatcher.d/localhost-prepend
/etc/ntp.conf
/etc/resolv.conf
/etc/security/access.conf
/etc/xinetd.d/servers
/etc/xinetd.d/services

cdl

This one is by segoe that uses locate to find a file and that cd’s to the first match found.

aspire ~/.scripts:
cdl demo/PKG
aspire ~/.arch/pkgbuilds/amnesia-demo:

This one put in your ~/.bashrc:

cdf () { cd "$(dirname "$(locate -i "$*" | head -n 1)")" ; } # locate then cd

Week of bash scripts – Unpack

As the antithesis of yesterdays pack command there is unpack.

Unpack

This script was originally written by brisbin33 in the Arch forums (beautiful work man) and is slightly-modified. It will unpack most compressed file formats. Syntax is:

unpack <archive.ext>

A week of bash scripts – Pack

Hello blogweb, this week I’ll be posting some of my bash scripts that I use on a regular basis. To begin:

Pack

I tend to do quite a bit of compressing files for uploading and I cannot always seem to remember the options and order of those options that tar needs. So I built a bash script that does it for me. I call it pack and it’s syntax is:

pack <file1> <folder1> ...

Backup Configurations with tar Helpers

Update: This article has been supplanted by The Beauty of rsync and Backup Script.

When I have to do a reinstall, sometimes I have to install from scratch – doing a clean install is just sometimes necessary. My configurations are priceless to me and after my reinstall I restore them from a backup copy. Here’s how I quickly add my configurations to an include file and back them up on a regular basis done with a basic script.

Basic tar Command

A good number of GUI programs can do this (you can read about the ones I’ve looked at here), but they seem to make the process more complicated, so I went back to tar and created a script. And it makes adding and subtracing files easy. For those new to tar the basic archive command is:

tar -c --xz -f <backupname>.tar.xz /folder/file /folder ...

Include/Exclude Files

By putting the archive command in a bash script it can be used later. Files and folders can be appended to the command in the script but for multiple files consider using include and exclude files:

#!/bin/bash

tar --files-from=include.txt --exclude-from=exclude.txt -c --xz -f backupname.tar.xz

Include/exclude files contain the path on a line of what or what-not to backup. The include file should list the full path and cannot use regexps but the exclude fine can:

/home/*/.local/share/Trash/files
/home/*/.Trash

Add Paths to Include/Exclude Quickly

To add paths to the include/exclude files readlink can be used. Adding to the include and exclude files can be done like this (using the script below):

$ bckcfg i /etc/rc.conf 
 Added "/etc/rc.conf" to bckcfg include file.
$ bckcfg e ~/.thumbnails/
 * "bckcfg" doesn't check if patch is correct because the exclude file can
 contain regexps.  Be sure the path is correct (e.g. '/mnt/win/*')
 Add "/home/todd/.thumbnails/" to bckcfg exclude file? (y/n): y
 Added "/home/todd/.thumbnails/" to bckcfg exclude file.

Creating notes of backups can be done by:

$ bckcfg n Added font config
$:cat bckcfg-not.txt | tail -n 2
20xx-08-14-02:52:23 PM: Added dhcp cacher config
20xx-08-14-02:52:33 PM: Added font config

The Backup Script

To backup do:

bckcfg c

The script names the backup by several definable variables and removes old backups if desired.

Consider putting it in a cron job to get regular backups.

o/

Restore Settings on a Broken Firefox

Update: 09-29-11 – Using script to automate process, see end of post.

When people have a issue with Firefox I’ve seen many people will resort to deleting their old profile (or folder) and creating a new one. This works but doing this will get rid of any passwords, history, bookmarks… therein. Having used Firefox quite a bit creating a new profile from time to time is a good idea anyhow as cruft, bad extensions, … can slow down browsing.

Manually

Copying the Firefox configs can be done by:

cd ~/.mozilla/firefox/

Backup the old profile and profile list:

mv xxxxxxxx.default{,.bck}
mv profiles.ini{,.bck}

Create a new profile:

firefox -CreateProfile <profilename>

This command will return the name of the new folder. Copy the basic settings to the new profile:

cd *.default.bck
cp places.sqlite key3.db cookies.sqlite mimeTypes.rdf formhistory.sqlite signons.sqlite permissions.sqlite webappsstore.sqlite persdict.dat content-prefs.sqlite ../*.<profilename>

This will transfer the bookmarks, browsing history, form entries, passwords, personal dictonary changes, and page zooms. There might be a couple other things wanted to add (possibly your firefox preferences), take a look at Transferring data to a new profile for more information.

Follow

Get every new post delivered to your Inbox.

Join 58 other followers