Wednesday, March 31, 2010

File to Hash Technique: Multiple values

If you have a file like below
#File test.txt
usa, phili
usa, cali
france, paris
france, marcille
india, delhi
usa, atlanta

Script to do that is below.

#!/usr/bin/perl
use strict;
use warnings;
use Data::Dumper;

my %table = ();

open(FILE, "test.txt") or die("Unable to open manifest due to $!");
while ()
{
chomp;
my ($key, $val) = split /, /;
$table{$key} .= exists $table{$key} ? ",$val" : "$val";
}
close(FILE);
print Dumper(\%table);


Here is the output.

$VAR1 = {
'usa' => ',phili,cali,atlanta',
'france' => ',paris,marcille',
'india' => ',delhi'
};

Perl Reference

Say you have a file like this.

Chicago, USA
Frankfurt, Germany
Berlin, Germany
Washington, USA
Helsinki, Finland
New York, USA

We need an output like below.

Finland: Helsinki.
Germany: Berlin, Frankfurt.
USA: Chicago, New York, Washington.

To do this it would be good to use perl references as below

my %table;
while (<>) {
chomp;
my ($city, $country) = split /, /;
$table{$country} = [] unless exists $table{$country};
push @{$table{$country}}, $city;
}
foreach $country (sort keys %table) {
print "$country: ";
my @cities = @{$table{$country}};
print join ', ', sort @cities;
print ".\n";
}

More explanation on references is here http://perldoc.perl.org/perlreftut.html

Monday, March 29, 2010

WMI Script to Terminate a Process on a Distant Machine

Option Explicit
Dim objWMIService, objProcess, colProcess
Dim strComputer, strProcessKill, strInput
strProcessKill = "'calc.exe'"

' Input Box to get name of machine to run the process
Do
strComputer = (InputBox(" ComputerName to Run Script",_
"Computer Name"))
If strComputer <> "" Then
strInput = True
End if
Loop until strInput = True


Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!\\" _
& strComputer & "\root\cimv2")

Set colProcess = objWMIService.ExecQuery _
("Select * from Win32_Process Where Name = " & strProcessKill )
For Each objProcess in colProcess
objProcess.Terminate()
Next
WSCript.Echo "Just killed process " & strProcessKill _
& " on " & strComputer
WScript.Quit

Start Process on a Remote Machine

Option Explicit
Dim objWMIService, objProcess
Dim strShell, objProgram, strComputer, strExe, strInput
strExe = "Calc.exe"
' Input Box to get name of machine to run the process
Do
strComputer = (InputBox(" ComputerName to Run Script",_
"Computer Name"))
If strComputer <> "" Then
strInput = True
End if
Loop until strInput = True

' Connect to WMI
set objWMIService = getobject("winmgmts://"_
& strComputer & "/root/cimv2")
' Obtain the Win32_Process class of object.
Set objProcess = objWMIService.Get("Win32_Process")
Set objProgram = objProcess.Methods_( _
"Create").InParameters.SpawnInstance_
objProgram.CommandLine = strExe

'Execute the program now at the command line.
Set strShell = objWMIService.ExecMethod( _
"Win32_Process", "Create", objProgram)

WScript.echo "Created: " & strExe & " on " & strComputer
WSCript.Quit

Categories of VBScript 800xxxxx error codes

Code 80005xxx - ADSI errors
Code 8007xxxx - Operating System error e.g. Windows 2003 / XP
Code 800Axxxx - Syntax errors
Sundry Errors


Code 80005xxx - ADSI errors
Errors beginning with 80005xxx point to an ADSI error in your VBScript. While the message box calls them ADSI, I think of them as LDAP errors. For example, suppose that you are scripting a user's properties and you type givename instead of givenName (two ns), that mistake in the ADSI / LDAP name would generate an 80005xxx error.

Code 80005000 Object Required
Code 80005001 An unknown ADSI domain object was requested
Code 80005002 An unknown ADSI user object was requested
Code 80005003 An unknown ADSI computer object was requested
Code 8000500D The directory property cannot be found


Sundry Errors - Including WMI and MSN
Code 8002009 Error Setting Default Printer
Code 80020005 Type mismatch
Code 8002801c DllRegisterServer in COM failed
Code 800401E4 Syntax error
Code 80040E14 One or more errors occurred during processing of command
Code 80040E37 Table does not exist
Code 80041001 Call Failed
Code 80041002 Object not Found
Code 80041006 Insufficient Memory
Code 80041010 Spelling mistake in a keyword
Code 80041013 Provider not Found
Code 80041014 Component Error
Code 80041021 Syntax error in WMI winmgmts \\
Code 80048820 MSN Messenger server problem
Code 80048821 MSN Messenger email username problem
Code 80048823 MSN Messenger password
Code 8004888D MSN Service is temporarily unavailable
Code 81000306 MSN Messenger server down?
Code 81000314 MSN Messenger server down?


