Blog.Arcath.Net

Printer Script that uses a computers Active Directory OU

by Arcath on Jun.30, 2009, under Programming

Well this is a special post:

  • Its the first post involving something i did for work
  • Its the first post where the code is written in VBS
  • Its the first Windows based post

This is a printer script i wrote to replace a script some else had written for one of the schools i work in, his script was a big, HOOOOGE case statement that ran of host name, e.g.

pc1 -> printer 1
pc2 -> printer 1 & 2
pc3 -> printer 1 & 2

This to the end user works exactly the same as the new script, but from my point of view the new script is allot better.

When the user logs in the script looks at the host name and then asks Active Directory where that computer is in its orginsational Structure. This means that if i move a PC in active directory the printers it gets change. You can tell how much better that is already, instead of having to rewite its case the new script just changes it for me.

So then its time to post the script:

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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
'Printer Script based on AD Group
'Written by Adam Laycock (Arcath)
'July 2009

'Variables

Set WshNetwork = WScript.CreateObject("WScript.Network")
 
Set oPrinters = WshNetwork.EnumPrinterConnections
 
printServer = "SERVERNAME" 'Set this to the machine that is your Print Server

DefaultColourPrinter = "\PRINTERNAME" 'The Main Colour Printer

DefaultBWPrinter = "\PRINTERNAME" 'The Main Black and White Printer

 
'Functions

'Get First Match
'Returns the First REGEX Match for the pattern you supply
'from http://www.somacon.com/p138.php
Function GetFirstMatch(PatternToMatch, StringToSearch)
	Dim regEx, CurrentMatch, CurrentMatches
 
	Set regEx = New RegExp
	regEx.Pattern = PatternToMatch
	regEx.IgnoreCase = True
	regEx.Global = True
	regEx.MultiLine = True
	Set CurrentMatches = regEx.Execute(StringToSearch)
 
	GetFirstMatch = ""
	If CurrentMatches.Count >= 1 Then
		Set CurrentMatch = CurrentMatches(0)
		If CurrentMatch.SubMatches.Count >= 1 Then
			GetFirstMatch = CurrentMatch.SubMatches(0)
		End If
	End If
	Set regEx = Nothing
End Function
 
 
'Remove all the Network Printers from the Machine
For i = 0 to oPrinters.Count - 1 Step 2
 
            On Error Resume Next
 
	    if Left(oPrinters.Item(i), 3) <> "lpt" And Left(oPrinters.Item(i), 3) <> "usb" then
 
             	WshNetwork.RemovePrinterConnection oPrinters.Item(i+1), true, true
 
            else WScript.Echo "No network printers found"
 
            end if
 
Next
 
'Connect to AD
Set objSysInfo = CreateObject("ADSystemInfo")
 
 
'Get LDAP entry to current computer object.
strComputerDN = objSysInfo.ComputerName
Set objComputer = GetObject("LDAP://" & strComputerDN)
 
strOU = GetFirstMatch("OU=(.*?),OU=", strComputerDN)
 
 
Select Case (LCase(strOU))
	'For Each OU make a Case
	'note that the OU Name is made to be all lower case
	case "room1"
		WshNetwork.AddWindowsPrinterConnection "\\" & printServer & DefaultColourPrinter
 		WshNetwork.SetDefaultPrinter "\\" & printServer & DefaultColourPrinter
	case "room2"
		WshNetwork.AddWindowsPrinterConnection "\\" & printServer & DefaultBWPrinter
		WshNetwork.AddWindowsPrinterConnection "\\" & printServer & DefaultColourPrinter
 		WshNetwork.SetDefaultPrinter "\\" & printServer & DefaultBWPrinter
End Select

and now an explination

First off it declares all its variables and creates some objects, can you tell i wrote this to be used in more than 1 place?

It then declares 1 function. This comes from http://www.somacon.com/p138.php and is basically a find the first hit to a regex string funtion. I had never done any regex in VBS and thier function does exactly what i need.

Then comes some actual printer management. It starts by removing all the connections to network printers that the machine has. This way the machine only gets the printers that you want it to (other than any connected by a cable to it).

This is followed by making a connection to active directory to get the AD String for the machine. An example of this is “CN=pc1,OU=Room1,OU=Site,DC=Arcath,DC=NET” This is then passed into the function i mentioned earlier and the first OU is returned, in this case “Room1″.

