Wednesday, September 9, 2009

Learning PowerShell With Me ..

Day one

What is Powershell ?

Install Powershell

You have to download and install Powershell for windows XP and Vista, but its included in Windows 2008 and windows 7 by default. You just have to enable the feature in Windows 2008.

Lets Begin

start the powershell prompt.

image

A powershell prompt looks very much like a windows command prompt and almost all of the windows commands work well in the powershell command window with a few exceptions. For all of you unix lovers and that includes me, most of the unix commands work well inside powershell too.

Lets start with Dir

Dir command without any switches works exactly the same way it would in a command prompt.

Dir c:

image

but wait Dir c:\program files will not work without the quotes surrounding it, 'cause powershell treats “space” as the delimiter between command and its parameters. So, you should surrounding your path with quotes, to enable powershell to see the whole path properly

dir “c:\program files”

image

Powershell comes with a ton of help, that is readily accessible by using help <commandname>. The help context also supports wildcards.

Help <commandname> -full

will give you a very detailed explanation of the command with examples too.

Type in help dir

image

did you notice that the actual command is called Get-ChildItem. And it provides a bunch of parameter options like -recurse etc., This leads me to believe that “dir” or “ls” are probably aliases for the command Get-ChildItem. I'll probably find out as i go. Personally, i would think its better to stick with the actual cmdlets (yes, these commands are implemented as scripts called cmdlets), than with the aliases, 'cause it will help you get acquainted with the cmdlets and understand the code better as we move on, atleast for the duration of learning powershell. Once you get into actual implementation in real life, its up to. As for me, I'm going to stick with the cmdlets.

So to list a directory:

Get-ChildItem c:\perflogs

or

Get-ChildItem “c:\program files”

to recursively display a folder content

Get-ChildItem -recurse “c:\program files”

gives a long listing, use Ctrl +C, looks like that works in powershell as “Break” too.

PowerShell has the unique ability to navigate an hierarchical structure just like a file system viz., registry or active directory or storage systems. This is awesome, so you could navigate registry like below:

Get-ChildItem HKCU:

image

will list out the contents of HKEY_CURRENT_USER

Guess what the below command does:

Get-ChildItem HKCU: -recurse

you could also change your current location into the registry viz., below:

cd HKLM:\Software