Code 8007xxxx - Operating System error e.g. Windows 2003 / XP
If your error begins with 8007xxxx then look for an factor outside VBScript. For instance, check the spelling of the name of your share or printer. Another possibility is that the server named in the script, is simply down or otherwise unavailable.

Code 80070005 Access denied
Code 80070035 The network PATH cannot be found
Code 80070043 The network NAME cannot be found
Code 80070055 The local device name is already in use
Code 8007007B The filename, directory or volume is incorrect
Code 800704B0 The specified device name is invalid
Code 800704B2 An attempt was made to remember a device .......
Code 800704B3 No network provider accepted the given network path
Code 800704CA This network connection does not exist
Code 800704C3 Multiple Connections to a server or shared resource...
Code 800704CF The network location cannot be reached
Code 8007052E Logon Failure: unknown user name or bad password
Code 80070571 The media is corrupt
Code 800706B5 The Interface is Unknown
Code 800706BA The RPC server is unavailable
Code 80070709 The Printer name is invalid
Code 80070961 This network connection has files open or requests pending
Code 80071329 Object Already Exists
Code 8007200E The Directory Service is Busy
Code 80072020 An operations error occurred
Code 8007202B A referral was returned from the server
Code 80072030 There is no such object on the server
Code 80072032 LDAP syntax error. Possibly a missing element e.g. cn=
Code 80072035 The server is unwilling to process the request
Code 8007203A The server is not operational
Code 80072EE2 Windows Update Service Problem


Code 8009xxxx
Code 80092023 Illegal character in a key name for a certificate

Code 800Axxxx Syntax errors
In VBScript, there are 53 syntax errors all beginning with 800Axxxx. These errors should be among the easiest to cure because the message often includes the missing punctuation mark or bracket.

Code 800A0005 Invalid Procedure Call
Code 800A000D Type Mismatch
Code 800A0035 File not found
Code 800A003A File Already Exists
Code 800A0046 Permission denied
Code 800A004C Path not found
Code 800A01A8 Object required
Code 800A01AD ActiveX component can't create object
Code 800A01B6 Object doesn't support this property or method
Code 800A01BD Object doesn't support this ACTION
Code 800A01C3 Object not a collection
Code 800A01C2 Invalid property assignment
Code 800A01CE Remote Server does not exist (or is unavailable)
Code 800A01F4 Variable undefined
Code 800A01F5 Illegal assignment
Code 800A03EA Syntax Error
Code 800A03EE Expected ')'
Code 800A03F1 Variable is undefined
Code 800A03F2 Expected Identifier
Code 800A03F4 Variable Undefined
Code 800A03F6 Expected End
Code 800A03FD Expected 'Case'
Code 800A0400 Expected statement
Code 800A0401 Expected end of statement
Code 800A0407 Invalid Number
Code 800A0408 Invalid Character
Code 800A0409 Unterminated string constant
Code 800A041F Unexpected Next
Code 800A139B - Expected ']' in regular expression
Code 800A139A - Expected quantifier in regular expression
Code 800A0CC1 Item cannot be found in the collection

Who is Logged in now in windows

Here is a WMI script to find out who is logged into the system at the moment.

#whoIsLogged.vbs

Dim objWMIService, objComputer, colComputer
Dim strLogonUser, strLogonUser1, strComputer

strComputer = "."
strComputer = InputBox("Enter Computer name", _
"Find Logon User", strComputer)
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!\\" _
& strComputer & "\root\cimv2")
Set colComputer = objWMIService.ExecQuery _
("Select * from Win32_ComputerSystem")

For Each objComputer in colComputer
If not objComputer.UserName = "" Then
strLogonUser = Split(objComputer.UserName,"\")
strLogonUser(1) = UCase(Left(strLogonUser(1),1))_
& Trim(Mid(strLogonUser(1),2,20))
Wscript.Echo strLogonUser(1) & " is logged on at " _
& strComputer
Else
Wscript.Echo "No one is currently logged on at " _
& strComputer
End If
Next

Automating FTP in windows

Here is a way to automate file upload using FTP in windows. Make a bat file called fileup.bat

@echo off
echo user MyUserName> ftpcmd.dat
echo MyPassword>> ftpcmd.dat
echo bin>> ftpcmd.dat
echo put %1>> ftpcmd.dat
echo quit>> ftpcmd.dat
ftp -n -s:ftpcmd.dat SERVERNAME.COM
del ftpcmd.dat

You can now run this using below command

fileup FileToUpload.zip

Saturday, March 20, 2010

Bash commands from Java: Good way

A string can be executed in the standard java way:
def command = """ping -c1 -W1 hostname""" // Create the String
def proc = command.execute() // Call *execute* on the string
proc.waitFor() // Wait for the command to finish

// Obtain status and output
println "return code: ${ proc.exitValue()}"
println "stderr: ${proc.err.text}"
println "stdout: ${proc.in.text}" // *out* from the external program is *in* for groovy

Thursday, March 04, 2010

Cython

Use this in case you want to create dll i n windows or .so files in UNIX. Its based on Python.

http://cython.org/