It then has a case statement where you place a case for each OU, in each case simply place the code for a simple printer script.

Leave a Comment :, , , more...

HsDB Class for Ruby

by Arcath on Jun.15, 2009, under Programming

In a previous post i mentioned that i was going to write a database interface that the new bot would use, and here it is:

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
require 'mysql'
 
class HsDB
	def initialize(dbhost,dbuser,dbpass,dbname)
		@dbc=Mysql::new(dbhost,dbuser,dbpass,dbname)
	end
	def query(q)
		out=[]
		out[0]=0
		qa=q.split(" ")
		query=""
		qa.each do |a|
			if query != "" then
				query+="AND "
			end
			query+="`record` LIKE '%#{a}%' "
		end
		res=@dbc.query("SELECT * FROM `records` WHERE #{query}")
		res.each do |row|
			out[0]+=1
			out.push(row[1])
		end
		return out
	end
	def add(record)
		@dbc.query("INSERT INTO `records` (`record`) VALUES ('#{record}')")
	end
	def remove(q)
		qa=self.query(q)
		if qa[0] == 1 then
			@dbc.query("DELETE FROM `records` WHERE `record` = '#{qa[1]}'")
			out=0
		else
			out=qa[0]
		end
		return out
	end
end

There are 4 methods to this class.

Initialize

This is the standard creation method in ruby, it is used in the this case to create the database connection “@dbc” using the ruby-mysql class, i will dig up the link and post it in a comment later.

Query

Of the 4 this is by far the most important. It searches the the database for “q”. To make the database searcher come up with more results, and more importantly similar results it searches for records that contain each word that the user searches for. This is even more precise than the database searcher i described before. It works using WORD1 and WORD2 etc… this means that the user can refine the search by adding more words.

The output is an array, the array contains the results aswell as a count of the results (held in array[0]) This means that any program using the class can easily tell how many results there are.

Add

This adds to the database, rather simple, it just inserts “record” into the database

Remove

This removes from the database, it uses the same query syntax as “query”, ive limited it to only deleting records when the query returns 1 result, didnt want some one using the bot to delete all records with an “a” in for example.

Thats about it simply require the class and the ruby mysql

1 Comment : more...

Database Searcher for Constance (Beylix)

by Arcath on Jun.13, 2009, under Programming

