This work is licensed under the Creative Commons Attribution-ShareAlike 2.5 License. To view a copy of this license, visit http://creativecommons.org/licenses/by-sa/2.5/ or send a letter to Creative Commons, 543 Howard Street, 5th Floor, San Francisco, California, 94105, USA. Originally written by Kynan Dent (http://kynan.org) for TWATech Radio (http://twatech.org). +-= TWAT Intro =---------------------------------------------------------------- | Welcome to TWAT Radio Episode 82: Windows From The Command Line Hi, my names's Kynan and I'm hopefully going to provide you with some information on making Windows system administration from the command line a little easier. We'll be discussing basic command line utilities and their usage for the Windows NT family of Operating Systems. As much as possible, I've covered tools that will work on everything from NT4 through to 2003 but I've NOT paid any attention to the old 9x, DOS based branch of Windows. We're going to look at the utilities that come from Microsoft as part of a base Windows install (or possibly on the CD but not actually installed) or as part of a Resource Kit. We'll also have a look at some very handy third party tools that can be easily obtained for free and one utility that you've got to pay for. The commands I'm going to talk about are commands that I would expcet most Windows sysadmins to know. Because of the nature of this medium it's going to be a little difficult to discuss command line tools without being very very boring so I'm going to mention the tool, what you can do with it, where you can get it and provide a brief insight into how I'd use it. This should be enough information for you to go and get your hands on them and work out the intricacies yourself. This information is intended to make you aware of what is available, there's nothing particularly hard-core here. I've tried to be reasonably comprehensive and to cover all the tools that I use every day but if you're already uber-l33t then you're probably going to be better off somewhere else... | +-= End: TWAT Intro =----------------------------------------------------------- +-= Subject Matter Intro =------------------------------------------------------ | Windows is primarily a Graphical User Interface (GUI) driven platform, however, its Command Line Interface (CLI) support has always been strong, coming as it does from the CLI-only days of DOS; most significantly, it's getting stronger all the time (I'm not going to start comparing with UNIX here - no flamewars please)! If you've never bothered doing a little digging you might be surprised at just how much work you can do from the command line. The problem with covering CLI tools for Windows is that Windows is a big, big family. It is my intent to primarily cover tools that have ALWAYS been available as part of the base OS, followed by tools that are available as part of Resource Kits, followed by a smattering of third party tools that are a part of my daily toolkit. If you're wondering "Why go all they way back to NT4", the environment that I currently work in has servers running NT4 (SP6a) right through to Windows 2003. If you're wondering, the timeline looks like this: Windows NT 4.0 - Released August, 1996 Windows 2000 - Released February, 2000 Windows XP - Released October, 2001 Windows 2003 - Released April, 2003 Before we dig into the tools, I want to mention something that I think is an important part of the "CLI-way": not removing your hands from the keyboard! Your fingers are going to be most productive while they're blazing away on the keyboard. Say you want to start up a program. You need to stop typing, move your hand from your keyboard to your pointing device, click on some icon or menus and then move your hand back again - painfully slow. A nicer alternative is to fire off whatever application, task or function you wanted from the keyboard and this can be acheived through the use of keyboard shortcuts or hotkeys. What's a hotkey? A hotkey is a combination of two or more keys that, when pressed together, perform a specified task. There are a fair few of these hotkeys built-in to Windows, most people are familiar with the Ctrl+C/Ctrl+V shortcuts that perform the Copy/Paste functions in most Windows based programs, well, there are a whole lot more like this! Some are application or suite specific (things like Ctrl+B to Bold things in the Microsoft Office and OpenOffice suites) and some are related to the OS and will do the same thing no matter what application you're in, ie the Windows Logo key+R will bring up the "Run" dialog. It's these OS level hotkeys that I'm mostly thinking about in the context of this article: shortcuts that use the Windows logo key (which I'm going to call the WinKey from now on). There are a few lists of shortcuts and hotkeys that you can check out in the Microsoft Knowledgebase and there's a handy-dandy page called "Keyboard Assistance", part of the Microsoft Accessibility site, that will point you at a lists specific to each OS and Microsoft application. I've compiled a list of URLS at the bottom of this section. Now obviously it is much easier to press Winkey+R than it is to use your mouse to click on [Start] and then [Run] but hey, how many times a day do you really do that? What if you have to run a particular application a lot of times every day? Well, there are some tools available that let you roll-your-own hotkeys. So let's get started, somewhat perversely, with a GUI app! | += URLs ======================================================================== | Keyboard Assistance http://www.microsoft.com/enable/products/keyboard.aspx http://tinyurl.com/9lrja Keyboard shortcuts for Windows: http://support.microsoft.com/default.aspx?scid=kb;en-us;q126449 http://tinyurl.com/4kruh List of the keyboard shortcuts that are available in Windows XP http://support.microsoft.com/default.aspx?scid=kb;en-us;301583 http://tinyurl.com/bpiw History Of Windows OS (up to 2006) http://www.levenez.com/windows | += End: URLs =================================================================== | +- End: Subject Matter Intro =-------------------------------------------------- +-= AutoHotKeys =--------------------------------------------------------------- | I used to use a program called WinKey (produced by a mob called Copernic) that allowed me to define a hotkey combination that included the Windows Key and any other key. It was only when I went to add the URL for WinKey to the shownotes that I discovered that, as of July 14, 2005, Copernic discontinued the distribution of WinKey! This prompted me to look for something to replace it with and what I've found is an awesome open-source solution called AutoHotkey! It's been around since November 2003 and, quite frankly, is an application that could do with its own TWAT. I'll give you a brief rundown on the features and I'll provide a link to the config I talk about in this show. Put simply, AutoHotKeys is a tool to provide custom hotkeys and automation. You run AutoHotkeys and it stays resident and accessible via a System Tray icon. Basically it hooks into the keyboard and does things when the keys you define are pressed. The really cool thing is that it includes a scripting engine that provides the ability to write your own scripts. These scripts can include things like mouse movement, key strokes and add the ability to wait for a certain window to open or become active. The scripting language is extremely feature rich and includes things like messagebox and inputdialog from VB. In addition, it will allow you to compile your scripts into executables! All of this goodliness comes in a 2MB install and will consume about 4MB of RAM when it's running! As with most open-source projects there is a thriving and extensive knowledgebase in the form of the AutoHotkeys forums which, amongst other things contains a pretty comprehensive list of default shortcut keys. I'm not going to say anything more specifically about AutoHotKeys now, but I will refer to it later on. When I DO mention it I'm going to assume that a) you've installed it and b) you've installed it in the default directory. | += URLs ======================================================================== AutoHotkey http://autohotkey.com AutoHotkey Forums: Comprehensive list of Windows hotkeys http://autohotkey.com/forum/viewtopic.php?t=1841 += URLs ======================================================================== | +-= End: AutoHotKeys =---------------------------------------------------------- +-= The Command Interpreter: CMD/COMMAND =-------------------------------------- | Let's kick off with the standard window into the CLI world in Windows: CMD.EXE. You can start a CLI session by clicking on the Start button, clicking on Run and typing in CMD. But like I said before, that takes too damn long and requires that your hand leave the keyboard! Instead, you can use the built-in hotkey WinKey+R, this will bring up the [Run] box automagically and you can type in "cmd" and hit [Enter]. This is annoying as well, more than likely you'll be opening and closing these windows a lot so why not create a hotkey specifically to open a cmd window? This is stunningly easy with AutoHotKeys: 1) Open up C:\Program Files\AutoHotKey\AutoHotkey.ini and add the following two lines to the bottom of the file: ;start a command (cmd) shell #c::Run "%COMSPEC%", C:\ The first line (starting with the semi-colon) is a comment reminding you what the hotkey does, the second line says: When I press the Winkey (represented by the hash) and the "c" key together, execute the command "Run %COMSPEC%". Run is an internal function of AutoHotkey and forks a process to run whatever comes next which in this case is %COMSPEC%. So what the hell is %COMSPEC%? %COMSPEC% is an environment variable that is always set to the correct location of the CMD.EXE executable, the Windows command interpreter. In my case this happens to be C:\WINNT\SYSTEM32\CMD.EXE but sometimes it's in other places. You can see all the other environment variables by typing SET, but we'll look at that in a minute, first lets quickly review two other topics I've mentioned: Environment Variables and Command Interpreters. Environment variables, these are basically variables that are set to specific values and are referencable by anything. There are some environment variables that are set by the OS (like COMSPEC) and you can also create your own. you can expand environment variables out by wrapping them in percent signs. Environment variables are created and deleted using the SET command. The SET command is actually an "internal command", it's a part of the CMD.EXE program; we're going to discuss SET in more detail in a second. Before that: What is a command interpreter? Easy, it's a process that waits for you to tell it to do something and then does it. You tell it what to do by typing on the command line and pressing [enter] when you're done. The command interpreter then looks at what you've typed, interprets it and does what you told it to do. It's important to note that what you TOLD it to do may not be what you WANTED it to do :) If you're coming from *nix land then it's worth noting that the Windows command interpreter is NOT case-sensitive. As far as it is concerned "set prompt", "SeT pRoMpT" and "SET PROMPT" are all identical commands. There are actually two Windows command interpreters on Windows NT servers: CMD.EXE and command.com. CMD.EXE is the native Windows NT command interpreter and command.com is the original DOS/Win9x command interpreter. command.com is included in the NT versions of Windows to allow for backwards compatability with older DOS based apps, effectively it IS DOS. Don't use it. Remember that if you create a BATCH script, ie a file that ends with .BAT then the OS will run it using COMMAND.COM. If you change the .BAT to a .CMD then the OS will use CMD.EXE instead. Let's move on...using your new hotkey (Winkey+c) start up a CMD.EXE window. Now we have a command window open. What can we do with it? Well, I recommend customising it so that it's exactly how you like it - you're going to be spending a lot of time here. There are four main things to customise: 1) Command buffer size 2) Mouse behaviour 3) Font 4) Colour scheme All of this can be set by clicking on the little icon in the top left hand corner of the window and selecting [Defaults] - or you can press Alt+[space], D if you want to stick to the keyboard ;) The first tab is [Options]. and the first section on this tab to change is the [Command History] section. I set [Buffer Size] to 999 which is the number of commands that you'll be able to cycle back through with the arrow keys and [Number Of Buffers] to 4 (don't worry about this for now). In the [Edit Options] section tick all three boxes. [QuickEdit Mode] means you can highlight things and copy them by left-clicking inside the window and paste them by right-clicking. If you don't turn this on you have to switch modes which is REALLY annoying. [Insert Mode] means that when you do paste/insert text it is added to the command line rather than overwriting and [AutoComplete] allows you to use [tab] to complete directory/file names. The next tab, [Font], is the most important thing to change in my opinion. This is because you want to change to a font that obviously differentiates between the zero character and the capital letter o! Using Lucida Console, the default, it's almost impossible to differentiate, even when the characters are right next to each other. I usually set the [Size] to 8x12 and the [Font] to "Raster Fonts". This is good because it's a proportional font which means all of the characters in your output are going to line up! The last tab (I skipped [Layout]) is [Colors]. I like to give my consoles a dark blue background by setting the [Screen Background] to R0 G0 B128 with dark yellow text by setting the [Screen Text] to R255 G255 B0. So, that's how to get a command prompt up and looking pretty. There is a LOT more to cmd than what we've covered so far and we are going to cover a lot of it whilst we're talking about other things. CMD.EXE is kind of like the glue that ties everything else together. I want to cover some other commands now but we'll keep tieing everything back to cmd as we progress. We're about to look at the SET command, you might remember that I mentioned that set was an "internal command" and I want to cover this concept quickly. Basically there are internal commands and external commands. The difference is that you can physically locate an external command whilst an internal command is actually built-in to another program. CMD.EXE is an example of an external command, you can track it down through the %COMSPEC% variable. SET is an internal command and exists only as a part of CMD.EXE. What is the point of this? Well, there are two basic reasons that I can see (Warning: This is my opinion NOT fact). SET is really only useful in the context of the CMD.EXE environment so there's no point in making an executable for the SET command. You'd have to spawn a new CMD.EXE process just to run it and after said CMD.EXE process closes, what is the net system change? Nada! So, SET is built-in to CMD.EXE. The other advantage is that CMD.EXE doesn't have to go through all the pain of spawning a new process and talking to it whilst it runs just to set a variable inside itself. It just flips a few bits internally and moves on with life which makes the whole process a LOT faster. I'll always identify whether a command is internal or external before I start talking about it. Let's look at SET now. | +- Vital Statistics: FILE : CMD.EXE LOCATION : %SYSTEMROOT%\System32 NT4 : Base W2K : Base XP : Base W2K3: Base | +- End: The Command Interpreter: CMD/COMMAND (for now) ------------------------ +- SET ------------------------------------------------------------------------- | Here's what I see when I start up a new CMD.EXE process: +- Screenshot ------------------------------------------------------------------ Microsoft Windows XP [Version 5.1.2600] (C) Copyright 1985-2001 Microsoft Corp. LOCAL C:\> +- End: Screenshot ------------------------------------------------------------- What are we looking at? Well, the first thing that CMD.EXE will tell you is what version of Windows you're it's running on at the moment. This is followed by the "command prompt" or just the "prompt". The prompt is actually an environment variable called PROMPT. In the screenshot above, the prompt says "LOCAL C:\>", if I change directories, to the WINNT directory for instance, then the prompt will change to reflect this: +- Screenshot ------------------------------------------------------------------ LOCAL C:\>cd \WINNT LOCAL C:\WINNT> +- End: Screenshot ------------------------------------------------------------- How does this work? We can find out with the SET command. The SET command, like MOST command line programs, will happily spill its guts on what it does if you pass it the command line argument "/?". Nearly any program, when run with just this parameter, will tell you exactly how it works. A lot of programs will also provide the same information if you just run them with no arguments at all, but some commands might take default action instead, which could possibly do something you didn't want to do. I always try /? before no arguments for this reason. Let's try it with SET and see what it can do: +- Screenshot ------------------------------------------------------------------ LOCAL C:\WINNT>set /? Displays, sets, or removes CMD.EXE environment variables. SET [variable=[string]] variable Specifies the environment-variable name. string Specifies a series of characters to assign to the variable. Type SET without parameters to display the current environment variables. If Command Extensions are enabled SET changes as follows: +- End: Screenshot ------------------------------------------------------------- I've truncated the output because it goes on literally for pages. We'll get to some of the other interesting things that SET can do in a minute but first, back to the prompt. From the help we can see that SET takes a variable name and sets it to a string value. It will also tell us what variables are set if we type "set". Try this now and look at what the PROMPT variable is set to: +- Screenshot ------------------------------------------------------------------ LOCAL C:\WINNT>set ALLUSERSPROFILE=C:\Documents and Settings\All Users CommonProgramFiles=C:\Program Files\Common Files COMPUTERNAME=w00t ComSpec=C:\WINNT\system32\CMD.EXE NUMBER_OF_PROCESSORS=1 OS=Windows_NT OSVER=NT51 Path=C:\WINNT\system32;C:\WINNT;C:\WINNT\System32\Wbem;D:\CYGWIN;C:\Kynan\Script s;C:\Kynan\Tools; PATHEXT=.COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH PROCESSOR_ARCHITECTURE=x86 PROCESSOR_IDENTIFIER=x86 Family 6 Model 9 Stepping 5, GenuineIntel PROCESSOR_LEVEL=6 PROCESSOR_REVISION=0905 ProgramFiles=C:\Program Files PROMPT=LOCAL $P$G SESSIONNAME=Console SystemDrive=C: SystemRoot=C:\WINNT TEMP=C:\Temp TMP=C:\Temp USERNAME=kynan USERPROFILE=C:\Documents and Settings\kynan windir=C:\WINNT +- End: Screenshot ------------------------------------------------------------- We can see that my PROMPT environment variable is set to the string on the right of the equals sign. There are three pieces to this string, the word "LOCAL" followed by the string $P$G. What does this mean: LOCAL : I insert the word LOCAL into my prompt so that I know that I'm on my machine. You might be thinking "Well duh!" but when you're bouncing around on a lot of remote boxes it's good to be able to tell at a glance exactly where you are, or at least where you AREN'T anyway. $P : This is a special string that CMD.EXE will replace with the current drive and directory that you are "in" $G : This is a special string that cmd will replace with the '>' character. This is because '>' is actually a special character by itself and it's a pain in the arse to get a > to appear. I don't think there's any particular reason that '>' has to be the last character of your prompt, it's just an ingrained convention these days. As you can see, there are a whole lot of other environment variables (including COMSPEC) but I'm not going to talk about them here. The last line of the SET help that I included above said something interesting: "If Command Extensions are enabled SET changes as follows:". What does this mean? This is another CMD.EXE option. It means that if the registry key HKEY_CURRENT_USER\Software\Microsoft\Command Processor\EnableExtensions is set to the value 1 that our commands have super-mutant powers! These extensions are built into all versions of Windows NT but are OFF by default in NT4. Windows 2000 and up all have this turned ON by default and I'm not really sure why you'd want to disable them (I've read that it's for compatability with old DOS applications but I've not run into a scenario where they've caused a problem). With Command Extensions on, SET gets some new and useful powers. Suddenly it can do maths and is able to display a specific environment variable instead of spewing out all of them: +- Screenshot ------------------------------------------------------------------ LOCAL C:\>set /A RESULT=2*(4+1)-12 -2 LOCAL C:\>echo %RESULT% -2 LOCAL C:\>set /A RESULT+=2 0 LOCAL C:\>set /a 0x7+0xE 21 LOCAL C:\>set PROMPT PROMPT=LOCAL $P$G +- End: Screenshot ------------------------------------------------------------- integer only mathematics. If you specify ANY floating point number (ie 1.5) then you're going to get a "Missing operator." error and if your answer requires a floating point (ie 3/2) then you're going to get an answer that truncates after the decimal point. Note that I said TRUNCATE, not ROUNDED! The more astute of you will have noticed that there was a hex calculation in the example, and you may also have noticed that the answer is wrong! Well, it's not actually wrong, it's just odd. According to the help from SET you can use the /A switch to manipulate decimal, binary, octal or hexadecimal numbers, depending on the prefix. This is basically a lie! Binary is just plain broken, and any operations done using octal (with a leading 0) or hex (with a leading 0x) will result in an answer that is correct, but converted back to decimal! Unfortunately there aren't any conversion methods provided to turn decimal back into hex or octal which makes the whole exercise somewhat pointless. The mathematics is basically useful for simple looping constructs - don't use it for engineering calculations or anything! SET can also do some handy REGEX style search and replace on environment variables +- Screenshot ------------------------------------------------------------------ LOCAL C:\>set NO_PR0N=Thisxxxisxxxaxxxstring LOCAL C:\>set NO_PR0N=%NO_PR0N:xxx= % LOCAL C:\>set NO_PR0N NO_PR0N=This is a string +- End: Screenshot ------------------------------------------------------------- Check out the help, everything is explained in detail there. | +- Vital Statistics: FILE : SET (Built into CMD.EXE) LOCATION : %SYSTEMROOT%\System32 NT4 : Base W2K : Base XP : Base W2K3: Base | +- End: SET -------------------------------------------------------------------- +- START ----------------------------------------------------------------------- | Once you're hacking away at the command line you may sometimes need to access a GUI program and you don't want to have to use the mouse to go digging through the menus, what can you do? You can use the START command. Let's have a quick look at the START help: +- Screenshot ------------------------------------------------------------------ LOCAL C:\>start /? Starts a separate window to run a specified program or command. START ["title"] [/Dpath] [/I] [/MIN] [/MAX] [/SEPARATE | /SHARED] [/LOW | /NORMAL | /HIGH | /REALTIME | /ABOVENORMAL | /BELOWNORMAL] [/WAIT] [/B] [command/program] [parameters] +- End: Screenshot ------------------------------------------------------------- So START basically lets you spawn a new program in a new window. If you type in "START notepad" then the START command will go looking for a notepad executable in the current directory and then in the PATH environment variable. If it finds it, it runs it. There are a few other switches, /D sets the current working directory for the new program, you can specify the window state using the /MIN and /MAX for minimised and maximised respectively. If you desire it, you can use START to run the program of your choice at the priority of your choice, simply specify the priority using the /LOW.../REALTIME switches. One thing to note, all of the switches need to be BEFORE the command you intend to run. I'm used to being able to put switches wherever and I ended up looking like a right dick when I was complaining that the priority change wasn't working! You can also use START to open a new Explorer window at a desired location. I often use this feature to open an Explorer in the current directory, once I've located a problem. You can do this by running START followed by a fullstop (the fullstop means "the directory that I'm currently in" and two fullstops means "the directory directly above this directory"). You can open other directories by running START followed by the drive/directory name: +- Screenshot ------------------------------------------------------------------ LOCAL C:\>start . LOCAL C:\>start C:\WINNT\SYSTEM32 +- End: Screenshot ------------------------------------------------------------- If your path has spaces in it then you're going to need to wrap it in quotes, and if you do that then START is going to assume that the first thing it sees in double quotes is a window name so you need to kick it off like this: +- Screenshot ------------------------------------------------------------------ LOCAL C:\>start "" "C:\Program Files" +- End: Screenshot ------------------------------------------------------------- Once again, there are command extentions that make START a little more useful. START can be used to open a non-executable file using the default assigned application. For instance if you have a text file called debug with a .txt extension then typing "START debug.txt" will open up Notepad with the debug.txt file opened (assuming that Notepad is still your default editor for .txt files). If there is no default handler then you'll see the normal Windows "How do you want to open this file" window pop up. | +- Vital Statistics: FILE : START (Built into CMD.EXE) LOCATION : %SYSTEMROOT%\System32 NT4 : Base W2K : Base XP : Base W2K3: Base | +- End: START ------------------------------------------------------------------ +- NET ------------------------------------------------------------------------- | Lets look at a bit of a swiss-army knife command now: NET. NET has many uses and I think the best place to start, as usual, is with the built-in help: +- Screenshot ------------------------------------------------------------------ LOCAL C:\>net /? The syntax of this command is: NET [ ACCOUNTS | COMPUTER | CONFIG | CONTINUE | FILE | GROUP | HELP | HELPMSG | LOCALGROUP | NAME | PAUSE | PRINT | SEND | SESSION | SHARE | START | STATISTICS | STOP | TIME | USE | USER | VIEW ] +- End: Screenshot ------------------------------------------------------------- As you can see, there's a lot to cover. I'm only going to mention the portions of NET that I tend to use on a daily basis. The commands can basically be clumped into four groups: 1) Tools to mess with services (CONTINUE, PAUSE, START, STOP) 2) Tools to mess with network shares (USE, SHARE, VIEW, FILE, SESSIONS) 3) Tools to mess with networking settings (COMPUTER, CONFIG, STATISTICS) 4) Help Lets start out with the help functionality because it's pretty cool! For starters, the help for NET is very comprehensive! Type NET HELP to get a slightly more verbose version of the default help screen. If you want help with any of NETs various functions type NET HELP FUNCTION or NET FUNCTION /HELP and you'll get all the details on that particular function. What's more, NET knows where to go looking for the error numbers that you sometimes see in the Event Log. If it's a four digit event code then NET should be able to give you the actual error message (and if you're really luck some possible troubleshooting steps). Let's look at some slightly more useful things. NET can help us manage services, now I suspect that most everyone knows that Windows runs off the back of services and I'm not intending to go into "what is a service" here, suffice to say that, for the most part, a service is just a fancy name for a process! Services generally have two names, a "service name" and a "display name". The service name is generally a short, easy name that programmers use but that doesn't give much information about what the actual service is. The display name is the more descriptive name that is used to identify the service in places where humans would find them. An example is the Windows Installer service. The display name is "Windows Installer" while its service name is MSIServer. Services can be managed using the Services snap-in for the Microsoft Management Console - otherwise known as %SYSTEMROOT%\SYSTEM32\services.msc - but that's a GUI and we don't want to be off waiting for windows and icons to load. Let's see what NET can do: The NET command provides us with four options for controlling services: NET START NET STOP NET PAUSE NET CONTINUE NET START has two functions. If you just type NET START by itself then you will get a list of all running services. If you type NET START followed by a service name or its' display name then NET will attempt to start the service. NET STOP has one function, STOP a service so you must feed it a service name or it won't do anything at all. NET PAUSE and NET CONTINUE are kinda odd and really aren't that useful. If the service in question doesn't have a PAUSE/CONTINUE function built-in then it won't work. +- Screenshot ------------------------------------------------------------------ LOCAL C:\>net start These Windows services are started: Application Layer Gateway Service ... Windows Time Workstation The command completed successfully. LOCAL C:\>net start telnet The Telnet service is starting. The Telnet service was started successfully. LOCAL C:\>net pause Telnet The Telnet service was paused successfully. LOCAL C:\>telnet localhost Telnet service is currently paused.... LOCAL C:\>net continue Telnet The Telnet service was continued successfully. LOCAL C:\>telnet localhost Welcome to Microsoft Telnet Service login:^] LOCAL C:\>net stop telnet The Telnet service is stopping. The Telnet service was stopped successfully. LOCAL C:\>net pause "Windows Installer" The requested pause or stop is not valid for this service. More help is available by typing NET HELPMSG 2191. +- End: Screenshot ------------------------------------------------------------- There are newer commands, like SC, that we could use to mess around with services but NET will be everywhere and SC may not. We'll look at them in a minute. First lets look at then next most useful function of NET: NET USE. NET USE has two main uses: 1) You can use it to map network drives 2) You can use it to authenticate you to a remote server Mapping a network drive is fairly simple and does exactly the same thing as the [Tools] > [Map Network Drive] function in Windows Explorer. If you want to have a new drive mapping you simple type NET USE * \\REMOTESERVER\SHARE_NAME /USER:USERNAME The * will pick the next unused drive name or you can specify an unused drive by replacing the * with the drive you want to use, X: for instance. To make it persistant (it will still be there if you reboot) then add /PERSISTANT to then end of the line. If you just want to be able to do things on the remote server like directory listings using DIR or run any commands that require you to be authenticated, like NET VIEW for example, then you can run NET USE and connect to the IPC share. This is the Inter-Process Communication share and talking more about how this works is well outside of the scope of this document. +- Screenshot ------------------------------------------------------------------ LOCAL C:\>dir \\REMOTE_SERVER\C$ Logon failure: unknown user name or bad password. LOCAL C:\>net view \\REMOTE_SERVER System error 5 has occurred. Access is denied. LOCAL C:\>net use \\REMOTE_SERVER /user:kynan The password or user name is invalid for \\REMOTE_SERVER. Enter the password for 'kynan' to connect to 'REMOTE_SERVER': The command completed successfully. LOCAL C:\>dir \\REMOTE_SERVER\C$ LOCAL C:\>dir \\REMOTE_SERVER\c$ Volume in drive \\REMOTE_SERVER\C$ is DRIVE-C Volume Serial Number is xxxx-xxxx Directory of \\REMOTE_SERVER\C$ 28/02/2006 17:50 Backup 24/02/2006 16:35 Documents and Settings 09/02/2006 14:31 Program Files 05/03/2006 14:08 TEMP 05/03/2006 14:07 WINNT 0 File(s) 0 bytes 5 Dir(s) 8,458,874,880 bytes free LOCAL C:\>net view \\REMOTE_SERVER Shared resources at \\REMOTE_SERVER Share name Type Used as Comment ------------------------------------------------------------------------------- Agents Disk build Disk Reports Disk The command completed successfully. +- End: Screenshot ------------------------------------------------------------- Once you've authenticated then, depending on your account priviliges, you can do almost anything on the remote server. A lot of the commands I'm going to talk about will use this authentication method. There's one more thing that NET USE can do. By itself the NET USE command will show you what drives you've already got mapped: +- Screenshot ------------------------------------------------------------------ LOCAL C:\>net use New connections will not be remembered. Status Local Remote Network ------------------------------------------------------------------------------- OK Y: \\FILESERVER\USERID$ Microsoft Windows Network OK X: \\FILESERVER\GROUP$ Microsoft Windows Network OK \\REMOTE_SERVER\IPC$ Microsoft Windows Network The command completed successfully. +- End: Screenshot ------------------------------------------------------------- This listing shows that I've got three shares currently mapped. The X and Y drives are drives mapped to a shared directory on a fileserver somewhere and the conection I made to the REMOTE_SERVER is listed. Note that there is no drive letter associated with this share. Finally, to remove a connection you've made with NET USE, use the /DELETE switch: +- Screenshot ------------------------------------------------------------------ LOCAL C:\>net use \\REMOTE_SERVER\IPC$ /delete \\REMOTE_SERVER\IPC$ was deleted successfully. +- End: Screenshot ------------------------------------------------------------ | +- Vital Statistics: FILE : NET.EXE LOCATION : %SYSTEMROOT%\System32 NT4 : Base W2K : Base XP : Base W2K3: Base | +- End: NET -------------------------------------------------------------------- +- SC -------------------------------------------------------------------------- | I very briefly mentioned SC when we were talking about working with services with the NET command. SC stands for "Service Control" or "Service Controller" or something like that! SC is very powerful, not only can we start and stop services (like with NET) but you can change the way they start, disable them and even create or delete them. The most obvious things you'll want to do are the same things that you can do with NET. Let's cover those first. Assume for now that we know the service we want to work with. The "Windows Installer" is a good one to play with as you're not going to break anything if you stop or start it. Before getting into that though, there's an important difference betweem SC and NET. Unlike NET, SC will NOT deal with "display names", it will only work if you give it the "service name". Luckily, SC provides a mechanism to obtain the "service name" if you already have the "display name" (and vice versa). To get the service name for the "Windows Installer" run SC with the GetKeyName argument, to get the "display name" use the GetDisplayName argument: +- Screenshot ------------------------------------------------------------------ LOCAL C:\>sc getkeyname "Windows Installer" [SC] GetServiceKeyName SUCCESS Name = MSIServer LOCAL C:\>sc getdisplayname MSIServer [SC] GetServiceDisplayName SUCCESS Name = Windows Installer +- End: Screenshot ------------------------------------------------------------- Stopping and starting services is pretty easy, simply use the START or STOP argument but unlike NET which just says "service started" and "service stopped", SC gives you a LOT more information: +- Screenshot ------------------------------------------------------------------ LOCAL C:\>sc start MSIServer SERVICE_NAME: MSIServer TYPE : 20 WIN32_SHARE_PROCESS STATE : 2 START_PENDING (NOT_STOPPABLE,NOT_PAUSABLE,IGNORES_SHUTDOWN) WIN32_EXIT_CODE : 0 (0x0) SERVICE_EXIT_CODE : 0 (0x0) CHECKPOINT : 0x0 WAIT_HINT : 0x7d0 PID : 604 FLAGS : LOCAL C:\>sc stop MSIServer SERVICE_NAME: MSIServer TYPE : 20 WIN32_SHARE_PROCESS STATE : 3 STOP_PENDING (STOPPABLE,NOT_PAUSABLE,ACCEPTS_SHUTDOWN) WIN32_EXIT_CODE : 0 (0x0) SERVICE_EXIT_CODE : 0 (0x0) CHECKPOINT : 0xc WAIT_HINT : 0x0 +- End: Screenshot ------------------------------------------------------------- I'm not going to go through all of the extra fields now because they're largely irrelevant for standard day-to-day troubleshooting but it is handy to know what they do so I've included a URL to the MSDN discussion about services. Basically you want to pay attention to the STATE field which will tell you what the service is currently doing (or was doing when SC last saw it). Also, like the NET command, you can get a list of running servers by using the QUERY argument. Simply run SC QUERY and you'll get a list of all the running services. +- Screenshot ------------------------------------------------------------------ LOCAL C:\>sc query SERVICE_NAME: ALG DISPLAY_NAME: Application Layer Gateway Service TYPE : 10 WIN32_OWN_PROCESS STATE : 4 RUNNING (STOPPABLE,NOT_PAUSABLE,IGNORES_SHUTDOWN) WIN32_EXIT_CODE : 0 (0x0) SERVICE_EXIT_CODE : 0 (0x0) CHECKPOINT : 0x0 WAIT_HINT : 0x0 SERVICE_NAME: AppMgmt DISPLAY_NAME: Application Management TYPE : 20 WIN32_SHARE_PROCESS STATE : 4 RUNNING (STOPPABLE,NOT_PAUSABLE,IGNORES_SHUTDOWN) WIN32_EXIT_CODE : 0 (0x0) SERVICE_EXIT_CODE : 0 (0x0) CHECKPOINT : 0x0 WAIT_HINT : 0x0 ... +- End: Screenshot ------------------------------------------------------------- This is going to be a VERY long list because each service will be listed with the same information that you get from a START or STOP command. To try and skim only the information we want you can use another command called FINDSTR (we'll discuss this in a bit more detail later but basically it's a program that will scan the output of one command for a string that you've specified and throw everything else. It's like grep, but not! Do NOT expect grep REGEX functionallity). Assuming all you really want to know is the SERVICE_NAME and the STATE you can do this instead: +- Screenshot ------------------------------------------------------------------ LOCAL C:\>sc query | FINDSTR "SERVICE_NAME STATE" SERVICE_NAME: ALG STATE : 4 RUNNING SERVICE_NAME: AppMgmt STATE : 4 RUNNING +- End: Screenshot ------------------------------------------------------------- The QUERY argument has a few parameters that you can pass it so that you can do more granular searches. For instance, using the STATE field you can retrieve only the services that are stopped (state= inactive) instead of the ones that are running or even ALL services installed on the box (state= all). Just remember the slightly odd syntax requires that the state= parameter is seperated from the actual state type by a space: +- Screenshot ------------------------------------------------------------------ LOCAL C:\>sc query state= inactive LOCAL C:\>sc query state= all +- End: Screenshot ------------------------------------------------------------- So, we can stop and start services, get names of known services and list services by their status, running, stopped or just present. What more could you want to do to a service? Well, SC doesn't just work WITH services it can work ON them as well. There are three start types for a non-driver service: Auto: Service starts automatically at boot time Demand: Service starts "on demand" Disabled: Service WILL NOT START, even if you explicitly request it. Let's say that the Windows Installer service has been disabled "for security purposes". You want to turn it back on so that you can install something. SC has command called CONFIG to do just that. The CONFIG command has a counterpart command, QC. This stands for Query Config. Using QC you can see what the current configuration settings are for a particular service. This gives you all kinds of useful information including the location for the service executable, any dependencies it may have and when it starts up (amongst other things): +- Screenshot ------------------------------------------------------------------ LOCAL C:\>sc qc MSIServer [SC] GetServiceConfig SUCCESS SERVICE_NAME: MSIServer TYPE : 20 WIN32_SHARE_PROCESS START_TYPE : 4 DISABLED ERROR_CONTROL : 1 NORMAL BINARY_PATH_NAME : C:\WINNT\system32\msiexec.exe /V LOAD_ORDER_GROUP : TAG : 0 DISPLAY_NAME : Windows Installer DEPENDENCIES : RpcSs SERVICE_START_NAME : LocalSystem +- End: Screenshot ------------------------------------------------------------- Running SC CONFIG will provide you with enough help to make an informed decision on what you want to do. To change the start type you just need to run SC CONFIG SERVICE_NAME start= START_TYPE: +- Screenshot ------------------------------------------------------------------ LOCAL C:\>sc start msiserver [SC] StartService FAILED 1058: The service cannot be started, either because it is disabled or because it has no enabled devices associated with it. LOCAL C:\>sc config MSIServer start= demand [SC] ChangeServiceConfig SUCCESS LOCAL C:\>sc qc MSIServer [SC] GetServiceConfig SUCCESS SERVICE_NAME: MSIServer TYPE : 20 WIN32_SHARE_PROCESS START_TYPE : 3 DEMAND_START ERROR_CONTROL : 1 NORMAL BINARY_PATH_NAME : C:\WINNT\system32\msiexec.exe /V LOAD_ORDER_GROUP : TAG : 0 DISPLAY_NAME : Windows Installer DEPENDENCIES : RpcSs SERVICE_START_NAME : LocalSystem LOCAL C:\>sc start msiserver SERVICE_NAME: msiserver TYPE : 20 WIN32_SHARE_PROCESS STATE : 2 START_PENDING (NOT_STOPPABLE,NOT_PAUSABLE,IGNORES_SHUTDOWN) WIN32_EXIT_CODE : 0 (0x0) SERVICE_EXIT_CODE : 0 (0x0) CHECKPOINT : 0x0 WAIT_HINT : 0x7d0 PID : 1368 FLAGS : +- End: Screenshot ------------------------------------------------------------- There is a lot more to SC and I highly reccomend reading the whole man page (or whatever they're called in MS land. += URLs ======================================================================== MSDN Services Entry - there's a LOT of good information here http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dllproc/base/se rvices.asp http://tinyurl.com/ac9d += End: URLs =================================================================== | +- Vital Statistics: FILE : SC.EXE LOCATION : %SYSTEMROOT%\System32 NT4 : Resource Kit W2K : Resource Kit XP : Resource Kit W2K3: Base | +- End: SC --------------------------------------------------------------------- +- FIND / FINDSTR -------------------------------------------------------------- | We looked at what FINDSTR can do a minute ago and if you are using Windows after any of the Unix-based OSes then you'll have noticed that this is a lot like the functionality provided by GREP. Unfortunately both FIND and FINDSTR come in well below the bar set by GREP! I will talk about GREP in a second but, in keeping with the theme of "using what's always available", let's look at FIND and FINDSTR. First, what's the difference between the two? Essentially nothing but you can think of FINDSTR as what FIND would want to be when it grew up. Both FIND and FINDSTR have been around since NT 4.0 and both exist to look through some text and print out whatever matches your search criteria. In order to show how these two commands work I've created a text file as shown here: +- Screenshot ------------------------------------------------------------------ LOCAL C:\>type c:\temp\findtest.txt This is Line 1 of the file This is line 2 of the file This is Line Three of the file This is line 4 of the file Mysterious entry number one Random garbage: sji2387yhuik This is line 5 of the file This is Line Six of the file +- End: Screenshot ------------------------------------------------------------- The help for FIND is short and sweet: +- Screenshot ------------------------------------------------------------------ LOCAL C:\>find /? Searches for a text string in a file or files. FIND [/V] [/C] [/N] [/I] [/OFF[LINE]] "string" [[drive:][path]filename[ ...]] /V Displays all lines NOT containing the specified string. /C Displays only the count of lines containing the string. /N Displays line numbers with the displayed lines. /I Ignores the case of characters when searching for the string. /OFF[LINE] Do not skip files with offline attribute set. "string" Specifies the text string to find. [drive:][path]filename Specifies a file or files to search. If a path is not specified, FIND searches the text typed at the prompt or piped from another command. +- End: Screenshot ------------------------------------------------------------- I think that's all pretty basic and self-explanatory, to find all lines that contain the word "line" in my test file for instance you'd run: FIND "line" C:\TEMP\findtest.txt. The most important thing to remember is that you MUST wrap the string you're looking for in double quotes. FIND does not support any regular expressions at all. You can make it case-insensitive with the /I switch but that's all. For more hard-core searching we turn to FINDSTR. +- Screenshot ------------------------------------------------------------------ LOCAL C:\>findstr /? Searches for strings in files. FINDSTR [/B] [/E] [/L] [/R] [/S] [/I] [/X] [/V] [/N] [/M] [/O] [/P] [/F:file] [/C:string] [/G:file] [/D:dir list] [/A:color attributes] [/OFF[LINE]] strings [[drive:][path]filename[ ...]] /B Matches pattern if at the beginning of a line. /E Matches pattern if at the end of a line. /L Uses search strings literally. /R Uses search strings as regular expressions. /S Searches for matching files in the current directory and all subdirectories. /I Specifies that the search is not to be case-sensitive. /X Prints lines that match exactly. /V Prints only lines that do not contain a match. /N Prints the line number before each line that matches. /M Prints only the filename if a file contains a match. /O Prints character offset before each matching line. /P Skip files with non-printable characters. /OFF[LINE] Do not skip files with offline attribute set. /A:attr Specifies color attribute with two hex digits. See "color /?" /F:file Reads file list from the specified file(/ stands for console). /C:string Uses specified string as a literal search string. /G:file Gets search strings from the specified file(/ stands for console). /D:dir Search a semicolon delimited list of directories strings Text to be searched for. [drive:][path]filename Specifies a file or files to search. Use spaces to separate multiple search strings unless the argument is prefixed with /C. For example, 'FINDSTR "hello there" x.y' searches for "hello" or "there" in file x.y. 'FINDSTR /C:"hello there" x.y' searches for "hello there" in file x.y. Regular expression quick reference: . Wildcard: any character * Repeat: zero or more occurances of previous character or class ^ Line position: beginning of line $ Line position: end of line [class] Character class: any one character in set [^class] Inverse class: any one character not in set [x-y] Range: any characters within the specified range \x Escape: literal use of metacharacter x \ Word position: end of word For full information on FINDSTR regular expressions refer to the online Command Reference. +- End: Screenshot ------------------------------------------------------------- FINDSTR has several distinct advantages over FIND, foremost amongst these are its ability to search using regular expressions and pattern anchoring and to search not only a specified file but to recursively search through directories looking for files to search in. In order to use FINDSTR to it's fullest potential you need to know the basics of regular rexpressions, and I'm not going to cover that here. The FINDSTR help covers it enough for you to use it and I recommend that you check out regex.info for more information. A couple of examples: To find all the lines that contain the word line: +- Screenshot ------------------------------------------------------------------ LOCAL C:\>FINDSTR line c:\temp\findtest.txt This is line 2 of the file This is line 4 of the file This is line 5 of the file +- End: Screenshot ------------------------------------------------------------- That returned all of the lines that have the word line on them, note that unlike FIND, double quotes are not required for the search string. Note also that we didn't get any lines where the word "line" started with a capital L. To get those as well you've got a couple of options. You could use the /I switch which, exactly like FIND, will search for any permutation of upper and lowercase letters but that's not as precise. If we only wanted to find lines with the word "line" or "Line" then /I won't work as it will return "lIne", "LiNe", etc. Instead we can use FINDSTRs regular expression capabilities: +- Screenshot ------------------------------------------------------------------ LOCAL C:\>FINDSTR [Ll]ine c:\temp\findtest.txt This is Line 1 of the file This is line 2 of the file This is Line Three of the file This is line 4 of the file This is line 5 of the file This is Line Six of the file +- End: Screenshot ------------------------------------------------------------- By defining a "class" in the square brackets we've said find any word that starts with "l" or "L" followed by lowercase "ine". Basically FINDSTR will attempt to match any characters in the square brackets but only one at a time. Note that I didn't have to tell FINDSTR to treat the search string as a regular expression, it treats all strings as regular expressions unless explicitly told not too. Let's say that we wanted all lines that have the word line, starting with lower- or upper-case L but only the lines where the word "line" is directly followed by a number. +- Screenshot ------------------------------------------------------------------ LOCAL C:\>FINDSTR /R /C:"[Ll]ine [0-9]" c:\temp\findtest.txt This is Line 1 of the file This is line 2 of the file This is line 4 of the file This is line 5 of the file +- End: Screenshot ------------------------------------------------------------- Because FINDSTR will treat a search string wrapped in double quotes as multiple search strings (ie "Hello World" will cause FINDSTR to search for the word Hello OR the word World on every line). In order to get around that you need to use the /C: sitch. This tells FINDSTR that you want it to search for the string, exactly as you typed it. Since our string also contains a regular expression we have to tell FINDSTR that it needs to look out for regex characters in the string. Finally, note that "[0-9]" class. This is a handy way to specify that you want any character that matches a number. It is exactly the same as typing "[0123456789]". You can use the same functionality to define groups of numbers: [0-49] is the same as [012349] and it also works with letters: [a-dA-D] will match a, b, c or d in upper or lower case. The other cool feature of FINDSTR is its' ability to go searching in multiple files and subdirectories. FIND CAN be given multiple files, but each file will have a header line printed out for it, even if FIND doesn't actually locate the string you told it to look for so it can get pretty ugly. FINDSTR will only produce output IF it finds the text you told it to look for. If you add the /S switch to the command line then it will start recursing into subdirectories to look for other files. to search all log files for the string "w00t" in the TEMP direcotry and all of its subdirectories you would do this: FINDSTR /S w00t C:\TEMP\*.LOG It looks a bit odd specifying the directory like that but it will check all files with a .LOG extension for the string w00t in C:\TEMP and any directory under that. So that's FIND and FINDSTR in a nutshell. I've really only covered the basic functionality here - there are more tricks that you'll learn as you use them. I just want to quickly touch on GREP here before we move on. GREP is NOT a Windows tool. It originated in Unix and it's primary purpose is finding patterns in files using regular expressions and telling you what they were or where it found them. GREP actually stands for global regular expression print, coming from the old ex command g/re/p - but that's not what we're here to talk about. If you run into something that the regex engine that the FINDs use can't parse like a logical OR for instance (grep 'dos|windows' will search for a line that has either "dos" or "windows" on it) then use grep. I've provided a link to a quite old version of grep but I like this one because it's only 103K and has NO external dependencies. += URLs ======================================================================== grep for Windows (with no external dependencies) http://www.interlog.com/~tcharron/grep.html http://tinyurl.com/ps7mu += End: URLs =================================================================== | +- Vital Statistics: FILE : FIND.EXE/FINDSTR.EXE LOCATION : %SYSTEMROOT%\System32 NT4 : Base W2K : Base XP : Base W2K3: Base | +- End: FIND / FINDSTR --------------------------------------------------------- +- REG / REGFIND --------------------------------------------------------------- | Let's talk about the registry now. Everything in Windows from the OS up stores its' settings in the registry. Essentially, the registry is the heart of the Windows OS. Now I'm assuming that you're an admin and you know all about the registry and you're aware that there IS a reason that every MS KB article that mentions tweaking the registry has this warning on the front of it: IMPORTANT: This article contains information about modifying the registry. Before you modify the registry, make sure to back it up and make sure that you understand how to restore the registry if a problem occurs. Or my favourite, from the Regedit helpfile: !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! CAUTION: Incorrectly editing the registry may severely damage your system. Before making changes to the registry, you should back up any valued data on your computer. !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! Personally I've NEVER destroyed a machine by messing with the registry but I DO know of people who have. Don't be afraid of the registry, but it IS worth being cautious! Onwards! The normal GUI way to access the registry is via either regedit.exe or REGEDT32.EXE and there are a couple of command line parameters that will allow you to use regedit.exe to create backups and make additions to the registry. To backup either a portion of or even the entire registry, use the /E switch. If you want the whole thing then just /E will do the trick. If you want a portion then you need to add the key after the /E like this: "/E "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion". You'll end up with a plain text file dump of the registry (but it's likely to be quite large): +- Screenshot ------------------------------------------------------------------ LOCAL C:\TEMP>regedit /e registry_backup.reg LOCAL C:\TEMP>dir registry_backup.reg Volume in drive C is DRIVE-C Volume Serial Number is 1007-71FB Directory of C:\TEMP 05/03/2006 15:19 34,734,082 registry_backup.reg 1 File(s) 34,734,082 bytes 0 Dir(s) 5,158,752,256 bytes free +- End: Screenshot ------------------------------------------------------------- In a similar way you can put data back into the registry. By crafting a plain text file using the right syntax you can create a file that regedit will happily import. The command line for this is just regedit . This is all pretty clumsy though - we want to manipulate things on the fly, not mess around with text files that have to be copied around all over the place and REG is the tool to do just that! +- Screenshot ------------------------------------------------------------------ LOCAL C:\>reg /? Console Registry Tool for Windows - version 3.0 Copyright (C) Microsoft Corp. 1981-2001. All rights reserved REG Operation [Parameter List] Operation [ QUERY | ADD | DELETE | COPY | SAVE | LOAD | UNLOAD | RESTORE | COMPARE | EXPORT | IMPORT ] ... +- End: Screenshot ------------------------------------------------------------- That looks pretty comprehensive! You can do nearly everything you'd ever need to do to the registry from here the only thing you can't do is search. The QUERY operation will only print out what keys are present at whatever key you specify, it can't search. Obviously that's a bit of a bummer so we'll detour briefly to look at REGFIND. REGFIND is a resource kit tool that allows you to search OR search and replace. It goes without saying that search and replace is something you should think about VERY carefully before executing, REGFIND isn't going to stop and ask if you're REALLY sure before it replaces all occurences of "Win" with "Lose" for example and I'd say that'd be pretty disastrous! Unfortunately REGFIND doesn't follow standard registry (regedit) format and it's output can be a bit ugly. I tend to use REGFIND to locate the area the key I'm looking for is in and then I'll switch to REG to find out exactlly what's there. The main thing to remember with REGFIND is the -n option which tells it to look for your search string in the key name as well as in the values (assuming you aren't exactly sure where the damn thing is) and the -y option which makes the search case insensitive. Right, back to REG. Most of the operation is pretty obvious. But let's look at an example. Lets say you wanted to check if 8.3 names are disabled on your box. You can use the QUERY option of REG to check: +- Screenshot ------------------------------------------------------------------ LOCAL C:\>reg query HKLM\SYSTEM\CurrentControlSet\Control\FileSystem /v NtfsDisable8dot3NameCreation ! REG.EXE VERSION 3.0 HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\FileSystem NtfsDisable8dot3NameCreation REG_DWORD 0x1 +- End: Screenshot ------------------------------------------------------------- The /v tells REG that I want to check a specific key "NtfsDisable8dot3NameCreation", if I'd left everything from /v onwards off then REG would return all values under the FileSystem key. I can see from the output that 8.3 filenames are in fact disabled on this machine. This is a big pain in the arse if certain things are expecting to be able to access directories via 8.3 names so I want to turn this option off. I can do this with REG too: +- Screenshot ------------------------------------------------------------------ LOCAL C:\>reg add HKLM\SYSTEM\CurrentControlSet\Control\FileSystem /v NtfsDisable8dot3NameCreation / t REG_DWORD /d 0 Value NtfsDisable8dot3NameCreation exists, overwrite(Y/N)? Y The operation completed successfully +- End: Screenshot ------------------------------------------------------------- You can get around that prompt by adding /F to the command line to force REG to overwrite anything it finds. The alternative to changing that value would be deleting it as it's not really required (8.3 is assumed to be required unless you specify otherwise). To delete the key we could do this: +- Screenshot ------------------------------------------------------------------ LOCAL C:\>reg delete HKLM\SYSTEM\CurrentControlSet\Control\FileSystem /v NtfsDisable8dot3NameCreation Delete the registry value NtfsDisable8dot3NameCreation (Y/N)? Y The operation completed successfully +- End: Screenshot ------------------------------------------------------------- Once again, /F can be used to override the prompt. This is all pretty basic though, let's look at the really cool stuff you can do with REG! REG COPY will allow you to copy a key and all its' subkeys from one portion of the registry to another (for backup purposes perhaps). It can also allow you to copy a key from the registry on one computer to another! This can be really handy if you have a standard environment and someones fragged their office settings or something, you can just copy and force an overwrite - problem solved - note that you can only access HKLM and HKU on remote machines. REG COPY is handy if you have a registry that you can access at the time to load the settings in from but if you want them in a more portable format then you've got two options. REG SAVE and REG EXPORT. Each of these options comes in a pair. You've got SAVE/RESTORE and EXPORT/IMPORT. We'll look at SAVE/RESTORE first: REG SAVE will dump what you tell it to in a binary format. You'll need REG to put back in again using the RESTORE option. It is customary to name these files with a .hiv (for hive) extension. Like the COPY option you can run this command on a remote server but there's a small gotcha, the file will be saved on the REMOTE server, not your local server! Once you've saved your file you can load it back into a registry using REG RESTORE. The painful ting about RESTORE is that you need to tell it exactly where to RESTORE the data to. If you SAVEd HKLM\Software\Windows\Mozilla then you need to specify exactly that on the command line when you run the restore. This is a double-edged sword though as this also means that you can choose to restore the SAVEd data back into another key if you wish! +- Screenshot ------------------------------------------------------------------ LOCAL C:\>REG SAVE HKLM\Software\Mozilla Mozilla.hiv The operation completed successfully LOCAL C:\>REG add HKLM\Software\Test_Mozilla The operation completed successfully LOCAL C:\>REG RESTORE HKLM\Software\Test_Mozilla Mozilla.hiv The operation completed successfully +- End: Screenshot ------------------------------------------------------------- The difference between SAVE/RESTORE and EXPORT/IMPORT is that EXPORT will dump an ASCII text "reg" file that you can use either REG or REGEDIT to import back into the registry. This means that you can't adjust where you're going to IMPORT in the registry as the .reg file will contain fully qualified paths. Also, you can NOT run this on a remote server. +- Screenshot ------------------------------------------------------------------ LOCAL C:\>REG export HKLM\Software\Mozilla Mozilla.reg The operation completed successfully LOCAL C:\>reg import Mozilla.reg The operation completed successfully +- End: Screenshot ------------------------------------------------------------- The last pair of instructions is LOAD/UNLOAD. I dn't use these a great deal but they allow you to temporarily "load" a .HIV file as a part of the registry, this can be handy if you want to LOAD a .HIV so that you can play with it in REGEDIT or extract a small portion of it. += URLs ======================================================================== Description of the Microsoft Windows registry http://support.microsoft.com/default.aspx?scid=kb;EN-US;256986 http://tinyurl.com/isxm += End: URLs =================================================================== | +- Vital Statistics: FILE : REG.EXE LOCATION : %SYSTEMROOT%\System32 NT4 : Resource Kit W2K : Resource Kit XP : Base W2K3: Base | FILE : REGFIND.EXE LOCATION : Wherever you installed the Resource Kit to. NT4 : Resource Kit W2K : Resource Kit XP : Resource Kit W2K3: Resource Kit | +- End: REG / REGFIND ---------------------------------------------------------- +- AT -------------------------------------------------------------------------- | I'm going to touch on AT very quickly because it got me out of a pickle recently! It's nothing particualrly exciting. It basically plugs-in to the Windows Task Scheduling service and runs a command that you specify at a time that you specify. This means that at will NOT work if the Schedule service is not running. AT is a very simple command. You create an AT job by typing AT HH:MM COMMAND. If you want to delete a job, AT JOB_ID /DELETE. That's about it. There are problems with creating long running at jobs so you're better off using the tash scheduler proper for creating weekly cleanup scripts and things like that. There are two really handy things you can do with AT: 1) You can schedule something to happen about in the very near future, perhaps just after you make a change that could cause you to lose connectivity to the machine. 2) You can schedule something to happen as another user. Let's look at option one first. Say you would like to change something about the TCP/IP setup of a machine, switch it to a static IP instead of DHCP perhaps. All well and good but if you're making that change remotely then you're session is going to be disconnected, and what if something goes wrong? What if you typed a number incorrectly? All of a sudden that machine is off the air until you can travel to it and set things right. Alternatively you can set a script to run five or ten minutes after you intend to make the change that will revert everything back the way it was before you changed anything. If the change goes well you can just kill the AT job, if it doesn't then you can wait for ten minutes and the machine should come back when your script runs! Here's an example: +- Screenshot ------------------------------------------------------------------ LOCAL C:\>at 17:30 %COMSPEC% /k "netsh interface ip set address USB dhcp" Added a new job with job ID = 1 LOCAL C:\>at Status ID Day Time Command Line ------------------------------------------------------------------------------- 1 Today 17:30 PM C:\WINNT\system32\cmd.exe /k "netsh interface ip set address USB dhcp" LOCAL C:\>netsh interface ip set address USB static 10.0.0.100 255.255.0.0 10.0.0.1 1 Ok. - Lose Session here and re-connect to new IP - LOCAL C:\>at 1 /delete +- End: Screenshot ------------------------------------------------------------- Nothing went wrong for me, but if it DID I could just twiddle my thumbs until the AT job kicked off and the machine should come back when it switches back to DHCP. Since I didn't want the NIC to switch back to DHCP I deleted the job. The other handy thing about AT is that anything that you schedule to run will run as the user that the Schedule service is running as. Using the /INTERACTIVE switch will let you open up a Command Shell ON THE CONSOLE ONLY. This can be handy if you need to access the system as the LocalSystem user, to check on some mapped drives for instance. +- Screenshot ------------------------------------------------------------------ LOCAL C:\>time The current time is: 16:44:13.99 Enter the new time: LOCAL C:\>at 16:45 /interactive %COMSPEC% Added a new job with job ID = 1 LOCAL C:\>at Status ID Day Time Command Line ------------------------------------------------------------------------------- 1 Today 16:45 PM C:\WINNT\system32\cmd.exe +- End: Screenshot ------------------------------------------------------------- AT was pretty much superceded by SCHTASKS but it's kept around for backward compatability and since it's only two keystrokes I'm sticking with it for now! | +- Vital Statistics: FILE : AT.EXE LOCATION : %SYSTEMROOT%\System32 NT4 : Base W2K : Base XP : Base W2K3: Base | +- End: AT --------------------------------------------------------------------- +- Networking Utilities Intro -------------------------------------------------- | For the most part the tools we've looked at so far are for administering the local machine but it's rare that you'll be working on just one machine these days so let's have a look at some of the tools that can help when working with multiple machines. Before we head into this section I would advise ANY system administrator who doesn't have a decent grasp on the basics of networking to go and read the intro to CCNA course - it will make your life a lot easier (and you can blame the network guys for more stuff ;) I'm going to assume that you're working in a TCP/IP environment for most everything in this section. | +- End: Networking Utilities Intro---------------------------------------------- +- IPCONFIG -------------------------------------------------------------------- | Let's start with IPCONFIG. If you know IFCONFIG from the world of UNIX then you can visualise IPCONFIG like this: imagine if IFCONFIG had a twin brother from which it was seperated at birth. IFCONFIG was taken to parties and generally had a great and educational childhood; IPCONFIG was dropped on its head, slept in a box and was whipped with chains everyday (I'm thinking of Chunk from The Goonies). While IFCONFIG grew up to be a happy and useful part of society, IPCONFIG grew up misshapen and stunted with the ability to perform only the most basic of tasks. That probably wasn't very helpful really. IPCONFIG has two basic functions: 1) Display current TCP/IP configuration 2) Perform basic DHCP related tasks (release/renew) The display function has two flavours, basic and full. If you type IPCONFIG by itself then you will get a display showing your current DNS suffix, IP address, subnet mask, default gateway and, if you're running off DHCP, your DHCP CLASS ID. +- Screenshot ------------------------------------------------------------------ LOCAL C:\>ipconfig Windows IP Configuration Ethernet adapter Onboard: Connection-specific DNS Suffix . : INTERNAL.NET. IP Address. . . . . . . . . . . . : 10.0.0.100 Subnet Mask . . . . . . . . . . . : 255.255.0.0 Default Gateway . . . . . . . . . : 10.0.0.1 DHCP Class ID . . . . . . . . . . : DHCP_AUTH LOCAL C:\>ipconfig /all Windows IP Configuration Host Name . . . . . . . . . . . . : LOCAL_MACHINE Primary Dns Suffix . . . . . . . : INTERNAL.NET Node Type . . . . . . . . . . . . : Hybrid IP Routing Enabled. . . . . . . . : No WINS Proxy Enabled. . . . . . . . : No DNS Suffix Search List. . . . . . : INTERNAL.NET Ethernet adapter Onboard: Connection-specific DNS Suffix . : INTERNAL.NET. Description . . . . . . . . . . . : Intel(R) PRO/1000 MT Mobile Connection Physical Address. . . . . . . . . : 01-23-45-67-89-AB Dhcp Enabled. . . . . . . . . . . : Yes Autoconfiguration Enabled . . . . : Yes IP Address. . . . . . . . . . . . : 10.0.0.100 Subnet Mask . . . . . . . . . . . : 255.255.0.0 Default Gateway . . . . . . . . . : 10.0.0.1 DHCP Class ID . . . . . . . . . . : DHCP_AUTH DHCP Server . . . . . . . . . . . : 10.0.0.10 DNS Servers . . . . . . . . . . . : 10.0.1.10 Primary WINS Server . . . . . . . : 10.0.1.10 Secondary WINS Server . . . . . . : 10.0.0.10 Lease Obtained. . . . . . . . . . : 05 March 2006 09:03:38 Lease Expires . . . . . . . . . . : 15 March 2006 09:03:35 +- End: Screenshot ------------------------------------------------------------- So you can see from the output that I'm running off a DHCP assigned IP. If I wanted to let it go and obtain a new IP I could run IPCONFIG with the /RELEASE switch followed by the /RENEW switch. More than likely the DHCP server is just going to give you back the same IP though (depending on how it's set up). There are other options available but they don't get used a great deal. | +- Vital Statistics: FILE : IPCONFIG.EXE LOCATION : %SYSTEMROOT%\System32 NT4 : Base W2K : Base XP : Base W2K3: Base | +- End: IPCONFIG --------------------------------------------------------------- +- NETSH ----------------------------------------------------------------------- | So, you can check your IP and stuff, but what if you want to actualy SET it, or swap from DHCP to static? Net Shell aka NETSH can do all this and more. NETSH is actually a front-end to a whole lot of "Helper" DLLs. These helpers provide a whole lot of extra functionality. There are two ways to access NETSH. You can just type NETSH at the command line and you'll be dropped into a "Net Shell" or you can write the whole command out on the command line. Here is an example of setting a static IP using both methods: +- Screenshot ------------------------------------------------------------------ LOCAL C:\>netsh netsh>interface netsh interface>ip netsh interface ip>show address Configuration for interface "Onboard" DHCP enabled: Yes InterfaceMetric: 0 netsh interface ip>set address Onboard static 10.0.0.100 255.255.0.0 Ok. netsh interface ip>show address Configuration for interface "Onboard" DHCP enabled: No IP Address: 10.0.0.100 SubnetMask: 255.255.0.0 Default Gateway: 10.0.0.1 GatewayMetric: 1 InterfaceMetric: 0 netsh interface ip>set address Onboard dhcp Ok. netsh interface ip>bye LOCAL C:\>netsh interface ip set address Onboard static 10.8.237.170 255.255.255.0 10.8.237.1 1 Ok. +- End: Screenshot ------------------------------------------------------------- I've demonstrated changing IPs because this, more than likely, it's the most common thing to do with netsh. However this is barely the tip of the iceberg, if you use a Windows server as a router for instance, then all of your routing commands and setup are configured via netsh. If you're interested in this then check out the help pages. | +- Vital Statistics: FILE : NETSH.EXE LOCATION : %SYSTEMROOT%\System32 NT4 : Resource Kit W2K : Base XP : Base W2K3: Base | +- End: NETSH ------------------------------------------------------------------ +- ROUTE ----------------------------------------------------------------------- | I mentioned the word route (or root if you're English or American) and I think it's worth noting that netsh will NOT help you with local routes. For this you need to use ROUTE. I'm not going to get into networking because that's a huge, huge topic and I'm just going to assume knowledge. If you're not 100% on how IP works and what routes actually do then I'd recommend not playing with this command (not in a Production environment anyway). The thing that is handy to remember is that a lot of problems, especially on multi-homed machines, are caused by the default route pointing to the wrong gateway. You can check this using the DISPLAY switch and looking for the line that starts with the words "Default Gateway", use FINDSTR to make this a bit easier: +- Screenshot ------------------------------------------------------------------ LOCAL C:\>route PRINT | findstr Default Default Gateway: 10.0.0.1 +- End: Screenshot ------------------------------------------------------------- This is a pretty simple tool and has three other options, you can: 1) Add a route 2) Modify a route 3) Delete a route The syntax is explained perfectly well by the built-in help so I'll say no more on the subject! | +- Vital Statistics: FILE : ROUTE.EXE LOCATION : %SYSTEMROOT%\System32 NT4 : Base W2K : Base XP : Base W2K3: Base | +- End: ROUTE ------------------------------------------------------------------ +- PING / TRACERT / ARP -------------------------------------------------------- | Speaking of troubleshooting, a LOT of issues (including "slow" response from applications) can often be traced back to misconfiguration of network settings. I'm going to mention a few things that have bugged me in the recent past, but first a quick intro to the three main network troubleshooting tools (we'll move the some more Windows flavoured stuff in a second). The number one place to start with network connectivity questions is PING. TRACERT and ARP can come in handy also. Again, there are some network smarts involved in these pieces of sofware but you don't really need to know HOW they work, just what it means if they don't! PING basically throws a packet at whatever IP address you specify and requests that the owner of the IP throws the packet back. TRACERT does a similar thing but it does some tricks to make sure that all the routers (or hops) on the way to the remote machine let you know who they are. ARP reports on the MAC address associated with an IP on your network segment. This is heading into hardcore networking territory but I mention it because I've seen a problem recently where this came in handy. Let's say that someone says to you "I can't browse the intranet". Assuming that the intranets URL is http://intranet.internal.net, you can drop to the CMD prompt and try to ping intranet.internal.net. +- Screenshot ------------------------------------------------------------------ LOCAL C:\>ping intranet.internal.net Ping request could not find host intranet.internal.net. Please check the name and try again. +- End: Screenshot ------------------------------------------------------------- The reponse we got there looks like the name resolution failed. If you get a response and you know what the IP is, try to ping it instead (I'm assuming that as the support person you know what the IP is). If the IP pings but the hostname doesn't then you've definitely got a DNS related issue - whether it's a local or remote DNS issue is a different question. If the IP doesn't ping, ping the default gateway. If THAT doesn't come back you've probably got either a routing or physical connectivity issue. If you investigate and there is nothing wrong with the routing table or the physical network cable/NIC, check the arp table. You can do this by running ARP with the -a switch: +- Screenshot ------------------------------------------------------------------ LOCAL C:\>arp -a Interface: 10.0.0.100 on Interface 0x1000003 Internet Address Physical Address Type 10.0.0.1 01-23-45-67-89-AC dynamic 10.0.0.191 de-ad-00-00-be-ef dynamic +- End: Screenshot ------------------------------------------------------------- I have had several instances recently (on Windows 2003) where there was no entry in the arp table. Adding one with the -s option fixed the problem right up (I'm still investigating WHY this happens). | +- Vital Statistics: FILE : PING LOCATION : %SYSTEMROOT%\System32 NT4 : Base W2K : Base XP : Base W2K3: Base | FILE : TRACERT LOCATION : %SYSTEMROOT%\System32 NT4 : Base W2K : Base XP : Base W2K3: Base | FILE : ARP LOCATION : %SYSTEMROOT%\System32 NT4 : Base W2K : Base XP : Base W2K3: Base | +- End: PING / TRACERT / ARP --------------------------------------------------- +- NSLOOKUP / DIG ------------------------------------------------------------- | We touched upon DNS very briefly above and I want to mention two tools that make working with DNS a little easier. I should mention that these tools don't specifically hook into Active Directory which seems to be the way that Windows likes to run DNS these days. NSLOOKUP +- Screenshot ------------------------------------------------------------------ +- End: Screenshot ------------------------------------------------------------- += URLs ======================================================================== Dig for Windows http://pigtail.net/LRP/dig/ http://tinyurl.com/6vq8v += End: URLs =================================================================== | +- Vital Statistics: FILE : LOCATION : %SYSTEMROOT%\System32 NT4 : Base W2K : Base XP : Base W2K3: Base | +- End: NSLOOKUP / DIG -------------------------------------------------------- +- TELNET / NC / TCPDUMP ------------------------------------------------------- | While we're on the subject of networking, here are three tools that you can use to verify if you (the Sysadmin) have a problem or if the network/firewall guys are screwing you over. Tool number one: good old TELNET. Most people tend to pooh-pooh telnet because of it's evil cleartext ways but as a network troubleshooting tool it can be very handy. If you've got a service that provides a TCP service (ie a web server) then an enourmously simple way to verify that it's functioning is to "telnet" to that port. You can do this by telling TELNET the hostname/IP address to connect to and the port to connect to seperated by a space. For instance to check that the webserver on the local machine is listening you'd do this: TELNET 127.0.0.1 80. Don't forget to check locally as well as remotely, it's always embarassing to complain to the network guys only to find that it's your service that's not running. If you want to get a bit more hardcore then kick up a notch to tool number 2: NetCat. NetCat describes itself as "the TCP/IP swiss army knife" and it has some UDP functionality as well. A thorough overview of NC is well oustide of my scope here so I'll just demo how you'd do the same port 80 check with netcat: +- Screenshot ------------------------------------------------------------------ LOCAL C:\>nc -v 10.1.6.141 80 gblond001s84.twofifty.uk.eu.abnamro.com [10.1.6.141] 80 (http) open HTTP/1.1 400 Bad Request Server: Microsoft-IIS/5.0 Date: Wed, 08 Mar 2006 19:45:53 GMT Content-Type: text/html Content-Length: 87 ErrorThe parameter is incorrect. LOCAL C:\> +- End: Screenshot ------------------------------------------------------------- If you're trying to work out if you've got a firewall problem and you've got access to both ends of the connection, you can cut layer 7 problems out of the loop and set up netcat to listen on the server side (after shutting down the service so you can borrow the port) and then connect using TELNET or NC to verify that packets actually arrive. If you really need to know EXACTLY what's going on then wheel out tool number 3: TCPDUMP. TCPDUMP was born on UNIX but it has been ported over to Windows. There are two main implementations - WinDump which is open source and freely available and TCPDUMP from a company called MicroOLAP and has to be paid for. Why have I picked a commercial tool? Well, WinDump is nice but in order for it to work you first have to install the WinPcap driver which is a pain in the butt if you just want to us it once to troubleshoot a problem, especially if you can't reboot the server willy-nilly. TCPDUMP (from MicroOLAP) is a 300K file that requires NO other files, it just works which makes it well worth it for a portable toolkit. TCPDUMP is not going to be particularly useful to you if you don't understand how networks work at a reasonably low level but if you do have a basic understanding then you'll be able to say definitively what your problem is by letting fly with TCPDUMP. | +- Vital Statistics: FILE : TELNET.EXE LOCATION : %SYSTEMROOT%\System32 NT4 : Base W2K : Base XP : Base W2K3: Base | +- Vital Statistics: FILE : NC.EXE LOCATION : Wherever you put it NT4 : Third Party Tool W2K : Third Party Tool XP : Third Party Tool W2K3: Third Party Tool | +- Vital Statistics: FILE : TCPDUMP.EXE LOCATION : Wherever you put it NT4 : Third Party Tool W2K : Third Party Tool XP : Third Party Tool W2K3: Third Party Tool | += URLs ======================================================================== NetCat For Windows Homepage http://www.vulnwatch.org/netcat/ http://tinyurl.com/9qoee TCPDump For Windows http://www.microolap.com/products/network/tcpdump/ http://tinyurl.com/ol3f9 += End: URLs =================================================================== | +- End: TELNET / NC / TCPDUMP -------------------------------------------------- +- MSTSC / QWINSTA / RWINSTA --------------------------------------------------- | Still on the networking side of things, let's skip back to GUI oriented things for a while. I'm a bit shaky on the background here but I THINK that, starting with Windows 2000, all server class Operating Systems from Micorosft have had two user Terminal Services license built-in and Terminal Services is up and listening on port 3389. This allows you to bring up a virtual desktop using the Microsoft Terminal Services client. The terminal services client is part of a base OS install as of Windows XP (I've included the link to the Remote Desktop Connection Software for everything up to XP) and can be launched from the command line like this: MSTSC /v:REMOTE_SERVER From Windows 2003 on there is a really nice option built-in that allows you to access the actual console instead of just a terminal session by adding /CONSOLE to the command line. This will gracefully (but silently) degrade to a normal Terminal Services connection if it can't obtain the console. It is worth noting that the /CONSOLE switch can interfere with other remote console access utilities like CA Remote Control for instance. I mentioned that there are only two user licenses built-in, so what happens if there are already two people logged on? Terminal services won't let you in! How do you find out who's locking you out and get yourself back on (to do your vastly more important things)? Well, there are two two tools available to help investigate and remove this problem: QWINSTA (Query WINdows STAtion) and RWINSTA (Reset WINdows STAtion). QWINSTA run without any switches will check connections to the local server, with the /SERVER: switch it will go and check on the remote server: +- Screenshot ------------------------------------------------------------------ LOCAL C:\>qwinsta /server:REMOTE_SERVER SESSIONNAME USERNAME ID STATE TYPE DEVICE console 0 Conn wdcon rdp-tcp#11 someone_else 1 Active rdpwd kynan 2 Disc rdpwd +- End: Screenshot ------------------------------------------------------------- So you get a username and the current state of their connection. If the state is "Active" then they're currently logged on and doing something. If it's "Disc" then either they were disconnected by a network problem or their computer/software failed somehow or they have bailed out of the session without logging out. It's quite possible that they kicked off a job that can only run as a foreground task and they've left it to run so bear in mind that reseting the session may screw up something that someone else is running. To kick a user off and reset their session (forcing any open applications to close) use RWINSTA. the command line is almost identical to QWINSTA with the addition of the session name or ID that you wan't to reset. Note that you'll get NO output unless you use the /V switch, successful or not: +- Screenshot ------------------------------------------------------------------ LOCAL C:\>rwinsta 1 /V /server:REMOTE_SERVER Resetting session ID 1 Session ID 1 has been reset +- End: Screenshot ------------------------------------------------------------- Now there's a session open and ready for you to connect to. I'm not sure what the status of the QWINSTA and RWINSTA tools is. They appear on the install CD but I'm not sure what option you need to select to install them - I think they're a base OS install but I'm not 100% on that and I don't have a way to check at the moment. += URLs ======================================================================== Remote Desktop Connection Software http://www.microsoft.com/windowsxp/downloads/tools/rdclientdl.mspx http://tinyurl.com/2elke += End: URLs =================================================================== | +- Vital Statistics: FILE : MSTSC.EXE LOCATION : %SYSTEMROOT%\System32 NT4 : Microsoft Download W2K : Microsoft Download XP : Base W2K3: Base | FILE : QWINSTA.EXE LOCATION : %SYSTEMROOT%\System32 NT4 : Microsoft Download W2K : Base? XP : Base? W2K3: Base? | FILE : RWINSTA.EXE LOCATION : %SYSTEMROOT%\System32 NT4 : Microsoft Download W2K : Base? XP : Base? W2K3: Base? |+- End: MSTSC / QWINSTA / RWINSTA --------------------------------------------- +- NBTSTAT --------------------------------------------------------------------- | NBTSTAT is a utility that pulls back NetBIOS information that a computer registers for itself. NetBIOS is a very old protocol, NETwork Basic Input Output System. It is the primary means of communication for Windows NT 4 and has been retrofitted to all versions of Windows since then. It is well known for the security issues it contains (mostly because it was designed and implemented long before the internet became what it is today). A full description of NetBIOS is outside of the scope of this discussion (and frankly, I don't fully understand it myself) so I recommend further reseach for everyone, including me. Just because you don't understand exactly how something works doesn't mean you can't use it - damned if I could repair a catalytic converter (or point at one for that matter) but I can still drive around in car. What can NBTSTAT do for us? It can tell us what the computer wants everyone to know about itself and this can be some very handy information! NBTSTAT has a few switches, dealing with connections and name cache. The two we're really interested in are the -A or -a switch. The uppercase A switch requires that you know the IP address of the target machine, lowercase a will allow you to enter the hostname instead and the OS will try to resolve it: +- Screenshot ------------------------------------------------------------------ LOCAL C:\>nbtstat -A 10.0.0.191 Onboard: Node IpAddress: [10.0.0.100] Scope Id: [] NetBIOS Remote Machine Name Table Name Type Status --------------------------------------------- FILE_BOX <00> UNIQUE Registered WORK <00> GROUP Registered WORK <1C> GROUP Registered FILE_BOX <20> UNIQUE Registered WORK <1B> UNIQUE Registered WORK <1E> GROUP Registered WORK <1D> UNIQUE Registered ..__MSBROWSE__.<01> GROUP Registered MAC Address = DE-AD-00-00-BE-EF +- End: Screenshot ------------------------------------------------------------- What does this output tell us? Well, when you check with the Microsoft list of name suffixes (URL below) you'll know that: *) the name of 10.0.0.191 is FILE_BOX (the 00 UNIQUE entry) *) FILE_BOX is in the WORK domain (the 00 GROUP entry) *) FILE_BOX is a domain controller for the WORK domain *) FILE_BOX is sharing files (the 20 entry) *) FILE_BOX is the Domain Master Browser (1B), Master Browser (1D) and will take part in Browser Service Elections (1E). I mostly use this to verify that the hostname that I've obtained from DNS actually matches the IP address. += URLs ======================================================================== List of NETBIOS Name Suffixes http://support.microsoft.com/default.aspx?scid=kb;en-us;Q163409 http://tinyurl.com/qtrh5 += End: URLs =================================================================== | +- Vital Statistics: FILE : NBTSTAT.EXE LOCATION : %SYSTEMROOT%\System32 NT4 : Base W2K : Base XP : Base W2K3: Base | +- End: NBTSTAT ---------------------------------------------------------------- | That's about it, I've mentioned the occasional third-party tool here and there but there are two standout packages that need to be mentioned before we're done, CYGWIN and Sysinternals. | +- End: Third Party Packages Intro --------------------------------------------- +- CYGWIN ---------------------------------------------------------------------- | The Cygwin package provides a port of common (and not so common) GNU utilities from Unix over to Windows. Basically, a whole lot of functionality is built into a DLL called cygwin1.dll that emulates the normal Linux APIs. You can then compile your application to make use of this DLL and you'll have whatever you want from the Linux/Unix world running on Windows. Great news, yes? Well, mostly. There are two reasons that I haven't talked about the Cygwin tools before now: 1) I wanted to stick to tools that are nearly always available wherever you go in a Windows environment. Cygwin is definitely not in this category (although it should be) 2) I wanted to stick to tools that had no dependencies outside of the executable itself (well, no dependencies outside of Windows base DLLs anyway). The problem with the Cygwin tools is the emulation layer works through the main cygwin DLL (cygwin1.dll) and quite possibly a few others may be needed, depending on the tool in question. Let's look at gawk as an example. The gawk executable is only 278KB by itself, awesome if that's all you need - but there's a bigger picture. There is a very nice tool called Dependency Walker. This will show you all of the DLLs that an executable (or even another DLL) requires in order to run. If we set Dependency walker onto gawk we find that we need: *) cygwin1.dll which is 1.2MB *) cygintl-3.dll which is 55KB *) cygiconv-2.dll which is another 1MB So for a 250KB tool we need to cart around an extra 2 and a half Megabytes of DLLS! That doesn't mean that you shouldn't use them though. In fact I carry the following ones around on my USB key: cat.exe cut.exe echo.exe gawk-3.1.4.exe grep.exe head.exe od.exe sed.exe sort.exe tail.exe tr.exe uniq.exe Combined with these DLLs you've got a very handy little toolkit: cygiconv-2.dll cygintl-3.dll cygpcre-0.dll cygwin1.dll += URLs ======================================================================== Cygwin http://cygwin.com Dependency Walker http://www.dependencywalker.com/ += End: URLs =================================================================== | +- End: CYGWIN ----------------------------------------------------------------- +- Sysinternals ---------------------------------------------------------------- | There is one more class of tools that I want to discuss, those provided by the fine folks over at Sysinternals, and boy are they classy! The Sysinternals tools are written by Mark Russinovich and Bryce Cogswell. These guys have a phenomanal grasp of how the Windows Operating System works at a very low level (check out "Microsoft Windows Internals, Fourth Edition" if you want some really good info on how Windows really works under the purty GUI covers). The Sysinternals tools tend to be very small and very specialised. I am going to tell you about a few that I use EVERY day but first, a caveat: A lot of the utilities I'm about to mention make use of the ADMIN$ and IPC$ shares to work their magic remotely. If you're running hardened boxes then it's unlikely that you'll be able to make use of the functionality without copying the executables over. PsTools v2.31 The PsTools suite contains 13 tools, I'm going to mention 3: PSEXEC :- Allows you to execute processes remotely, basically by installing itself as a services for the duration of the connection. I use this ALL the time to effectively get a remote console: +- Screenshot ------------------------------------------------------------------ LOCAL C:\>psexec -u DOMAIN\kynan \\REMOTE_HOST CMD.EXE PsExec v1.70 - Execute processes remotely Copyright (C) 2001-2006 Mark Russinovich Sysinternals - www.sysinternals.com Password: Microsoft Windows 2000 [Version 5.00.2195] (C) Copyright 1985-2000 Microsoft Corp. C:\WINNT\system32>hostname REMOTE_HOST C:\WINNT\system32> +- End: Screenshot ------------------------------------------------------------- Notice that the prompt doesn't contain LOCAL anymore? That's why I do that. I spend a LOT of time logged on to remote machines like this. The command line is pretty simple and the help is more than adequate. Note that I didn't use the -p option to provide my password. If you do that it means you don't get prompted but it's VERY easy to check on the command line parameters of a running process so I don't use this. PSKILL :- Functions in a very similar way to the resource kit utility KILL. Basically you supply a PID or a process name and PSKILL will kill it. The advantage that PSKILL has over KILL is that, like PSEXEC, it can run on remote servers as well. Very handy for offing recalcitrant services. PSLIST :- A command line version of the Windows Task Manager, but better. Again, like all of the PS utilities it can run on a remote machine which is always a bonus. It can also display all the running processes in a tree format so that you can track down which process started another process very easily. It can run in "Task Manager" mode, refreshing every x seconds (you can specify x). It can supply all the same information as Task Manager with the exception of username but it can also supply information thread and memory usage. PSLOGLIST :- A command line window into the Event Log, although there is a Resource Kit utility, DUMPEL, PSLOGLIST has copious filtering options and an AWESOME "tail" functionality that puts it over the line as tool of choice! PSINFO :- A cut down version of SYSTEMINFO. Handy for checking out exactly what the basic specs of a remote machine are: +- Screenshot ------------------------------------------------------------------ LOCAL C:\>psinfo PsInfo v1.72 - Local and remote system information viewer Copyright (C) 2001-2005 Mark Russinovich Sysinternals - www.sysinternals.com System information for \\LOCALHOST: Uptime: 3 days 10 hours 6 minutes 15 seconds Kernel version: Microsoft Windows XP, Uniprocessor Free Product type: Professional Product version: 5.1 Service pack: 2 Kernel build number: 2600 Registered organization: xxx Registered owner: xxx Install date: 30/03/2005, 06:28:36 Activation status: Error reading status IE version: 6.0000 System root: C:\WINNT Processors: 1 Processor speed: 1.7 GHz Processor type: Intel(R) Pentium(R) M processor Physical memory: 766 MB Video driver: ATI MOBILITY RADEON +- End: Screenshot ------------------------------------------------------------- The PSTOOLS suite contains more utilities that come into their own when you actually start troubleshooting rather than just sysadmining: PsFile (shows files opened remotely), PsGetSid (display the SID of a computer or a user), PsLoggedOn (see who's logged on locally and via resource sharing), PsService (view and control services), PsShutdown (shuts down and optionally reboots a computer), PsSuspend (suspends processes), PsUptime (shows you how long a system has been running since its last reboot). There's one more Sysinternals utility that I want to mention, TCPVCON. TCPVCON provides the same functionality that NETSTAT -n does but since NETSTAT didn't get its -N option until XP - TCPVCON comes in very handy on Windows 2000 whilst tracking down the process that is listening on a particular network port. I can't recommend enough that you spend some time investigating the other tools that are available on the Sysinternals website, you're bound to find something you could have used to fix a problem you had! | += URLs ======================================================================== Sysinternals Website http://www.sysinternals.com/ Sysinternals Forums http://www.sysinternals.com/Forum/ += End: URLs =================================================================== | +- End: Sysinternals ----------------------------------------------------------- +- CMD REDUX ------------------------------------------------------------------- | Phew, nearly done. I want to mention one more thing. Now that you know all these cool new commands there's one more thing to know regarding how you can use them! Shell scripts are well ingrained in the UNIX world but in Windows it's a slightly different story - and not for the better unfortunately. Shells like ksh, zsh and bash offer some REALLY fancy scripting tools including multiple looping constructs and various conditional tests, combined with the plethora of small tools like cut, awk, sed and so on you can do some pretty comprehensive programing. Windows is starting to catch up now with the MONAD shell which looks like it is going to provide a lot of the same functionality as the UNIX shells plus it's going to hook into the OS pretty deep which will allow you to do some useful things, kind of like the ps tools except natively and via scripts. The MONAD Shell is certainly a step in the right direction but, like I said at the start of the show, I'm trying to provide solutions that will work with as little extra effort on all versions of NT. This is why I haven't mentioned the Windows Scripting Host (WSH) either. Instead, what I'm going to do now is talk about the programming constructs that are built-in to CMD. There are two constructs that the CMD shell offers: IF and FOR. Don't be disheartend though. These two constructs have been overloaded to hell and gone, especially FOR, so you can get a lot of things done but it really is VERY ugly! IF is easy because it's only got a couple of option: IF [NOT] ERRORLEVEL number command IF [NOT] string1==string2 command IF [NOT] EXIST filename command Errorlevels are notoriously hard to rely on because not all programs will set them. OK, let's look at FOR and some more let's say "abstract", uses for it. If you want to map a drive (using NET USE) in a script and you need to know what drive got used, how would you do that? Well, using FOR you can scan IN this example we'll map a drive normally, unmap it and map it again using the FOR construct to capture the drive letter in an environment variable: +- Screenshot ------------------------------------------------------------------ LOCAL C:\>net use * \\REMOTE_HOST\C$ Drive W: is now connected to \\gbas-00610\c$. The command completed successfully. LOCAL C:\>net use W: /delete W: was deleted successfully. LOCAL C:\>FOR /f "eol=T tokens=2 delims= " %G in ('net use * \\remotehost\C$') do (set NEW_DRIVE=%G) LOCAL C:\>(set NEW_DRIVE=W: ) LOCAL C:\TEMP\a>net use %NEW_DRIVE% /delete W: was deleted successfully. +- End: Screenshot ------------------------------------------------------------- What happened there? Well, CD /D Here's another example of putting everything together. This is a loop that renames all files in the current directory, replacing spaces with underscores and uppercase characters with their lowercase equivalents (with the help of some cygwin tools): +- Screenshot ------------------------------------------------------------------ LOCAL C:\>for %G in (*) do @( More? @for /f "tokens=*" %H in ('echo %G ^| tr '[ A-Z]' '[_a-z]' ^| sed 's/_$//') do move "%G" %H) LOCAL C:\>(for /F "tokens=*" %H in ('echo File Number One.txt | tr '[ A-Z]' '[_a-z]' | sed 's/_$//') do move "File Number One.txt" %H ) LOCAL C:\TEMP\a>move "File Number One.txt" file_number_one.txt +- End: Screenshot ------------------------------------------------------------- A couple of things to note: 1) the caret (^) is the DOS Command Shell escape character. See how the pipe (|) had to be escaped in the for loop? 2) So that's an += URLs ======================================================================== | A pretty informative spiel about the flaws in a lot of commands built-in to CMD.EXE including SETs complete ineptitude when it comes to maths! http://groups.google.co.uk/group/alt.msdos.batch.nt/browse_thread/thread/d5b0aa1 f4272929a/c728da35cd729c12?tvc=2#c728da35cd729c12 http://tinyurl.com/o5rwo | += End: URLs =================================================================== | +- End: CMD REDUX -------------------------------------------------------------- +- Windows Resource Kits ------------------------------------------------------- | I've been talking about all of these cool tools and now you really want to try them. So where can you get them? Well, the bad news is that you have to buy the Resource Kits. The good news is that a lot of the tools can be found actually on the Microsoft website or some other places on the net. I've collected the more useful ones here for you: Windows Server 2003 Resource Kit Tools http://www.microsoft.com/downloads/details.aspx?FamilyID=9d467a69-57ff-4ae7-96ee -b18c4790cffd&displaylang=en http://tinyurl.com/6p6cy Windows 2000 Resource Kit Book http://www.microsoft.com/resources/documentation/windows/2000/server/reskit/en-u s/default.asp All Resource Kits (NT, 2000, XP, 2003) http://www.dynawell.com/support/ResKit/ Windows NT 4.0 Resource Kit Support Tools http://www.microsoft.com/downloads/details.aspx?FamilyID=3e972e9a-e08a-49a2-9d3a -c0519479e85a&DisplayLang=en http://tinyurl.com/4emlh Random Resource Kit Tools and other useful Stuff http://www.petri.co.il/download_free_reskit_tools.htm http://tinyurl.com/o4hw | +- End: Windows Resource Kits -------------------------------------------------- +- TWAT Outro ------------------------------------------------------------------ | That's it! I hope there was something here that you didn't know or that helped you out somehow. Don't forget that there's heaps more cool stuff like this out there just waiting for you to find it. To start with, Microsoft include pretty thorough documentation for all the version of Windows that I covered here (well, the NT coverage is a bit skimpy) and if you start looking around then you'll never run out of new ways to do things! Have fun. kynan += URLs ======================================================================== Windows NT 4 Executable Reference http://www.microsoft.com/technet/archive/winntas/deploy/prodspecs/shellscr.mspx http://www.windowsitlibrary.com/Content/405/29/files/tablea_1.html Windows 2000 Command Line Reference http://www.microsoft.com/windows2000/en/server/help/default.asp?url=/windows2000 /en/server/help/ntcmds.htm http://tinyurl.com/kmy Windows XP Command Line Reference http://www.microsoft.com/resources/documentation/windows/xp/all/proddocs/en-us/n tcmds.mspx http://tinyurl.com/36leu Windows 2003 Command Line Reference http://technet2.microsoft.com/WindowsServer/en/Library/552ed70a-208d-48c4-8da8-2 e27b530eac71033.mspx http://tinyurl.com/qaer3 += End: URLs =================================================================== | +- End: TWAT Outro ------------------------------------------------------------- MMC /COMPUTER=x ================================================================================ Commands to cover custcon uptime dumpel kill tlist wmic GUI services.msc eventmgr.msc compmgmt.msc +------------------------------------------------------------ | MONAD If you're interested in checking out MONAD you can download it here: http://tinyurl.com/9u7fm http://www.microsoft.com/downloads/details.aspx?FamilyID=e8e5203a-574c-4105-af6b -b2fef39adf55&DisplayLang=en You will need to register, alternatively you can use bugmenot.com: http://tinyurl.com/dlxys The Monad Documentation can be found here: http://tinyurl.com/bku5h http://www.microsoft.com/downloads/details.aspx?familyid=6387C46B-4753-4EAF-8D8B -368074F39CCC&displaylang=en| +------------------------------------------------------------ +- Screenshot ------------------------------------------------------------------ +- End: Screenshot ------------------------------------------------------------- += URLs ======================================================================== += End: URLs ===================================================================