or Set-Location HKLM:\Software
(yes, “cd” is the alias for cmdlet “Set-Location”, as i said, I'm going to stick with cmdlet names instead of aliases)

Same thing can be applied to Environment Variables also. Eg:

Set-Location ENV:

Get-ChildItem ENV:

Get-ChildItem ENV:\systemroot

image

Copy Items

“Copy” is another most used dos command. And the it works the same in powershell too. “Copy” is an alias for cmdlet “Copy-Item”.

Help Copy

or

Help Copy-Item

will reveal all the switches available for the cmdlet. Most commonly use switch would probably be “-recurse”

Delete Items

RD, Del or rm will work exactly as expected, but the underlying cmdlet for all this is “Remove-Item”

you could use rd or del or rm to achieve the same result eg:

rd c:\temp\test.txt

or

del c:\temp\test.txt

or

Remove-Item c:\temp\test.txt

you could also use the same “-recurse” switch to recursively delete folders.

Read contents of a file

Most of us are used to “TYPE” or “CAT” commands to achieve this. The same works in PowerShell too. Eg:

type c:\temp\test.txt

cat c:\temp\test.txt

or use the cmdlet directly

Get-Content c:\temp\test.txt

PowerShell Drives (PSDrives)

As we have seen, powershell lets you navigate registry, storage systems, environment variables etc., using simple navigation commands that we are used to. It can do that, 'cause it loads them as Psdrives or PowerShell Drives.

To see a list of all these PowerShell drives, which you can navigate, type in the below:

Get-PSdrive

image

This will show you all the drives that PowerShell has loaded. The power of navigating through certificate stores, Environment Variables and functions is amazing.

Did you notice that PS (PowerShell) has loaded “alias” as a drive. So lets see all the aliases that PS has built-in by listing the contents of the drive.

Get-ChildItem alias:

image

WOW!, that's a nice list of aliases that can be used. It would be handy to have a printed list (cheatsheet)
of these aliases that you can pinup at your desk. I'll make one up.

Cmdlet Naming syntax

The beauty of the long names is that, they have a consistent naming syntax. Each command has a verb-Singularnoun, syntax. ie., the cmdlet starts with a verb viz., get, remove etc., and ends with the singularnoun, ie., ChildItem, content, Psdrive etc., Stress on the word Singular, 'cause none of the commands actually end in plural, there is no Get-ChildItems or Get-Contents. Cmdlets nouns always are Singular.

Eg: issue the command below to see a list of all cmdlets available to powershell

Get-Command

image

Notice how all the cmdlets start with a verb, and end with a singular noun. None of them have a plural form.

The reason, this is done, is that, it is easier to search of a particular cmdlet, when needed.

Hope you have already started to ride with me and will continue .......

Monday, August 10, 2009

Finding files in Linux / Unix

I have a lot of friends and colleagues who ask me about searching files in unix. Most of them are web-developers and graphic designers, who are typically not from the Unix world and are intimidated by the console world. This blog is mainly for them.

find is a very powerful command, the only problem is figuring out how to use it to get the result you want. In its simplest form, the syntax of find command looks like this:

$ find path parameters/operators

path is the path where you want to search for the files, and parameters/operators are usually the criteria on which you want to find the files eg: name, date etc.,

most common form of find command would be as below:

# find / –name Downloads

The above command will search the complete filesystem for a file/folder named “Downloads”

The other options that are available are

find –name filename find the file filename
find –perm mode finds the files based on the permission/access mode. Access mode here has to be specified in octal viz., 640 etc.,
find –type c finds files based on the filetype, viz.,
b for block special files
c for character special files
d for folders or directories
f for plain files
l for symbolic links
p for Named pipe files
s for socket files
find –name username find files owned by the user <username>. username can be specified as UID
find –group groupname find files owned by the group <groupname>. groupname can be specified as GID
find –size n find files by their size. n  denotes blocks. each block is 512 bytes. +n can be used to look for files larger than n blocks.
find –atime n


-
mtime n

-ctime n
find files last accessed n days ago. to make this command even more powerful, you could use –n to say files accessed less than n days ago.

same as –atime, except that it looks for content modified time

same as –atime except that it looks for access mode changed time
find –newer file finds files that have a modified time stamp that is more recent than the file specified
find operator1 –a  operator2 find files that match operator1 and operator2. this is the default behaviour when two operators are specified, so –a is optional
find operator1 –o operator2 find files that match operator1 or  operator2
find !operator find files that do not match operator
find \{expression \} find using regular expressions…very complex and powerful
-print prints the output to standard output ie., console
-exec command executes the command. command must end with \; as shown in the example below:
# find –name “*.mp3” –exec rm –rf {} \;
the above command will search for files with extension “.mp3” in the current folder and delete them.
{} in the above command will ensure that the complete path of the file is passed onto the command.
-ok command works exactly like –exec command, except that in this case, it prompts the user before executing the command

Some examples:

$ ls –l `find . –type l -print`

find . –type l –print in the above command will print all the symbolic links in the current directory. –print will print it to standard output, in this case, it is being redirected to ls –ld, which in turn will print them in a long listing format.

$ find . –atime 4 –print

will find files that were last accessed 4 days ago

$ find . –mtime 7 –print

will find files that were modified 7 days ago. You also specify a range of time.

$ find . –mtime 7 –mtime –9 –print

will find files that were modified between 7 to 9 days ago.

If you wanted to delete all the files in the current directory and sub-directory that have not been accessed in 90 days, then you would use the command below:

$ find . –atime +90 –exec rm –rf {} \;

pretty powerful isn’t it. you could also tweak this command to delete only the log files like *.log or *.tmp easily.

$ find . –atime +90 \(–name “*.log” –o –name “*.tmp”\) –exec rm –rf {} \;

Combining GREP and FIND

If you wanted to search for a particular word in all the files of a particular directory, then you could do a command substitution with grep as below:

$ egrep ‘findme’ `find . –type f -print`

 

There is a lot more we could do by combining the power of find with other commands. We barely scratched the surface here.

Monday, July 20, 2009

Rose Garden at Hartford,CT

We recently had the pleasure of visiting the Elizabeth Rose Garden in Hartford,CT. Established in 1908, it is the first municipal Rose Garden in the United States. Tucked away in Hartford suburbs, is this beautiful sprawling garden located at the corner of Prospect street and Asylum street. Rose Garden being the main attraction, with lovely arches made up of climbing roses, leading to a gazebo in the center, I bet in its prime bloom, would be the perfect spot for a picturesque wedding. There are other flower gardens too along with some green houses. We reached the garden late evening and with not much daylight left, the photos do not do much justice to the actual location. One has to be there to enjoy the beauty of nature combined with great landscaping.

 

Map picture

Monday, March 23, 2009

Ubuntu Vs Fedora

Everyone has a right to their opinion, a fundamental right bestowed upon us by free democratic constitution. Being in the IT field for over 14 years, i have used a variety of Operating systems ranging from the very Basic DOS to the most current version of Windows 2007 beta.

I have been an avid fan of open-source and have always been a fundamental catalyst of change towards adoption of open-source technologies to my peers, friends and family. I have used a lot of Fedora and Ubuntu. I have implemented a lot of open-source technologies both for work and personal use. I like Ubuntu for its small distribution size both for desktop and server use.

For someone who has not tried it yet, Ubuntu is as close to user-friendly as it can get, to match Windows OS. But the scary fact that I have run into is that, it is becoming one of the unstable distributions that one can find for a Desktop OS, closely following Windows. Stability is the key reason I prefer to host my apps on Linux rather than on Windows (other than cost ;-)). All my network tools run on Linux Platform. All key network services in my network, are hosted on Linux.