Anyone who has poped into our IRC Channel (#whitefall on freenode) will have noticed that theres a new name thats allways there, “Beylix”. This is yet another bot, i know this is yet another bot, but i hope unlike the others ive made it wont just dis appear from use.

The underlying IRC Class is the same one i wrote for “Verbend”, and was used in “Silverhold”. Ive chosen not to re-write it for a few simple reasons:

  1. It works
  2. it covers all the bases (join, leave, whois) aswell as some little extras that where added for some of “Silverholds” advanced functions.
  3. The main focus of this bot was to completely re-write its parsing functions.

So its parsing, I decided that for it to be noticeably better it would have to read human input, instead of using strict syntax, for example the old bot used “!time” as the command to return the time. This new bot reads what the user has typed to see if it contained the question “what is the time?”, and if it detects this it then returns the time.

It still uses command like syntax for maths. “~ 1+1″ will return “> 2″, but this was the only way to really “secure” the maths command. Because the maths is evaled it needs to be secured in some way to stop accidentally harmful code being evaled. I do heavily restrict the code, it is run in a new process thread so it cant effect the root program, and that thread is restricted to ruby safe level 4. I also restrict the words that can go in e.g. “sleep = no”. Its also limited to on 1 second execution time.

But the big thing (the title piece of this article) is the database searching, “Silverhold” was the first bot to use a mysql database to store its data. My problem was that when someone asked it about a topic its ability to find similar topics was serverly limited. I understand now how hard it is to make search algorithms for mysql databases. Id rather not create a keyword table so that it can find them, the main problem with that is that the user(s) have to supply the keywords. I personally would rather have it simply search the article and work out the results. SO ive been thinking about how to make it so that it can work like that.

“Silverhold” stored data by holding the Item in one table and then inf facts for an item in another. This meant that the user searches for an item and then it recounts all the facts it has for that item. I want “Constance” to seach more by fact, no item. So if it had 5 facts of:

  1. The Sky is blue
  2. The Sea looks blue
  3. Blue is a colour
  4. Red is a colour
  5. Colour is made of light

Then i want the query “blue” should return 1,2,3 and the query “colour” 3,4. This could be done by using LIKE and then i need to come up with a big rule for the inputs. so “What is blue” or “Who is blue” but then it does need to ignore all requests for data that obviosuly arent for it e.g. “What is that?”.

This has turned into a really waffely post, so im gonna go write the program to do this and post the results later.

Leave a Comment :, , more...

Fedora 11 for the Wind

by Arcath on Jun.11, 2009, under Linux

Well the time has come to update the wind to Fedora 11. So i opened up the “PreUpgrade” Utility and set it off. 3 hours later the download had finished (Wireless was a mistake) and it was time to reboot, so i rebooted the wind and was greeted by anaconda. It asked for nothing and just started chugging through the packages that needed updating (ALL OF THEM!!!!!) at this point i went and put the kettle on made a brew and went back to work. 20 mins later i came back expecting to see “Your install is done please reboot” but no. anaconda had crashed after 500 packages. There was nothing to do other than reboot the wind. It started off good plymouth loaded (although it was fedora 10s) and it was quite happily loading, and then NO.

So that was the wind shafted. So being in the position of having to install a new OS i got a USB DVD drive and set about installing fedora again on the wind.

Once i got to disk management i realised that this was actually a good idea, Fedora 11 features ext4, which should have some speed gains, now my netbook (wind) has nothing that important, all my programs are on Whitefall and all my documents are on google docs or my PC, so nothing really would be lost if i formatted, (except my many hundreds of network profiles :( ). Also swap space would be properly allocted for my RAM, i installed more RAM after installing fedora 10 so my swap space wasnt in proportion to my RAM.

After a long install (USB isnt good for installing a whole OS) it came to first boot. I wasnt that concernd, from fedora 10 i knew that fedora would actually work on the wind. The first thing i noticed was that plymouth worked out of the box! before i had to specify the VGA mode in grub so that it would make shiny on my screen. i then of course went through the first boot screens, not much has changed from Fedora 10.

Now that the install is done i might aswell start to comment on Fedora 11 itself.

First off i had no driver issues, everything was auto detected and all works fine, Bluetooth YES, Wired network YES, graphics YES, wireless YES!!! This has to be the first time ive installed any linux distro and had the wireless work straight away, although i did replace the winds wireless card with a new intel one so thats probabbly why.

Theres not much differance from 10 in terms of look and feel, some icons are different and the menus are ordered differently, but other than that it looks the same (bring on the echo icon theme!!!!).

after a little tinker i had pidgin setup and my terminal shortcut re made aswell as all the silly GUI stuff removed from terminal.

I will probabbly come up with some more comments after ive used it for a little while but for now ive got it working no probs.

3 Comments :, , , more...

Work Rant

by Arcath on Jun.11, 2009, under General

As some of you may know i work as an IT Technician for multiple primary schools in the local area, the jobs that i do in the schools vary massively, from the bigger schools where im sorting out thier virtual server so that if thier main server dies i have a backup of AD, to the little P2P schools whos biggest concern is normally little problems that once i fix, and show them the problem never occour (or i never get told about) again.

But in some cases my jobs can get quite annoying, for example in schools that i visit once a week the smallest remedial problems that are usually fixed by plugging in the mouse, or turning on the plug etc…. are allways left for me, the staff never seem to look at the problem just notice something wrong and write it on my to do list. The smaller schools that only visit once a month never really pass these problems onto me, because i only come in for 3 hours a month, so they have to be able to fix most little problems themselves.

One job that i loathe is installing ancient software, just one example is “Dazzle Plus” where you need to change a registry value to “Service Pack 4″ so that it will install because apparently Windows NT SP4 is a higher version than Windows XP SP3. This is why i keep a clean image of each type of PC on the schools FOG machine. specifically so that i only have to install stuff once per machine type, it also makes recovering from HDD fails or corruption easier. One school swapped from a P2P network to a Server/Domain network over easter, so i decided i would spend my easter holiday re-imaging the school, and installing all thier software onto the server, that way 95% of thier software is actually only a shortcut on the desktop. But one of the teachers didnt get the “Put all the software in this room” message, so now once a month i have to trundle through a mountin of “Windows 3.1 Compatable” software installing it on the network dreading the software that needs to be locally installed on each machine.

Another pet hate of mine is USB Printers, they really do get annoying. if its a P2P network i dont mind s much, it comes with the territory, but when they have a Server/Domain where the thing they love is that its all automated, and everything runs off one place. But USB printers go against this. I have looked into re-sharing them from a server so a script can add it for me, but that didnt pan out. So that leaves me with 1 option. for each USB Printer i have to manually install it on the machine its attached to, then go through each DOMAIN USER on each machine that wants it adding the printer, unlike a network printer where all i do is add the printer to a script and it gets automatically added on logon to all the machines.

Dont get me wrong working in many schools is brilliant, it gives such a potential to test things, if theres many ways of doing a job i can try each one on a different network and then after a month see which worked best and swap all the networks to that method. It also means that my network design is so refined, theres nothing in there that doesnt need to be there., and when a school asks for new things the chances are that i, or one of the other techies have done it at another school, and have already had all the problems.

This was just a little rant after a few vists where the same annoying little things keep cropping up.

Leave a Comment more...

New TF2 Unlocks System

by Arcath on May.24, 2009, under General

Those of you that play TF2 will have noticed that there is now unlocks for the sniper and spy! As with the past updates i launched TF2 and joined one of my usual servers and started picking people off from the other side of the map as a sniper. 8 achivements later i was looking forward to my first new unlock, then out of nowhere i get given a spy unlock. This prompted me to take a closer look at the update news, and it turns out they have changed the unlocks system.

In short they have made thier own achivements system redundant. The only reason i made an effort to kill people in a very specific way was so that i would get a shiny new gun. But now i can take the much easier option of spectating a listen server on my own PC for a day and i will have more than one of everything.

From what i have read there are 2 reasons for this new system:

  1. people that couldnt get achivements whined because they couldnt use the new guns
  2. people where bieng lazy and going onto achivement servers and just typing in “takeoutthefun” to get all the achivements.

Both points are perfectly valid, some people can be perfectly good at the game, but find it hard get the achivements, and thus dont unlock the content, and it does defeat the object of the achivements system if people just log on to a server that lets the unlock everything at once and get it.

I know that valve will never change the system back, but there are some refinements that valve could make to improve the system:

  • limit the items that are given the the class that the user has played the most scince the last unlock (if i want sniper stuff i will play the sniper till i get it)
  • assign higher priority to items that the user doesnt have yet, instead of letting a user get loads of 1 item when they dont have an item that they want, and are powerless to get.
  • instead of making it rand() time (its probabbly done off a complex algorithm, but to the end user it appears random), give the unlocks after the player has played “x” time as class “a” with “y” achivements
1 Comment :, more...

New Steam Gamer Card

by Arcath on Apr.27, 2009, under Programming

The Latest Version of the Steam Gamer Card is now here!

This new version implements all the caching ideas i had come up with whilst making the other versions. So when the cacher is run (once every 10 mins at the moment) this process occours:

Load all the Steam Profile Links into an array

Download every profile to a temp folder

Go through each profile finding all the picture links and building the users profile array

Download any images that are missing (e.g. new avatars)

Generate the Gamer Card Image and save it

This then means that when someone requests a Gamer Card it loads at the speed of requesting a static image! This is allot faster than previous versions.

It looks the same as the previous version:

My Steam Gamer Card

Along with this new version comes a website http://steam.arcath.net this is because i finally feel that it is ready for Public Release I hope to have the form to get one ready within the next few days

Leave a Comment :, , more...

New Wireless Card for the Wind

by Arcath on Apr.06, 2009, under Linux

My new wireless card for the Wind turned up today. I was surprised how easy it was to open up, after the eee put up a quite a fight. Once i got the screws out the back simply lifted off and revealed all the slots i needed. First off the RAM clipped in nice and easy and the wireless card wasnt hidden behind anything so that was easy to find. I then had to disconnect the 2 attenna clips and unclip the wireless card from the slot, push in the new one and attach the attenna to it.

On first boot i got rather concered, Network manger still wasnt listing wireless networks and there was no “Enable Wireless” box. After looking in the network config i noticed that although the hardware had been detected there was no corresponding interface. Once i had created the interface in the network config and given control to network manager and rebooted i was happy to see that both my home wireless networks had been picked up.

Leave a Comment :, more...

Proxy Script for the Wind

by Arcath on Apr.03, 2009, under Programming

Ive written a script for my wind that sets my proxy for me on login. This script doenst set any proxy options other than the on/off setting, i only use proxy or no proxy so all the other settings remain the same. Its written in ruby (no surprise there).

This is the script:

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
#!/usr/bin/env ruby
#First job get IP
system('ifconfig  > /tmp/tmp_ip.txt')
 
#Now to read the ip
def scan
	tmpf=File.new("/tmp/tmp_ip.txt")
	ignore=0
	begin
		while (line=tmpf.readline)
			line.chomp
			if ignore !=0 then
				ignore-=1
			end
			if line=~/Loopback/ then
				ignore=2
			end
			if line=~/inet addr:/ and ignore==0 then
				ip=line.scan(/inet addr:(.*) Bcast:/)
			end	
		end
	rescue EOFError
		tmpf.close
	end
	return ip
end
 
ip=scan
 
#Bit for wireless
 
if ip =~ /10\.[1-255]\.[1-255]\.[0-255]/ then
	system("gconftool-2 --type=boolean --set /system/http_proxy/use_http_proxy true")
	system("gconftool-2 --type=string --set /system/proxy/mode manual")
else
	system("gconftool-2 --type=boolean --set /system/http_proxy/use_http_proxy false")
	system("gconftool-2 --type=string --set /system/proxy/mode direct")
end

As you can see it starts off by dumping the output of ifconfig into a tmp file, and then looks through it to find your current ip (ignoring loopback).

Once it has it, it applies a regex rule to it in my case i want the proxy when my ip starts 10. and doesnt continue 0.0 so 10.0.0.8 has no proxy but 10.107.64.8 does. It also means that i ahve no proxy when on 192 networks.

This ONLY works for Gnome! its possible to run this script by opening up a terminal and running `ruby script.rb` or putting it your sessions, to run on login.

1 Comment :, , , more...

New Machine, New Scripts

by Arcath on Apr.03, 2009, under General, Programming

As i said in my last post i am retiring the eee and getting an MSI Wind as a replacement. Well the Wind turned up on wednesday and i have to say im impressed. I really do like the Wind, the keyboard is small, but not too small, unlike the eee im not pressing the wrong key, or hitting more than one key at a time. The screen is sooo much better, the extra 2″ makes all the differance. The biggest differance is the HDD Size, on the eee i was constantly checking how much space i had left before i installed things or ran updates, with the wind ive got most of the stuff i need on it already and its got 100GB left.

My OS of choice when it comes to non server machines is fedora (which unfourtunatly the eee couldnt take). So the wind was quickly violated by a fedora 10 live pendrive (it never actually booted into the copy of XP that came with it), and 10 mins later i was sat looking at the fedora 10 desktop, looking for things that didnt work, and i came up with a nice check list of things to fix:

  • Wireless

After running an update and doing some research i installed a couple of drivers and tested the card, i then looked on the underside of the wind to see what it had. After searching for the correct drivers and coming up empty i gave up. I am now waiting for a new wireless card to arrive which i will fit in place of the one it was shipped with. The replacement should work no probs.

Of Course with any new machine there are little things that you notice and write scripts for. For me atm its mostly proxy settings. Becasue my wind is used for work where i work in an office and schools i constantly need to swap between the lancashire LEA proxy and no proxy for the office.

The First thing i wrote was a simple bash script to run a yum update through the proxy (which is allways usefull, why update at home when the schools get unlimited fast internet :p)

I then began work on a program that looks at the IP address that the wind has been given and updates its proxy accordingly. So far it is able to determine weather or not i need the proxy but it doesnt set it yet. Im still looking into how fedora sets its proxys. I will post the program when i finish it.

Leave a Comment :, , more...

Looking for something?

Use the form below to search the site:

Still not finding what you're looking for? Drop a comment on a post or contact us so we can take care of it!

Visit our friends!

A few highly recommended friends...