Archive

Archive for the ‘Scripts’ Category

Arch / Yum

December 3rd, 2011 No comments

I recently switched to Archlinux and I have to say I love it a great deal. I really like the simplicity of it, unfortunately due to my long standing usage or yum I have been spoilt. It means that I find myself wishing to have commands like yum install package, so switching pacman’s -S was a little too much. I therefore wrote a wrapper to make it easier for me. Maybe it can help others just starting out in the path to using Archlinux.

In preparation for this, you will need to install yaourt and enable it with sudo access. Either that or replace all the references to yaourt below with pacman.

Drop this into your ~/.bashrc (or zshrc):

function arch() {
        if [ -z "$1" ]; then
                echo "arch  " >&2
                return -1
        fi

        case $1 in
                upgrade)
                        # Synchronize, upgrade
                        shift
                        sudo yaourt -Syu $@
                        ;;
                install)
                        # Install stuff
                        shift
                        sudo yaourt -S $@
                        ;;
                localinstall)
                        # Install file
                        shift
                        sudo yaourt -U $@
                        ;;
                remove)
                        # Remove
                        shift
                        sudo yaourt -R $@
                        ;;
                fullremove)
                        # Remove file
                        shift
                        sudo yaourt -Rns $@
                        ;;
                info)
                        # Display information
                        shift
                        yaourt -Si $@
                        ;;
                search)
                        # Search
                        shift
                        yaourt -Ss $@
                        ;;
        esac
}

Now you can do things like:

$ arch install git
$ arch remove git
$ arch info git
$ arch search git

Hope its handy!

Tags: ,

Renaming Files In A Directory

September 2nd, 2009 1 comment

So I had a problem on Windows in that I have lots of directories that are named correctly but I wish the files under them to be uniformly named.

The solution was to use PowerShell, which is an extremely effective scripting tool for Windows, especially if you come from a UNIX shell background.

There is actually quite a lot of documentation available for it and rather than go into detail I will simply show you the script:

#
# RenameDirectoryFiles.ps1
#
 
param( [string[]]$paths )
Set-PSDebug -Strict
 
foreach ( $path in $paths ) {
    if ( !(Test-Path $path -PathType Container) ) {
        Write-Error "'$path' doesn't exist or isn't a directory"
        exit 1
    }
 
    $i = 0
    Get-ChildItem $path | sort FullName | foreach {
        $tmp = "{0:000}" -f $i
        $ext = $_.Extension
        $newname = "$path - $tmp$ext"
        Rename-Item $_.fullname $newname
        $newname
        $i = $i + 1
    }
}

So the usage is extremely simple:

RenameDirectoryFiles.ps1 'My Directory'

After which all the files under ‘My Directory’ will be renamed to ‘My Directory – 000.fileextension’.

Tags: ,

Skinning A Cat

May 17th, 2009 No comments

I was recently discussing with someone about sed usage. They were having difficultly creating an appropriate regex to handle their problem:

(Orlando) sed regex kicks my ass.  I like to remove the second : in the
line. So that in 123:456:6789 it will only returns 123:456.  I can find the
first :, but I have not been able to use s/:{2}// to find the second
one, and remove the rest.

I enjoy regex (I know I’m weird, leave me alone), so I was able to provide an answer to this problem:

(@znx) Orlando: the trick is to use [^:] and \1 ..
(@znx) like:   s/\(:[^:]*\):.*/\1/

Now obviously at first glance this regex could be a bit intimating to someone who is still picking up the skills but as with most things if we break it down it becomes easier.

Working out to in, \( \):.*, that says match something with : at the end and all the character after it. The . is a special meaning “any character” and * to match multiple characters. The first match will be stored by sed and assigned into the \1 for the replacement (that is what the brackets do). Inside the brackets we have :[^:]*. The sequence [^ ] is a negated list, that means that we are asking it to match everything that is NOT inside the list, in this case :.

Putting it altogether we are saying: Match a leading : and a trailing : with any characters after it. Placing the contents between the two : in memory. Then finally we replace the contents.

% echo 123:456:6789 | sed 's/\(:[^:]*\):.*/\1/'
123:456

