Category Archives: code

All things with code in them

bash: reverse the contents of a file

This was a unique interview question I had a while back, I was asked to write a script that would write the contents of a file to another file in reverse order. Now it seems trivial so I thought I would post a basic example:

#!/bin/bash

linecount=`cat file1 | wc -l`

for (( i=1; i<=$linecount; i++ ))
do
  /usr/bin/tail -$i file1 | /usr/bin/head -1 >> file2
done

It’s really that simple! First you grab the line count of your source file (Line 3) and based on the number of lines in the file, we loop and iterate backwards using tail + head (Line 7).

srvany.exe service wrapper

I put this together for a project recently, if you’ve ever used the instsrv.exe and srvany.exe utilities from the Windows 2003 resource kit you know they have their limitations. For instance if the executable you’re daemonizing with srvany.exe crashes or is killed, the service still shows as running. Not really helpful when you’re talking about, let’s say, cluster fail-over, or monitoring for that matter. Here’s a script I put together that captures process IDs for a sub-process that the script calls, the process for the script itself, and the parent process of the script. If the sub-process called by the script dies, it will destroy it’s parent process and terminate itself.

''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
'' srvany.exe wrapper from the Windows 2003 resource kit Please use at you own risk - this      ''
'' script is without warranty. This script checks every 5 seconds if the process it spawned is  ''
'' still alive. If the spawned process is not alive it will kill the parent process and         ''
'' terminate itself.                                                                            ''
'' Set: HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\YourService\Parameters\Application ''
'' To: cscript.exe /nologo "C:\path\to\this\script.vbs"                                         ''
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''

Const SW_NORMAL = 1
dim strCommand, strComputer
strComputer = "."
strCommand = "C:\path\to\your\executable.exe" ' This can be anything, try "c:\windows\notepad.exe" and run the script interactively

' Create WMI object
Set objWMIService = GetObject("winmgmts:" & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")

' Create configuration object required by Win32_Process to create a new process
Set objStartup = objWMIService.Get("Win32_ProcessStartup")
Set objConfig = objStartup.SpawnInstance_
objConfig.ShowWindow = SW_NORMAL

' Create process object
Set objNewProcess = objWMIService.Get("Win32_Process")

' Create process based on strCommand
intReturn = objNewProcess.Create(strCommand, Null, objConfig, intProcessID)

Do Until pCheck <> 0

'Object for checking script process ID and parent process ID
Set objSWbemServices = GetObject ("WinMgmts:Root\Cimv2")
Set colProcess = objSWbemServices.ExecQuery ("Select * From Win32_Process")

'Object for checking if our application is alive
Set objSWbemServicesSub = GetObject("WinMgmts:Root\Cimv2")
Set OurProcess = objSWbemServicesSub.ExecQuery("Select * From Win32_Process where ProcessID = " & intProcessID)
   
    If OurProcess.Count = 0 Then
    ' Process no longer exists - crashed or terminated - now terminate script and parent processes
    For Each objProcess In colProcess
        If InStr (objProcess.CommandLine, WScript.ScriptName) <> 0 Then
           
            ' Object needed to grab parent process ID from objProcess (this script)
            Set objSWbemServicesParent = GetObject("WinMgmts:Root\Cimv2")
            Set ParentProcess = objSWbemServicesParent.ExecQuery("Select * from Win32_Process where ProcessID = " & objProcess.ParentProcessId)
           
            ' Terminate parent process
            For Each srvProcess In ParentProcess
                srvProcess.Terminate()
               
                ' Terminate script handler (Loop check)
                pCheck = 1
            Next
           
           
        Else
           
        End If
    Next

    End If

Wscript.Sleep 5000

Loop

Perl script random password generator…

It’s somewhat random :) ¬†Great for generating secure passwords…

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
#!/usr/bin/perl
my $currentPassword;
$currentPassword=randomPassword(8);
print $currentPassword;&nbsp;

sub randomPassword {
my $password;
my $_charrand;
my $_numrand;
my $_uprand;
my $_specrand;
my $c_num=0;
my $c_up=0;
my $c_spec=0;
my $password_length = $_[0];

if (!$password_length) { $password_length = 8; }
my @chars = split(" ","a b c d e f g h i j k l m n o p q r s t u v w x y z");
my @nums = split(" ","0 1 2 3 4 5 6 7 8 9");
my @upchars = split(" ","A B C D E F G H I J K L M N O P Q R S T U V W X Y Z");
my @specchars = split(" ","\* \$ \! \# \% \@ \_ \-");

srand;

for (my $i=1; $i &lt;= $password_length ;$i++) {
$_charrand = int(rand 26);
$_numrand = int(rand 10);
$_uprand = int(rand 26);
$_specrand = int(rand 8);</h6>
<h6>if ($_uprand &gt; 17 &amp;&amp; $c_up == 0) {
$password .= $upchars[$_uprand];
$c_up +=1;
next if($c_up == 1);
}
if ($_numrand &gt; 6 &amp;&amp; $c_num == 0) {
$password .= $nums[$_numrand];
$c_num +=1;
next if($c_num == 1);
}
if ($_specrand &gt; 4 &amp;&amp; $c_spec == 0) {
$password .= $specchars[$_specrand];
$c_spec +=1;
next if($c_spec == 1);
}&nbsp;

$password .= $chars[$_charrand];
}
$_charrand = int(rand 26);
$_numrand = int(rand 10);
$_uprand = int(rand 26);
$_specrand = int(rand 8);
if ($c_up == 0) {   $password =~ s/[a-z]//; $password .= $upchars[$_uprand];    }
if ($c_num == 0) {  $password =~ s/[a-z]//; $password .= $nums[$_numrand];  }
if ($c_spec == 0) { $password =~ s/[a-z]//; $password .= $specchars[$_specrand];    }

return $password;

}

Thanks Paul Bradley for the basic concepts.