Fedora on the other hand, has always been consistent with providing a reasonably stable desktop OS. Its Server version, called CENTOS (though both projects do not seem to be related at all) built to be as close as possible to the commercial REDHAT Linux versions is the most stable, free OS that I have come across. Fedora’s install set is huge compared to Ubuntu, largely due to the multitude of installation options that come with it. The basic install of Fedora can still run into couple of gigabytes. But the stability of the systems installed with Fedora is unparalled compared to Ubuntu.

Ubuntu has now stepped into the mainstream with being the only alternative choice of Operating System that comes pre-installed from desktop/laptop vendor Dell. Rumors are that, soon others will follow. Fedora is yet to see anything close to that. Ubuntu, being a Debain distribution enjoys the user-friendly nature of apt, that actually revolutionized nature of application installations on Linux as a whole. Dependency resolution has long been an issue that was not addressed effectively in REDHAT or SUSE world until APT showed up in Debian. DEBIAN by the way, was a distribution built by Ian Murdock and his wife Deb, and hence the name Debian.

Yum an equivalent of APT for REDHAT or RPM based distributions was plauged with problems in its early development stages. But now with FC9 and FC10, the number of packages available via YUM is no less than APT. Yum like wine has gotten better with age, a boon that FC users like me were waiting for. Fedora has long enjoyed faithful users, while Ubuntu on the other hand is more like the new fad, that everyone is jumping into. Don’t get me wrong, I do agree that Ubuntu is the reason, common man knows about Open-Source technologies and how useful they can be. Ubuntu has brought Linux into the mainstream. Ubuntu has been the push that Linux has been dreaming about.

I now moved all my Ubuntu boxes back to Fedora, and love being an FC geek now. I realized that I missed the geek factor in Ubuntu.

Delegate Unlock User Account in Active Directory

 

I have come across couple of admins who have fought with this problem often. They want to delegate the unlock account function to more accessible, help desk team and are unable to do so. Funny way, Microsoft team thinks, this facility though readily available in Windows, is hidden from view. There is a dat file called dssec.dat in c:\windows\system32 folder. You will also see it in your workstation if you have administrative tools installed.

image

Just open this file with a text editor viz., notepad or Notepad++ (even better), and search for a string called “lockoutTime”. Its located under the “[user]” section.

image

Change the value from “7” to “0”, save the file and exit.

Now Right-Click on the OU that you want to delegate permissions on, and select properties.

image

Click on the security tab (if you don’t see one, then you have to click select View –> Advanced Features on the menu bar)

image

Click on Advanced. click on Add user, enter the username and click on “ok”. In the Permissions Entry window select the “Properties” tab. Drop down the Apply onto list box and select “User Objects”

image

You will see two new persmissions as seen in the figure above. “Read lockoutTime” and “writelockoutTime”. Any user with these two permissions will be able to lock and unlock user accounts, in that OU.

Cheers

Most Useful Cisco IOS commands

I have to admit that I am not an avid cisco person. Just a make do, kind of person like most. Below is a list and explanation of the most useful cisco IOS commands that I have found in my general use. Please feel free to add stuff as you go:

 

1) ‘do’ command

It is a wonderful command that a nice wise guy at CISCO thought of. It was so annoying for me to constantly go back to exec mode from command mode, just to execute some exec commands viz., show.