Sucess, however as with most things, there is more than one way to skin a cat and regex is rarely the prettiest method. So what other ways can we solve this problem?

With AWK:

% echo 123:456:6789 | awk -F: '{print $1":"$2}'
123:456

With cut:

% echo 123:456:6789 | cut -d: -f1,2
123:456

As always, experimentation with the mass of GNU tools you can find on your system will bring a greater deal of power to your tool chest. Mind you, then I wouldn’t get complements for helping would I?

(Orlando) Wow, When I grow up, I like to remember this thing like you do. :-) 

Haha, till next time!

Tags: ,

BigBrother Scripting

March 17th, 2009 No comments

I was recently asked if it was possible to monitor the Event Log for a single event and ensure that it was occurring regularly. It is rare that I handle Windows scripting and when I do I normally find myself cursing it, haha! In this case we want to ensure that a print server is constantly printing through the day, we expect that at least 1 print job will occur every 15 minutes, if not then we’d like a warning. Obviously this check should only run during work hours.

So the first step is relatively simple, access the Event Log and look for a single event by its event code.

set objWMIService = GetObject("winmgmts:\root\cimv2")
set colEvents = objWMIService.ExecQuery _
   ("Select * from Win32_NTLogEvent Where Logfile = 'System' and EventCode = 10")

What we did here was grab all the events with event code of 10 (a print job!). So if we count the number of events within a range then we will have basically completed a huge part of the work.

So next step is to make an interval that will be 15 minutes back from whatever time is current.

set dtmStartDate = CreateObject("WbemScripting.SWbemDateTime")
dtmStartDate.SetVarDate DateAdd("n",-15,Now()),True

And applying that into our statement:

set colEvents = objWMIService.ExecQuery _
   ("Select * from Win32_NTLogEvent Where Logfile = 'System' and EventCode = 10" _
   & " and TimeWritten >= '" & dtmStartDate & "'")

This means that we are now collecting the events that only occurred within the last fifteen minutes. So what next, well we need to have a statement to pass to BigBrother to indicate success or failure. Fortunately enough I have another script which monitors the cluster (thanks to the awesome DeadCat repository) and it has some code to help place the file that BigBrother collects.

const HKLM = &H80000002
strBBExtPathNew = "SOFTWARE\Quest Software\BigBrother\bbnt\ExternalPath"
strBBExtPathOld = "SOFTWARE\BigBrother\bbnt\ExternalPath"
set oReg = GetObject("winmgmts:\root\default:StdRegProv")
 
oReg.GetStringValue HKLM,strBBExtPathNew,,strExtPath
if isNull(strExtPath) then
  oReg.GetStringValue HKLM,strBBExtPathOld,,strExtPath
end if
if isNull(strExtPath) then
  WScript.Quit
end if

Read more…

Tags: ,

File Oddity

February 13th, 2009 No comments

Today at work I was attempting to parse a file and discovered something odd happening. When I simply viewed the file with cat, I could see this:

<html><head><title>Status</title></head>
<table>
<tr><td>Failed</td><td>Backup Group</td></tr>
<tr><td>Success</td><td>Another Backup Group</td></tr>
</table>
</body>
</html>

Nothing odd there, the file is normal but when I tried this command:

$ grep -i failed status.html
$

Huh? No output, suggesting that there is no lines with the words failed on them. The same occurs with awk and sed, indeed I could not find any tool to be able to grep out the status. So the next step was to check what was odd about the file:

$ file status.html
status.html: HTML document text

Still, nothing unusual. So now I am in full head scratching mode, I open up the file with vim to see if I can discover anything strange about the file but nothing. At this point I happened to switch to more rather than cat and the result was the start of how I solved it.

$ more status.html
��<

$

Ah, so now I can see why grep and the others cannot view anything in the file. So this time I switch to vim again and check what file encoding we have:

:set fileencoding
fileencoding=ucs-2le

For those that are unaware, this is UCS-2 (little endian), also know as UTF-16. So the issue was simply that we had UTF-16 characters, now for the trick to get around it:

$ iconv -f UTF-16 -t UTF-8 status.html | grep -i failed
<tr><td>Failed</td><td>Backup Group</td></tr>
$

Tada. Once more a solution!

Tags: ,

Switch to our mobile site