eg: do show running-config

 

2) time-range

very useful for setting time-range for IP ACL lists. it works like aliases for time-ranges

eg:

time-range lunchbreak

periodic weekdays 1200 to 1300

 

3) show running configuration of a single interface

Another extremely useful command. Its a pain to go through the show running-config command output, specially ‘cause of the time it takes to show the config, specially on lengthy configurations. This is mostly due to the fact that it gathers all the required variables before it shows the config.

A time saver in this case is the below command:

show running config interface serial 0/0

It can also be coupled with the do command to execute the same in the config mode

do show running config interface serial 0/0

 

4) no ip domain-lookup

A very valuable time-saver command for me. I have fat fingers and often tend to typo on my IOS commands. I hate that the router takes a while and tries to resolve my command and takes forever to give me the prompt back. This is usually the first command I enter on a router.

 

5) no logging console

Are you annoyed by the constant logging of error messages on the console, that upset the continuity of your commands. Though not a problem theoretically, it is a problem when working on the console. Use the below command to get rid of that.

no logging console

Tuesday, March 27, 2007

Classless Static Routes using DHCP server

A very hidden and untalked about feature of Microsoft DHCP server is the ability to publish Classless Static Routes to DHCP clients. I have been looking for a feature like this at my company for a while now and was hitting a dry spot over the Internet. So, once I figured out how to successfully do this, I wanted to share it with anyone else who would be looking for this.

Situation:

Consider a situation (like mine), wherein you have a corporate network and want to assign static routes to your client machines, historically the but the only obvious options were:

- to use a *.cmd or *.bat file that the users could execute
- to use a Group Policy to push routes to users

None of these options appealed to me, 'cause about 30-40 percent of my users were mobile users, who often traveled around with their laptops. I did not want the static routes assigned to them, when they connect remotely. Also, they moved frequently between offices and it would create a havoc if they had those routes assigned to them when they were connected at a remote office.

The best possible option would be to somehow assign these routes via DHCP so that their mobile computers forget the route as soon as they disconnected from my network.

This is possible via DHCP option 249 and the appropriate RFC can be found at IETF. I would sincerely recommend giving the RFC a read. It isquite small and easy to understand. Windows 2003 server comes with this option, but for if you are a Network guy who is stuck with Windows 2000 Server (for whatever reason), then you can follow the steps below to
achieve the same:

- Start the DHCP Console


file:///media/sda1/Downloads/Blog/dhcpconsole.png

- Right- Click on "server options" and select "Set Predefined Options" file:///media/sda1/Downloads/Blog/setpredefoptions.png
- Click on "Add" in the "Predefined Options and Values" window, and it
will bring up the "Option type" Window.

file:///media/sda1/Downloads/Blog/addoption.png

- In the "Option Type" window type in the details as shown in the
figure below:

Name = Classless Static Routes
Data type= IP Address : check the checkbox for Array
Code= 249
Description= You can type in any description you want.

file:///media/sda1/Downloads/Blog/classless.png

- Click on "OK" and click on "OK" on the Predefined Options and Values"



Now a little theory on how this Classless Static Route works (or you
could just read the RFP noted above) :

It takes two parameters:

- Destination Descriptor
- Router/Gateway

Destination descriptors describe the IP subnet number and subnet mask
of a particular destination using a particular destination using a
compact encoding. With this kind of encoding the first octet describes
the width of the subnet mask, followed by all the other octets of
the subnet number.

eg:-





































Subnet number Subnet mask Destination descriptor
0 0 0
12.0.0.0 255.0.0.0 8.12
12.0.0.0 255.255.255.0 24.12.0.0
12.19.0.0 255.255.0.0 16.12.19
12.32.131.0 255.255.255.0 24.12.32.131
12.219.0.128 255.255.255.128 25.12.219.0.128

Now that we know how it works, lets start configuring the Scope Options.

- Right-click on "Scope Options" and select " Configure
Options". Select "249 Classless Static Routes" and add the network
address and gateway address one after the other as shown in the figures
below:



file:///media/sda1/Downloads/Blog/addstaticdone.png

- This is how it would look in the DHCP console

file:///media/sda1/Downloads/Blog/addstaticgwdhcpcon.png

- Check your DHCP client ( you may have to renew your IP address for
changes to take effect). Open Command Prompt and type in "route print"

file:///media/sda1/Downloads/Blog/routeprint.png

It sure worked for me.