Showing posts with label redhat. Show all posts
Showing posts with label redhat. Show all posts

Tuesday, May 26, 2009

Controlling Group Access To Directories Recursively And Automatically Using Simple FACL's On Linux

Hey there,

Today we're going to take a look at using simple FACL's (file access control lists) to allow additional access restrictions (for one or more groups other than the directory owner's group) to a directory, while ensuring that the change propagates automatically to all subdirectories and files within all or any. Our examples for today should work on most distro's of Linux (and most proprietary Unix distro's), although the actual commands needed may be different ("man getfacl" or "man setfacl" should sort you out). For today's examples, all commands were run on RedHat Enterprise Server 5.2 (Tikanga - A Mãori word idiomatically meaning "The Mãori Way" or, more sanctimoniously, "correct," "right" or "true" - all absolutes ;)

The situation for today's example is pretty simple, although highly useful (of course, those aren't necessarily opposites ;). You have a directory that is owned by the user "user1" and the group "group1." A user name "user2", in the group "group2" needs to have access to your directory and also needs to be able to add new directories and/or files within that directory. To top it off, when either "user1" or "user2" creates a file or directory within the directory to be shared, that directory and/or file must be accessible to both "user1" and "user2" and owned by the group "group1." Simple enough :)

Of course, the easiest way to do this would be to add "user2" to "group1" and be done with it. However, since that might possibly afford "user2" more privilege than is actually needed (he/she may be able to access other files/directories that are owned by "group1"), a more restrictive solution is required. This is where simple FACL's come into play.

First, we'll take a quick look at the directory in question, with ls -l:

host # ls -ld shared_dir
drwxrwx--- 2 user1 group1 512 May 25 13:24 shared_dir


Once we're done, it will look almost exactly the same, except for the "+" symbol at the end of the alpha permissions display (This is an additional field, as opposed to setuid, setgid and sticky bit which replace the final alpha permissions field with a substitute character) As a point of note; some distributions include the "+" symbol at the end of "every" file, since all files/directories (on a filesystem that supports FACL's) have a default FACL. This seem counter-intuitive to me, since it makes it harder to eyeball which files/directories you've mucked with on purpose ;)

host # ls -ld shared_dir
drwxrwx---+ 2 user1 group1 512 May 25 13:24 shared_dir


Now, in order to make the whole concept of FACL's more accessible, it should be noted (at least, these days) that "all" files have FACL's (see slight caveat above), even if you don't explicitly set them. These FACL's mirror the existing file/directory permissions by default and you'll only the see the "+" symbol on files/directories where the default FACL has been modified (which is what we're going to do).

For instance, the FACL for our original shared_dir, looks like this before we even do anything, and can be obtained with the "getfacl" command (consider owner: user1, group:group1 and permissions of 770 - or drwxrwx---):

host # getfacl shared_dir
# file: shared_dir
# owner: user1
# group: group1

user::rwx
group::rwx
mask::rwx
other::---


All pound (#) comments are not acted upon, just like in most scripting languages. You can remove them, but they'll get automatically recreated every time you run a FACL command.

So, for this directory, we want to allow the group "group2" recursive read, write and execute permissions (read permissions, so they can see the contents of the directory or read any files in it, write permissions, so they can create new files/directories within the directory and/or write to files in it, and execute permissions, so that they can cd into the directory and/or execute files within it)

Luckily for us, this is actually fairly simple. All we need to do is to make use of the "setfacl" command.

host # setfacl -m g:group2:rwx shared_dir


This will change the FACL settings for the shared_dir directory, but won't do "exactly" what we want:

host # getfacl shared_dir
# file: shared_dir
# owner: user1
# group: group1

user::rwx
group::rwx
group:group2:rwx
mask::rwx
other::---


While doing this will allow "group2" read, write and execute access to the directory "shared_dir", the extended access will begin and end with the "shared_dir" directory, and any files/directories created by any user in "group2" will still be owned by "group2" when they are written to this directory.

If we want to satisfy the one remaining requirement (allowing "group2" to create new files/directories within "shared_dir" and have them all belong to "group1", with the unique FACL applied to each and every one), we need to set "default FACL's". Again, this is very simply done, and very easy to manage using the setfacl command Our first command will be to remove the rule we added with our last command. Then we'll set default FACL's for everyone and for the specific users and groups:

host # setfacl -x g:group2:rwx shared_dir
host # setfacl -d -m u:user1:rwx shared_dir
host # setfacl -d -m g:group1:rwx shared_dir
host # setfacl -d -m u:user2:rwx shared_dir
host # setfacl -d -m g:group2:rwx shared_dir


If you use the form above (which is, admittedly, more strict than it needs be; but I'm a control freak ;) and don't see the extra "default" FACL entries for the default user and group that own the file/directory, you can set those like this (also using setfacl):

host # setfacl -m d:u:rwx shared_dir
host # setfacl -m d:g:rwx shared_dir
host # setfacl -m d:o:--- shared_dir


These three entries should be put into your new FACL for the shared_dir by default, when you type the highly-specific FACL commands above, but if they're not, you'll want to add them. They are the key to propagating correct permissions on all new files/directories created within that directory.

Now typing "getfacl" should show you a dramatically different output:

host # getfacl shared_dir
# file: shared_dir
# owner: user1
# group: group1

user::rwx
group::rwx
mask::rwx
other::---
default:user::rwx
default:user:user1:rwx
default:user:user2:rwx
default:group::rwx
default:group:group1:rwx
default:group:group2:rwx
default:mask::rwx
default:other::---


As I mentioned, you could leave out all the commands pertaining to the original owner (and group) of the file, but I like to be as specific as possible, just in case. Now, any file/directory that either user1, user2, or members of group1 or group2 create in this directory will have 770 permissions (rwxrwx---+) and their group will be set to "group1." You can also easily tell that your settings have worked by looking for the "+" symbol at the end of newly created files, which indicates that the FACL has been applied to your new file (although with a slightly different output for files than for directories):

host # who am i
user2
host # touch shared_dir/test
host # ls -l shared_dir
total 0
drwxrwx---+ 2 user2 group1 96 May 1 14:01 test

host # getfacl shared_dir/test
# file: test
# owner: user2
# group: group1

user::rw-
user:user1:rwx
user:user2:rwx
group::rwx
group:group1:rwx
group:group2:rwx
mask::rwx
other::---


And that's that :) If you still don't get the group propagation that you're expecting, it may not be supported on your OS. In that case, you can add this additional command (on top of the FACL's) to ensure that the correct group "sticks":

host # chmod g+s shared_dir


And you should be all set :)

Cheers,

, Mike




Discover the Free Ebook that shows you how to make 100% commissions on ClickBank!



Please note that this blog accepts comments via email only. See our Mission And Policy Statement for further details.

Tuesday, May 5, 2009

Wtmpx Log Rolling On Unix or Linux: Practical Application Of Fwtmp

Hey There,

In yesterday's post on getting the year from wtmpx, we took a look at a great built-in program called fwtmp (that I somehow managed to not notice for several years ;) and examined some uses of it from a high level perspective.

Today we're going to look it from an opposite angle and look at something very specific that it can help you do. And, just to dot the i's that I can (and this list is, of course, incomplete), you can find fwtmp in /usr/lib/acct on Solaris and in /usr/sbin/acct on RedHat Linux (AS 5.2) and on SUSE Linux 9. Of course, all of the operating systems require you to have the correct pkg/rpm/dpkg files installed in order for the command to exist on your system at all :)

Below is a really simple shell script to illustrate the functionality of fwtmp. It's basically a log rotation script written specifically to highlight the use of fwtmp to rotate your wtmpx/wtmp/btmp file. It's meant to be run in cron and is simple to execute since (as it stands) it takes no arguments. Feel free to embellish for your own environment or to make it more accessible across a wide variety of different OS's. The basic cron entry I would add would be something like:

58 23 * * * /usr/local/bin/wtmp_rotate >/dev/null 2>&1


which basically just tells the cron daemon to run /usr/local/bin/wtmp_rotate (the place I like to put all my custom scripts) at 11:58pm every day and to dump any output from the command into the bit-bucket (redirecting both STDOUT and STDERR to /dev/null)

Hope this script helps you out some. You may want to test it by making a temporary directory and copying your wtmpx file into there first. I've included some commented lines to indicate the parts of the script you'd want to modify to ensure that your testing "doesn't" use the real system file.

And to answer the question of why I compress the files after converting them back to binary; I found, in my testing, that the opposite of what seemed logical was true. The binary files compacted to a much greater degree than the fwtmp-generated ASCII files. I didn't investigate it much further since it is what it is, but, if I had to throw out a possible reason it may be that fwtmp pads that ASCII file with a lot of extra bits that can't be stripped (That brush-off has middle-management written all over it ;)

Enjoy and cheers :)


Creative Commons License


This work is licensed under a
Creative Commons Attribution-Noncommercial-Share Alike 3.0 United States License

#!/bin/bash

#
# wtmpx_rotate - rotate your user login logs... wheee :)
#
# 2009 - Mike Golvach - eggi@comcast.net
#
# Creative Commons Attribution-Noncommercial-Share Alike 3.0 United States License
#

# COMMENTED OUT SECTIONS SHOULD BE SWAPPED WITH THEIR UNCOMMENTED COUNTERPARTS TO DO LOCAL-DIRECTORY TESTING WITH A COPY OF WTMPX
# THESE SWAPPABLE SECTIONS WILL BE SEPARATED FROM LIKE PARTS OF THE SCRIPT BY A SINGLE BLANK LINE

if [[ ! -d /var/adm/backup_log_dir ]]
then
mkdir /var/adm/backup_log_dir
fi


#if [[ ! -d backup_log_dir ]]
#then
# mkdir backup_log_dir
#fi


wtmpx="/var/adm/wtmpx" # This may be /var/log/wtmpx or /var/log/lastlog depending on your setup
#wtmpx="wtmpx"


fwtmp="/usr/lib/acct/fwtmp" # This may be /usr/sbin/fwtmp depending on your setup. Not using "which" since /usr/lib/acct isn't a standard directory.
sed=`which sed`
rm=`which rm`
compress=`which compress` # Or gzip, bzip2, whatever you prefer

grep_date=$(date "+%a %b %e")
grep_date_ext=$(date "+%a %b %e"|$sed 's/ //g')
grep_year=$(date +%Y)
variable_ext1=$(echo ${RANDOM}`date "+%S"`)
variable_ext2=$(echo ${RANDOM}`date "+%S"`)
variable_ext3=$(echo ${RANDOM}`date "+%S"`)
wtmpx_plus_variable_ext1=${wtmpx}.$variable_ext1
wtmpx_plus_variable_ext2=${wtmpx}.$variable_ext2
wtmpx_plus_variable_ext3=${wtmpx}.$variable_ext3
backup_log_dir_file=${wtmpx}.${grep_date_ext}.$grep_year


backup_log_dir_dir="/var/adm/backup_log_dir"
#backup_log_dir_dir="backup_log_dir"


$fwtmp < $wtmpx > $wtmpx_plus_variable_ext1

$sed -n "/$grep_date.*$grep_year$/p" $wtmpx_plus_variable_ext1 > $wtmpx_plus_variable_ext2
$sed "/$grep_date.*$grep_year$/d" $wtmpx_plus_variable_ext1 > $wtmpx_plus_variable_ext3

$rm $wtmpx $wtmpx_plus_variable_ext1

$fwtmp -ic < $wtmpx_plus_variable_ext2 > $wtmpx
$fwtmp -ic < $wtmpx_plus_variable_ext3 > $backup_log_dir_file

$rm $wtmpx_plus_variable_ext2 $wtmpx_plus_variable_ext3
$compress $backup_log_dir_file
mv ${backup_log_dir_file}.Z $backup_log_dir_dir


, Mike




Discover the Free Ebook that shows you how to make 100% commissions on ClickBank!



Please note that this blog accepts comments via email only. See our Mission And Policy Statement for further details.

Friday, April 24, 2009

Linux Distribution Logos - An Interesting Collection

Happy Friday to everyone,

If you haven't left work yet (assuming you made the double mistake of waking up "and" coming in ;), here's hoping you can get out the door fast. I don't know what the weather's like in your area, but it's going to be nice and balmy around here for the next few days, after which it will, once again, be freezing cold and snowy (I love Chicago :)

I came upon this random collection of Linux logos on Tech Source From Bohol and thought it would be interesting to share. Most of these are just visually interesting. Some of them (like the logo for "Blag" Linux, which I didn't know existed and am dying to try out - yes, just because of the name ;) are a bit amusing. You be the judge. No one should have me as the arbiter of their taste ;) I've only included 20 of them because my bones are brittle and ...I just couldn't stand the copy and paste any more! ;)

Enjoy your weekend and enjoy the logos. Also, stop by Tech Source From Bohol and check out the rest of the 50-logo set, plus all of the other interesting articles and showcases they have over there :)

Cheers,







, Mike




Discover the Free Ebook that shows you how to make 100% commissions on ClickBank!



Please note that this blog accepts comments via email only. See our Mission And Policy Statement for further details.

Thursday, November 13, 2008

Getting CPU Information From Various Flavours Of Linux And Unix

Hey there,

Today, in keeping with yesterday's theme of covering a fairly specific topic and trolling it around the seamy underbelly of the world of Unix and Linux, we're going to take a look at how to grab CPU information from your Unix or Linux box. I try to cover the major distros here, but (of course) my resources are limited and (except for the HP-UX example below) I've personally run and verified all of the results of the commands put out in this post today. If you crave additional information about your particular Operating System and the CPU(s) on it, check out some of our earlier posts on CPU usage, monitoring, etc, for all sorts of Unix/Linux varieties. Hopefully, you'll find some useful information in the growing archives of this sprawling morass of letters and numbers (by which I, of course, mean this blog ;)

On to today's business! For each OS, we'll be listing the OS name, followed by a practical line of code that you should, hopefully, be able to cut-and-paste onto your own system to get your specific information. Also, for each, we'll list the actual output that my trials produced, except for the HP-UX exception already noted.

1. Listing out CPU information on Solaris (Note that these "virtual" CPU's are actually real):

host # psrinfo -v| awk 'BEGIN{cpua=0;cpub=0}{if ( $0 ~ /Status.*processor/ ) {print $0;cpua=1} else if ( cpua == 1 ) {printf"%s ", $1;cpua=0;cpub=1} else if ( cpub == 1 ) {penult=NF-1;print $penult,$NF;cpub=0}}'|sed 's/,$//'
Status of virtual processor 0 as of: 11/12/2008 13:53:47
on-line 650 MHz
Status of virtual processor 1 as of: 11/12/2008 13:53:47
on-line 650 MHz


2. Listing out CPU information on SUSE and/or RedHat Linux:

host # cat /proc/cpuinfo|egrep 'processor|model name'|awk -F":" 'BEGIN{i=0}{if ( ! i%2 ) {printf"%s %d: ", $1,$2;i++} else {print $2;i=0}}'

processor 0: Intel(R) Xeon(TM) CPU 3.40GHz
processor 1: Intel(R) Xeon(TM) CPU 3.40GHz
processor 2: Intel(R) Xeon(TM) CPU 3.40GHz
processor 3: Intel(R) Xeon(TM) CPU 3.40GHz


3. Listing out CPU information on AIX 5.x:

host /# pmcycles -m
CPU 0 runs at 1200 MHz
CPU 1 runs at 1200 MHz
CPU 2 runs at 1200 MHz
CPU 3 runs at 1200 MHz
CPU 4 runs at 1200 MHz
CPU 5 runs at 1200 MHz
CPU 6 runs at 1200 MHz
CPU 7 runs at 1200 MHz


4. Listing out CPU information on HP-UX (as generally as possible). This bit of code is sewn together from exemplary commands on SysDigg's HP-UX CPU Info Page, since I can't get my hands on an HP-UX box right now, and the information gathering process is more convoluted than any of the preceding distro's (We're not even going to begin to talk about the new Itanium processors and/or differentiate between virtual and physical CPU's/Cores, etc. This is for a HP9000/800 model box):

host # pc=`ioscan -k |grep processor |wc –l `
host # pt=$(grep -i $(model |tr "/" " " \|awk '{print $NF}') \/usr/sam/lib/mo/sched.models |awk '{print $NF}')
host # ps=`echo "itick_per_usec/D" | adb /stand/vmunix /dev/mem | tail -1`
host # echo "Processor count: $pc - CPU Type: $pt - Speed: ${ps}Mhz"
Processor count: 2 - CPU Type: PA8700 - Speed: 750Mhz


Phew... Hopefully, the HP-UX information is correct (if not, please write in as I'd be glad to credit anyone with the correct answer if they can get to an HP-UX machine before I can :)

And, that's that. Quick and painless today ;) I promise to chew your virtual ear off tomorrow as I rant and rage for no apparent reason other than to possibly foment passive-aggressive revolution amongst the working class. Actually, whatever I have to write about tomorrow probably won't be "that" moving ;)

Cheers,

, Mike




Please note that this blog accepts comments via email only. See our Mission And Policy Statement for further details.

Friday, October 10, 2008

How To Set Up A Headless X Server On Redhat Linux

Hey there,

Today we're going to throw out another Linux tip somewhat related to networking. Or, more correctly, we're going to throw another quick tip out there ;) Today we're going to look at setting up a headless X Server. It's not quite as difficult, or as scary, as it sounds. Running a headless X Server is kind of like Night Of The Living Dead (the original; although the remake was kind of fun) except without all the zombies and with exported displays instead of excoriated remains (best I could do in the almost-rhyming department on that one ;)

If you stick to the following steps (Tested on RedHat Enterprise Linux Update 4) and adjust slightly if your distro is either completely different, your system architecture varies or your RedHat release is just a version or so off, you should be up and running in no time.

1. Make sure that you install all of the following rpm's on the machine on which you want to run the headless X Server (ignore errors that state you already have any of the packages installed. If you run into dependency conflicts, run rpm with the --nodeps option. If you need to update any of the files, run rpm with the --update option. You may need to install these one by one, but you might get lucky and just be able to run rpm -ivh in a loop and have them all install the first time. You can also get around dependency issues by installing all of the rpm's on one line - i.e. rpm -ivh rpm1.rpm rpm2.rpm ... rpmN.rpm):

XFree-libs-data-4.3.0-78.EL.i386.rpm
XFree-xfs-4.3.0-78.EL.i386.rpm
XFree-libs-4.3.0-78.EL.i386.rpm
XFree86-xauth-4.3.0-35.EL.i386.rpm
XFree86-base-fonts-4.3.0-35.EL.i386.rpm
XFree86-4.3.0-78.EL.i386.rpm
cpp-3.2.3-47.i386.rpm
xinitrc-3.32-1.noarch.rpm
switchdesk-3.98.17.i386.rpm
desktop-file-utils-0.3-10.i386.rpm
XFree86-Xvfb-4.3.0-78.EL.i386.rpm
XFree86-ISO8859-14-100dpi-fonts-4.3.0-97.i386.rpm


2. Start up X's virtual frame buffer server like so:

Xvfb :0 –pn –nolisten tcp –audit 4 –screen 0 800x600x16 & <-- The 800x600 is the screen resolution and the x16 (16 bit)is the color depth. You can change these settings to suit your taste or satisfy any limitations your graphics driver might impose).

NOTE: If you have problems with the X Server going offline when you logoff, try running it with nohup and/or check out our previous post on what to do when nohup hangs up anyway!

And, how about that? I think this is, blessedly, the shortest post I've ever written :) Just pretend there are a couple more paragraphs of "ipsum lorem dolor sit amet" if you find yourself suffering from information underload ;)

Cheers,

, Mike




Please note that this blog accepts comments via email only. See our Mission And Policy Statement for further details.

Thursday, October 2, 2008

Linux Vs. Unix: The Sins Of The Father?

Hey There,

If you're a regular reader ( or even a slightly irregular reader ) of this blog, you may have noted that from time to time I'll, tongue in cheek, make reference to, one day, eventually writing a post that basically says nothing, goes nowhere and ends flat, leaving you feeling like you bought another pet rock. For some reason, there is overwhelming interest in my actually going through with this and making a complete mockery of my blog (although I've felt, at some times, that I was achieving that end quite admirably ;) by writing just such a post. Since I pride myself, somewhat, in doing what I say I'm going to do (no matter how stupid or harmful ;) today has become the day that I put digits to keyboard and hammer out that post.

PLEASE NOTE: I'm not kidding. While this post may be somewhat amusing, you will probably walk away, after reading it, realizing only that you'll never ever get that time back. Without further ado, fanfare and/or circumstantial pomp, here comes that post. Please Stop Reading Now if you don't want to read a few paragraphs that will ultimately pose no problem, resolve nothing and leave without paying the check. You've been notified. This post is meaningless. It will also be written without emoticons from this point on. The whole thing's a joke. I just can't type that many winks in one post. The last time I attempted to, my keyboard got conjunctivitis and I had to have it deloused at the Rustler Steak House down the street from my Pet Psychic's favorite Organic Food outlet.

Unix and Linux are two keywords I like to use a lot in post bodies, and post titles, for this blog. It goes mainly to the fact that this blog is about lots of things Unix and Linux related. And, since it's next to impossible to do good SEO with a blog where the content on the front page changes entirely every day, falling back on those two words (and a few choice other ones) helps keep this cyber-rag in Google's goggles. You may have noticed that I used them in my title today and have, thus far, used the words Linux and Unix a total of 6 times (3 each) within a relatively brief chunk of text. I have no sense of direction and also can't calculate keyword density on the fly, but, if my offhand calculations are correct, I'd say we're looking at about a 100% saturation level, at the very most.

I'm a huge fan of Solaris and RedHat, which makes it hard for me to talk to plants, even though my wife insists that they're listening and I may actually be helping them grow. Still, when it comes down to a choice between using either Linux or Unix to complete a particular task, I tend to lean toward the wall in the office with the most stable furniture. I've been studying Feng Shui for some time now, and I can honestly tell you that nothing is where it's supposed to be. One of the underlying principles of that ancient practice (or is it just the only philosophy that involves heavy lifting?) is the assertion that where you put things can have a dramatic impact on your quality of life. For instance, if you stick a fork in your eye, you will be blind, bleeding, in severe pain and making a mess of your living area in no time. Luckily, the color red attracts good energy. The kind that will help you muster up the strength to either pull that fork back out of your eye or, at the very least, put your @ss in a car that (depending upon the severity of your wound) is either going to end up in the emergency room parking lot or wrapped around a tree on your neighbors lawn. If you release enough good energy, you may even attract the attention of strangers who will call 911 as soon as they've run out of video tape.

Fortunately, the solution to every problem is almost as simple as the problem itself. All you need to do is follow these 3 simple steps, and you'll be able to troubleshoot any Linux or Unix problem that comes your way. This is a tried-and-true method that is virtually 100% guaranteed...

1. Be sure that you understand the language in which the problem is being described to you. More pointless meetings have been adjourned due to poor communication than for any other reason. Understanding is key when you're dealing with someone who is completely paralyzed by irrational fear. If, after exhausting all options, you find that you still cannot make any headway, pretend to understand. Nodding, squeezing of the chin between thumb and forefinger and vague (yet distant) rolling of the eyes, coupled with comforting sounds like mmm-hmmm, can go a long way toward getting you to step 2 as quickly as possible.

2. Email the only supervisor you have who, for some reason, refuses to answer direct questions via any recordable medium. While he (or she) can be extremely irritating under most circumstances, you have an ally in this management-type who will provide you with absolutely bullet-proof @ss-cover if anyone ever comes around asking questions. Just be sure you send the original email and keep multiple copies (at multiple locations) of the response requesting that you get together to discuss the issue in person at an off-site location.

3. Using the information you've barely gleaned, and the brush off you've cleanly pocketed, during the execution of steps 1 and 2, manufacture an incident that trumps both with respect to both immediacy and length-of-engagement. If you have to get to work on something "mission-critical" right away and you might be going at it for days, without sleep, so that your company can hang on to some hope of staunching the flow of imaginary life-blood-cash, your problem should be reassigned soon enough.

IMPORTANT NOTE REGARDING STEP 3: Be sure that your "emergency" requires you to be off-site (i.e. out of the office and, preferably, out of the data center. Shoot for a non-extradition country, if possible) in order to fix it. Maintain communication only via pay-phone. Never turn on your computer or your cell phone. Be sure that everyone understands that they "are" talking to you on your company cell's speaker-phone (even though they aren't) and use a public terminal at the library to occasionally bounce a mail through a VPN connected to your organization's backup network. Make sure you manually edit the headers just enough to make them confusing to a human and completely sensible to a mail agent. If you maintain frequency-silence by leaving your cell phone and computer off, you can avoid suspicion to a better degree. Even the more paranoid among your masters will be somewhat comforted by the fact that all the systems are bad "and" the GPS devices they've weighed you down with aren't indicating where in the world you are. If you own a car, take a bus. You probably have Tom-Tom in there or some form of LoJack. If at all possible, find a place in the mountains (near a National Park or Wildlife Preserve) to do your heavy troubleshooting, live off of berries and kill your own food. If you're reasonably intelligent, after a week or so, you'll never want to come back.

That being said, given Solaris' and RedHat's solid track records, I think you'll find that, utilizing a proper steam-powered vacuum cleaner, you can make almost any stain look worse. If you do nothing else for the rest of your life, constantly berate yourself for buying white carpets. And don't go easy on your self. Be really mean. You deserve every moment of the grief you're going to endure. What were you thinking? That'll teach you to use Linux, when Unix is a perfectly acceptable alternative OS that is also entirely biodegradable, so you can feel superior while you're busy raping and pillaging the environment in some other way.

It goes without saying that...

, Mike




Please note that this blog accepts comments via email only. See our Mission And Policy Statement for further details.

Wednesday, October 1, 2008

How To Easily Find The WWN's Of A QLogic HBA On RedHat Linux

Hey there,

Today's post should be nice and simple. Maybe even short... yeah ;) This is a bit of a follow-up on a post we did a long long time ago regarding Linux networking tips. It's quite a bit more specific, but remains true to the spirit of that post (from December 2007, which, still, seems like it was just last year ;)

Today, we're going to take a look at a really simple way to figure out the World Wide Name (WWN) of both your Fibre NIC's port(s) and the switch it's connected to. To add a bit of clarity here, a lot of times you'll hear a QLogic (which is what we have on the menu today) Fibre NIC referred to as an HBA (Host Bus Adapter). It's become common to interchange the meaning of the two, although, technically, the HBA is an I/O adapter that resides "between" the computer's Bus (A collection of wires that data gets transmitted through. Not a clever acronym as far as I know ;) and the Fibre Channel Loop, and deals with the overhead associated with the transfer of information between the two. This becomes even more confusing when you consider that some Fibre NIC cards either have an HBA on board or act in the capacity of an HBA. But, in the end, you have to ask yourself just one question: If you can fix one a' them doohickies when it breaks, who cares? ;)

Anyway, back to the topic of the day: Finding the port and switch WWN's for a QLogic Fibre NIC on RedHat Linux. The version we're testing on today is:

hostess # cat /etc/issue
Red Hat Enterprise Linux ES release 4 (Nahant Update 6)
Kernel \r on an \m

hostess # uname -a
Linux hostess1 2.6.9-67.0.1.ELsmp #1 SMP Fri Nov 30 11:51:05 EST 2007 i686 i686 i386 GNU/Linux


The setup on our machine is a very simple QLogic Fibre Channel Card (which comes with it's own on-board HBA), referred to by the operating system as qla2xxx (This translates to another meta-name in /etc/modprobe.conf, but since that name is an alias for this name, we'll use this one instead.). In order to find out the WWN's for this card, all we need to do is follow this simple process:

1. Find the instance of the card's name in the /proc filesystem:

host # find /proc -type d -name qla2xxx
/proc/scsi/qla2xxx
<-- Note that we referenced a directory here. Normally, you wouldn't know this, but we did, so it made the search go faster by .001 seconds (according to the "time" command which is notorious for being off by a few thousandths of a second every now and again ;)

2. cd into the qla2xxx directory and do an "ls -l" and a "file" on "*" (not really necessary, but fun :)

hostess # ls -l *
-rw-r--r-- 1 root root 0 Sep 30 12:25 1
-rw-r--r-- 1 root root 0 Sep 30 12:25 2
-rw-r--r-- 1 root root 0 Sep 30 12:25 3
-rw-r--r-- 1 root root 0 Sep 30 12:25 4
hostess # file *
1: empty
2: empty
3: empty
4: empty


3. Now, you've probably noticed that the file sizes are all 0 and the output of the file command says "empty" for all of them. This is an illusion the /proc filesystem plays. You can prove this (the long way) by copying any file into, say, /tmp and running the same commands again:

hostess # cp 1 /tmp/DELETEME
hostess # ls -l /tmp/DELETEME
-rw-r--r-- 1 root root 1033 Sep 30 12:27 /tmp/DELETEME
hostess # file /tmp/DELETEME
/tmp/DELETEME: ASCII English text


...it's interesting to note, also, that running the "stat" command doesn't even get you the correct information within the /proc filesystem. The results are the same as above: The file's empty if it's in /proc, but has mass when it's copied or moved out.

4. Now we can get our info. This egrep command pulls out all the salient information. There's a lot more output in each file and, depending upon your interests (or how bored you are right now ;), you might find a lot of it very helpful in a troubleshooting or performance-evaluation situation. First the command, then the explanation:

hostess # egrep 'QLogic|scsi-' *
1:QLogic PCI to Fibre Channel Host Adapter for QLA2342:
1:scsi-qla0-adapter-node=200000e08b12f98d;
1:scsi-qla0-adapter-port=210000e08b12f98d;
2:QLogic PCI to Fibre Channel Host Adapter for QLA2342:
2:scsi-qla1-adapter-node=200100e08b32f98d;
2:scsi-qla1-adapter-port=210100e08b32f98d;
2:scsi-qla1-target-0=50060e80039cab0a;
2:scsi-qla1-port-0=50060e80039cab0a:50060e80039cab0a:612c13:81;
3:QLogic PCI to Fibre Channel Host Adapter for QLA2342:
3:scsi-qla2-adapter-node=200000e08b18e575;
3:scsi-qla2-adapter-port=210000e08b18e575;
3:scsi-qla2-target-0=50060e80039cab1a;
3:scsi-qla2-port-0=50060e80039cab1a:50060e80039cab1a:612c13:81;
4:QLogic PCI to Fibre Channel Host Adapter for QLA2342:
4:scsi-qla3-adapter-node=200100e08b38e575;
4:scsi-qla3-adapter-port=210100e08b38e575;


The things to notice above, are that only two of the targets have the "scsi-qlaX-adapter-target" value set. This is because the "QLA2342" (qla2xxx's actual name, shown in the output) only has 2 ports (despite the four descriptors). You can actually read up more on the technical specs at QLogic's Official QLA2342 Spec Page. Notice that even "they" refer to the QLA2342 as an HBA, rather than a Fibre Channel NIC...

5. And, now, here's the information you're ultimately looking for. To find the WWN for each of the two "ports," check the egrep results for the files that came back with the word "target" in them. All four use the "port" keyword. You can grab this more succinctly off of the command line with:

hostess # grep -l "target-" *|xargs egrep -i 'QLogic|scsi' /dev/null
2:QLogic PCI to Fibre Channel Host Adapter for QLA2342:
2:Number of reqs in pending_q= 0, retry_q= 0, done_q= 0, scsi_retry_q= 0
2:SCSI Device Information:
2:scsi-qla1-adapter-node=200100e08b32f98d;
2:scsi-qla1-adapter-port=210100e08b32f98d;
2:scsi-qla1-target-0=50060e80039cab0a;
2:scsi-qla1-port-0=50060e80039cab0a:50060e80039cab0a:612c13:81;
2:SCSI LUN Information:
3:QLogic PCI to Fibre Channel Host Adapter for QLA2342:
3:Number of reqs in pending_q= 0, retry_q= 0, done_q= 0, scsi_retry_q= 0
3:SCSI Device Information:
3:scsi-qla2-adapter-node=200000e08b18e575;
3:scsi-qla2-adapter-port=210000e08b18e575;
3:scsi-qla2-target-0=50060e80039cab1a;
3:scsi-qla2-port-0=50060e80039cab1a:50060e80039cab1a:612c13:81;
3:SCSI LUN Information:


From the above, you'll know that the "adapter-port-0" line is the WWN of the port itself, and the "target-0" line is the WWN of the Fibre Switch it's connected to.

Simple as binary PI ;)

Cheers,

, Mike




Please note that this blog accepts comments via email only. See our Mission And Policy Statement for further details.

Tuesday, September 23, 2008

Emergency Booting RedHat Linux With USB

Hey there,

This post is for any Linux admin out there, who uses RedHat (or any similar distro, really - the differences are generally minor) and works in a shop outfitted with the latest and greatest hardware to "drive the network." I'm not sure what that expression means, but I heard it in a meeting once and it seemed vaguely motivating ;) It's also the first post on using grub since our post on using grub to change the root password.

If you do use RedHat Linux and run it on hardware that's new or "newer," you probably have a couple of servers (or, possibly, even regular PC's) running RedHat that don't have those good old-fashioned PS/2 keyboards and mice (mouses ?? I'll puzzle over that for my remaining years). You may even, in some instances, find yourself in a situation where you're booting a server from a USB drive. You won't see that too often (especially not in enterprise systems), but you'll catch it here and there in development environments with bizarre quadruple-boot configurations. You may not, technically, support them, but (since you're the sys admin) you support them ;)

Basically, today, we're going to take a look at a way you can protect yourself against disaster in the former situation (No PS/2 Keyboard or mouse) and assume that your server is running RedHat Linux and only has USB keyboard and mouse connectors (Really, you don't need the mouse. That's for the GUI, and the GUI shouldn't have anything to do with an "emergency" recovery. If your GUI works, things can't be all that bad, and, if it doesn't, you won't be using it ;). We'll assume also, that you'll need them to work properly when you boot from a disaster situation. This, as most RedHat Linux users and/or admin's can attest to, is an issue directly related to the default OS setup. The issue is that the USB drivers generally (or, by default) get loaded up after the system has begun booting. Since the USB drivers are treated as ancillary, if your machine is completely screwed and you need to do some minimal CLI work (just interacting with "grub" at a high level), having a USB keyboard as your only option means you're screwed, too, unless you get creative and connect to the box via ALOM or Serial or can jerry-rig some other form of TTY connection to emulate keyboard interaction (You'll discover amazing things you never knew you knew when an important box goes down and the boss is building up to a Grand Mal seizure while he breathes down your neck ;)

Of course, the easiest thing to do (in almost any case, for any problem) is to use up that ounce of prevention (If you encounter resistance, you can always spin this as something that will "save the company a pound of cure" ;). And the easiest way to do that in RedHat Linux is to just create an alternate boot image that includes USB drivers (you saw this coming from a mile away, I know). And RedHat (as with most other distro's) makes this very easy to do. Given the version of RedHat Linux you're running, the switches/arguments you have to pass to the various commands may be slightly different, so I'm including multiple options in some cases where only a few (or one) are actually relevant. Check the man pages on your system to see which one works for you and/or if that option even exists. Who knows, you may have more options on your version than I do on mine, which could, potentially, be even better :)

The first thing to do, would be to figure out what USB drivers you have loaded on your system. A simple find command like this, should give you a general idea (use "lsmod" and grep that output if you want to do things "the right way," but you may miss a few things ;)

host # uname -r
2.4.21-37.ELsmp
host # find /lib/modules/`uname -r`/kernel/drivers/usb -type f -name "*usb*"
/lib/modules/2.4.21-37.ELsmp/kernel/drivers/usb/host/usb-ohci.o
/lib/modules/2.4.21-37.ELsmp/kernel/drivers/usb/host/usb-uhci.o
/lib/modules/2.4.21-37.ELsmp/kernel/drivers/usb/dabusb.o
/lib/modules/2.4.21-37.ELsmp/kernel/drivers/usb/serial/ir-usb.o
/lib/modules/2.4.21-37.ELsmp/kernel/drivers/usb/serial/kl5kusb105.o
/lib/modules/2.4.21-37.ELsmp/kernel/drivers/usb/serial/usbserial.o
/lib/modules/2.4.21-37.ELsmp/kernel/drivers/usb/hpusbscsi.o
/lib/modules/2.4.21-37.ELsmp/kernel/drivers/usb/storage/usb-storage.o
/lib/modules/2.4.21-37.ELsmp/kernel/drivers/usb/usb-midi.o
/lib/modules/2.4.21-37.ELsmp/kernel/drivers/usb/usbcore.o
/lib/modules/2.4.21-37.ELsmp/kernel/drivers/usb/usbnet.o


and this one, just because it's always nice to have (details on down the page):

/lib/modules/2.4.21-37.ELsmp/kernel/drivers/usb/host/ehci-hcd.o

The second thing to do would be to cozy up your "mkinitrd" command and get comfortable with it ;) On RHEL4 (RedHat Enterprise Linux Release 4), you can get away with the following command line to create a new bootable USB-friendly kernel boot image (Note that the release in these examples is RHEL3):

host # mkinitrd --with=ehci-hcd --with=uhci-hcd /boot/newinitrd-`uname -r`.img `uname -r`

If you're using an older, or different, version of RedHat, check out the options you have available to your "mkinitrd" command. Generally, you'll find at least one of these:

--with-usb
--without-usb
(completely contrary to this post, but, included for completeness for those folks who want to make sure they boot with NO USB support ;)
--with=MODULE_NAME
--preload=MODULE_NAME


For instance, this would work on most servers:

host # mkinitrd --preload=ehci-hcd --preload=usb-storage --preload=scsi_mod --preload=sd_mod /boot/usbinitrd.img `uname -r`

From my little find investigation, I found that this would probably work well for my particular server:

host # mkinitrd --preload=ehci-hcd --preload=usb-storage --preload=usb-uhci --preload=usb-ohci --preload=scsi_mod --preload=sd_mod /boot/usbinitrd.img `uname -r`

And, then we'd add a new entry in /etc/grub.conf and give it a test the next time we can sneak in a clean boot up (For those last few examples of "mkinitrd" entries, of course, I'd be doing them all with `uname -r` instead of the actual value of that command, but you don't want to put those backticks in your /etc/grub.conf). A new entry, considering our command above, might look something like this:

title USB RHEL3 (2.6.9-1.667smp)
root (hd0,0)
kernel /vmlinuz-2.6.9-1.667smp
initrd /usbinitrd.img 2.6.9-1.667smp


...basically, if you're just created a different "initrd" image for your same kernel, just copy those lines, change the title slightly and alter the line that begins with "initrd" to point to the file you created with "mkinitrd." Simple :)

and, just in case you're curious about any of the modules we've suggested possibly adding to your new USB boot image, you can usually find out as much about them as you want to know using the modinfo command, like so (I'm leaving out the usb-storage, etc, ones since their name's pretty much say it all :)

host # modinfo ehci-hcd
filename: /lib/modules/2.4.21-37.ELsmp/kernel/drivers/usb/host/ehci-hcd.o
description: "2003-Jan-22 USB 2.0 'Enhanced' Host Controller (EHCI) Driver"
author: "David Brownell"
license: "GPL"
parm: log2_irq_thresh int, description "log2 IRQ latency, 1-64 microframes"

host # modinfo usb-uhci
filename: /lib/modules/2.4.21-37.ELsmp/kernel/drivers/usb/host/usb-uhci.o
description: "USB Universal Host Controller Interface driver"
author: "Georg Acher, Deti Fliegl, Thomas Sailer, Roman Weissgaerber"
license: "GPL"

host # modinfo usb-ohci
filename: /lib/modules/2.4.21-37.ELsmp/kernel/drivers/usb/host/usb-ohci.o
description: "USB OHCI Host Controller Driver"
author: "Roman Weissgaerber <weissg@vienna.at>, David Brownell"
license: "GPL"


Here's hoping you either never have to use this, or that you have it ready to roll if you ever do :)

Cheers,

, Mike




Please note that this blog accepts comments via email only. See our Mission And Policy Statement for further details.

Thursday, August 21, 2008

Displaying System Information On Linux Or Unix With Cfg2html

Hey There,

Today's post is about a program I got turned on to at work, and which makes our script on linux server information reporting seem a bit lackluster. Then again, there's something to be said for not having "too much" information ;) What we're going to look at today is something you (and your technical colleagues) might love (or hate -- check out a message board or two to keep an accurate reading on the heated and irregular pulse of the user community at large ;) This is definitely not something the higher-ups are going to want to deal with. I'm sure they'd love to know it's available, but (and once you check it out, you'll agree) it doesn't contain the requisite number of pie-charts and 3-dimensional lines to impress a board of directors ;)

The script (which is available for free) is called cfg2html and, from my experience so far, I must say it does a fantastic job of reporting what's reportable and making for a very easy-to-read html server analysis (even if I do have to page-down 50 times to look at absolutely everything it reports on). You can pick up the latest (but not necessarily most stable) version at the cfg2html main site. This is an excellent place to go and grab it, but, since it does always have the latest version, you run the risk of picking up a newer (meaning not quite as thoroughly tested) release that you may not want.

If you're looking for stability, and/or a major release, check out the cfg2html Yahoo group. I'm not sure why this is their main site for stable releases, but it's an option that I've never seen used by a free software distributor, so far, and that makes it (at the very least) interesting. There's probably a very good reason. And I'll make myself nuts trying to figure out what it is unless I just drop it... immediately ;)

The cfg2html latest release page and the cfg2html stable release page (which is redirected to from both come.to and freshmeat.net) both have links to downloads tested to run on HP-UX 10 and 11, Solaris, AIX, SCO Unix, SUSE, Debian, Ubuntu and Red Hat) Linux, NT4.0, Windows 2000, certain Brocade switches and OpenWRT/Freifunk routers. You can also find plugins for AP R/3, Oracle, Informix, Samba (with or without SWAT), ITO and NNM, XP-Surestore Storage, EVA, SureStore E, SuperDome, OLA/R, SCM, AutoRAID, FC60, Tip/X, MC/SG, and Dataprotector/OmniBack. Your download size will vary depending on what you need, but the basic setup doesn't get much larger than 900Kb (Which is actually pretty large when you consider that it's a "script"! ...Actually there are probably some extra binary components to a few of the more eccentric entries in the series. The script I used was only about 40 or 50 Kb.)

If that list of options isn't extensive enough for you, you'll be glad to know that sourceforge.net hosts a separate project exclusively for cfg2html for IBM AIX and another, more specific, revision of the original product, called ora2thml which is more heavily geared toward Oracle configuration reporting. And, just to prove it's a small world, ora2html is in the midst of getting together support for AIX.

Random Interesting Fact: The term "acronym" is almost always used incorrectly. An acronym is any combination of letters, which can be pronounced like a word (actually, it should, technically, be a "real" word, but we've let that slip long ago), consisting of the initials of other words. Self Contained Underwater Breathing Apparatus (SCUBA) or White Anglo-Saxon Protestant (WASP) are acronyms. NT, XP, SCM, NNM, CFG, etc are just groups of initials. People who prefer to avoid conflict sometimes refer to them as abbreviations, although that is generally a bit of a stretch, as well ;)

Snapping right back to (One of my favorite acronyms ;) cfg2html, I've posted some screen shots below of the run-time output (taken from the internet public domain -- Shoot me an email if you deserve credit, since I couldn't find who it actually belonged to) and sections of the actual output from a box I got to test it out on. I think you'll agree that the results are impressive, if not overwhelming and possibly suffocating ;)

Click the picture below to see the run-time output from some guy's server in its original size:

cfg2html runtime

And, just after and below this sentence, click the following pictures for larger versions of a portion of the cfg2html TOC output and two out of 50-odd pages of copious details:

cfg2html report header


cfg2html kernel parameter report


cfg2html hardware report

Like I mentioned, if you're looking for something less severe, check out our old post on reporting Linux system information (and maybe even check out our famously lame collections of sar graph scripts for Unix (follow the links near the top of the article to get all the other scripts) and their all-in-one counterpart Linux sar graphing script.

If you want it all and you've gotta have it now (or as soon as you figure out how to make the html format itself the way you want it to ;), I'd highly recommend checking cfg2html out for yourself.

In a future post, we'll look at ways to configure it other than the "everything under the sun" method we've employed today.

Cheers,

, Mike




Please note that this blog accepts comments via email only. See our Mission And Policy Statement for further details.

Wednesday, August 20, 2008

How To Manage Your Disk By UUID On Linux

Hey There,

Today's post is about something I think is pretty cool on Linux (since about kernel 2.1.x, when /proc/partitions was introduced, or made standard). It has to do with disk mounting (both on the command line or through the fstab) by UUID (Universal Unique Identifier). UUID notation, when used as a means to access disk, is just one more way that Linux has moved ahead of the pack to (depending on your way of thinking ;) either make disk management more accessible or make the fstab and disk identification even more confusing ;) NOTE: Skip the next paragraph if you don't care about Open Solaris' slight support for this functionality, to date. Skip to the numbered list if you just want to check out the commands and have had your fair share of my opinion ;)

For those of you who got here by catching the Solaris and Unix tags on this post, I want to address your concerns immediately, since you may no longer be concerned with this text after the next few sentences ;) Although Solaris does "understand" UUID addressing, the level on which Solaris addresses the issue (with regards to disk management) isn't user-friendly enough to fit in the scope of this post. Basically, and this is putting it very generically, the getting and setting of object UUID's on Solaris is still only resident at the code-base layer. I'm glad to see that Sun is addressing the issue with C functions like wsreg_set_id() and wsreg_get_id(), but, since the functionality provided by this layer of access hasn't been implemented in any relevant user tools, we won't be looking at Solaris' implementation of it for the remainder of this dialogue. Ok, I'll give Solaris 10 points for having expanded greatly upon the previous version's acceptance of the standard by implementing a lot of new C routines, a "makeuuid" binary and support for UUID's of zones, but, again, since we're going to be looking at mounting disk using the UUID (without re-writing the OS), Solaris (Open and Regular) is out for now (8/20/2008 just in case the future makes me incorrect, which it has a nasty habit of doing ;)

While Linux boasts most of the same C routines and headers as Solaris (which it must, of course, since the OS supports UUID identification), they're named slightly differently and - the biggest plus - Linux (RedHat and Ubuntu, at least) come with plenty of programs to work with disk UUID's and plenty of hooks to allow other programs to make use of the disk UUID's as well!

The most basic program (that Solaris has picked up on) is called "uuidgen." This program will generate a UUID for you based on the output from a decent randomness-generator (like /dev/random) or resort to time-and-MAC-based randomization ( Generally, the only random factor used is time, unless you have the privilege to view your ethernet adapter's MAC address). The program can be forced to use one or the other, if you have a specific preference (with the "-r" and "-t" flags, respectively). This seemingly extraneous program does have one very important area of application, which we'll look at below.

Where you really see the benefit with Linux is in how they've worked it into their basic hard disk management facilities. They've made it very simple for you to keep track of your disks by UUID using any number of methods. I'll be listing several different means to some "ends" you may want to achieve, as every command may not be available in your Linux distro, but at least one probably is.

One, often unmentioned (but highly valuable), benefit of using UUID's to deal with your disks is that you don't have to worry about system naming conventions and the hassles inherent with using them. For instance, if you have a disk with a specific UUID and a block device name of /dev/sda3, if you do all your work (and system/application customization) with that disk, as the name /dev/sda3, you might be in for a big headache if you have a system problem (or just install some new hardware and reconfigure) and Linux decides to rename /dev/sda3 as /dev/sdb3 (or "anything" else). If you're using UUID's, you can simply use the "tune2fs" command (shown below) to assign the original UUID back to the new logical device name, so /dev/sdb3 would function exactly as if it were /dev/sda3, without causing any issues with your Linux OS :):

1. If you don't know the UUID of your disk, you can find it by using one of the several commands below:

host # vol_id /dev/sda3
...
ID_FS_UUID=a1331d73-d640-4bac-97b4-cf33a375ae5b
...


or:

host # blkid /dev/sda3 <-- Leave blank to show all disks
/dev/sda3: LABEL="/" UUID="a1331d73-d640-4bac-97b4-cf33a375ae5b" SEC_TYPE="ext3" TYPE="ext2"

also:

host # ls -l /dev/disk/by-uuid|grep sda3
lrwxrwxrwx 1 root root 10 11. Okt 18:02 a1331d73-d640-4bac-97b4-cf33a375ae5b-> ../../sda3


2. If you prefer to generate your own UUID's (see above), you can use the uuidgen command and couple it with tune2fs to change the default UUID assigned to your disk by the system, like this:

host # uuidgen
1d721189-7b71-4315-95a7-1c3abc90d379
host # tune2fs -U 1d721189-7b71-4315-95a7-1c3abc90d379 /dev/sda3


3. Then again, if you already know the UUID, you might want to find out what disk it's associated with. You can generally get this information with the "findfs" command, like so:

host # findfs UUID=a1331d73-d640-4bac-97b4-cf33a375ae5b
/dev/sda3


Of course, using some of the commands above and grepping out part of the UUID will also get you your answer, like:

host # ls -l /dev/disk/by-uuid|grep a1331d73-d640-4bac-97b4-cf33a375ae5b
lrwxrwxrwx 1 root root 10 11. Okt 18:02 a1331d73-d640-4bac-97b4-cf33a375ae5b-> ../../sda3


or

host # blkid|grep a1331d73-d640-4bac-97b4-cf33a375ae5b <-- remember that blkid with no arguments returns all of the system disk
/dev/sda3: LABEL="/" UUID="a1331d73-d640-4bac-97b4-cf33a375ae5b" SEC_TYPE="ext3" TYPE="ext2"

4. And, lastly (for this post, at least ;), you can mount your disks using the UUID, and even incorporate that automated UUID mounting into your /etc/fstab. To mount directly from the command line, you can do something like this:

host # mount -U a1331d73-d640-4bac-97b4-cf33a375ae5b /directory/you/mount/this/disk/on

and you could instruct your system to mount this partition by UUID from within the fstab, as well. It works basically the same way that the LABEL keyword does:

host # cat /etc/fstab
...
UUID=a1331d73-d640-4bac-97b4-cf33a375ae5b /directory/you/mount/this/disk/on ext3fs defaults 1 1


And, at this point, you should be able to figure your way around using UUID's to manipulate your disk on Linux with no problem. Enjoy, and please "be careful" :)

Cheers,

, Mike




Please note that this blog accepts comments via email only. See our Mission And Policy Statement for further details.


A comment from Curt, who despises UUID"

I despise UUID with a passion!
An example:
One of my systems has two 200GB hard drives.
Each has over 16 partitions, multiple operating systems and
various data partitions. Now add an external USB hard drive
for backup and restore of partitions.
Imaging trying to figure out how to mount hd1,12 and back it up
to sde4.

Nightmare!

LABEL on the other hand is usable and understandable by humans.
LABEL allows a USB flash drive to always mount the same, solving
that problem.
;<I also dislike using SCSI for PATA drives, limiting partitions to 15,
but that is another story.

Eliminate UUID's and the Microsoft's that create them,
Curt

Tuesday, August 19, 2008

Finding Running Process ID's On Linux Using Pidof

Hey again,

Today, we're going to take a look at a quirky little command (The use of the term "quirky" is my personal bias creeping in ;) called "pidof" that you can, absolutely, find on RedHat ES versions 4 and up. It's probably on lots of other distro's, too, but I can only afford to muck with what's in the free-server-pool at any given moment. This command is actually very interesting and, given that RHEL3 boasts the "pgrep" command, I was quite surprised when I bumped into it. I'm not sure if it seemed contradictory or complementary; just unexpected.

"pidof," as the name would suggest, is a program that will find the process id (PID) of a running program (or the PID's of programs). Again, just like its name, it finds the "pid of" a running process. I'm just repeating this over and over again because the name is so self explanatory is seems contrary to everything I've come to expect from Linux and Unix (od, bc, dc, nm, ar, etc.. &;-- Literally etcetera. There's no program, that I know of, named etc yet ;)

Normally, I would blow a command like this off and stick with what I know; relegating it to that place in the back of my mind so cluttered with mental detritus that it's bound to all crumble apart sooner or later ;) As luck, or a fate I couldn't possibly avoid, would have it, this command does have some interesting (if not puzzling) features and an even more interesting lineage (skip to the bottom of the post for the most bizarre thing about it ;).

In it's basic form, you use it much like you might use pgrep. For instance:

host # pidof dsmadmc
27937 27927 27921 27918 24324 15596 11970 17360


the output format is somewhat different (horizontal rather than vertical) and more limited, but the results are relatively equal. You've just pulled a list of PID's that have, in this case, the string "dsmadmc" in them. It should be noted that pidof's standard mode of operation is like using "pgrep" with the "-x" option. It only returns exact matches and not substring matches. It should also be noted that, unlike pgrep, you can specify more than one program on the command line without making any major changes. Of course, the output is cryptic enough that this may or may not be a good idea:

host # pidof dsmadmc sshd
27937 27927 27921 27918 24324 15596 11970 17360 20657 20651 31593
host # pidof sshd
20657 20651 31593
<-- As you can see, the PID groups follow each other in order, but you have no way of knowing - at least from the straight output - where the PID's from your first named program stop and the PID's from your next named program begin!

This seems like it would be a great way to line up and knock down zombie processes, but, unfortunately, it won't match them (at least not the ways I tried):

host # ps -efl|grep Z
F S UID PID PPID C PRI NI ADDR SZ WCHAN STIME TTY TIME CMD
4 Z root 20992 20989 0 79 0 - 0 exit 00:00 ? 00:00:00 [sh] <defunct>
host # pidof Z

host # pidof defunct

host # pidof "<defunct>"

host # pidof "[sh]:


...and nothing.

If, for some reason, you only want to return one PID from a pool of them, you can run it with "-s," like so:

host # pidof -s dsmadmc
27937


The only thing I could ascertain from running this option multiple times is that it just picks the first PID from it's normal output when you run it in "single shot" mode. I couldn't make any correlation between start date, run time, child/parent process relationship or anything more complex. It's actually as simple as it seems. I suppose you could use this option if you just needed to make sure that at least one instance of a program was running.

The "-x" option is good for hunting down what shell is running what script. You can usually find this out by backtracing the PID from child to parent and so forth, by running "file" against the script itself or just checking your ps output. In the case where you have a script, showing up in your process table, that doesn't have an obvious point of origin for you to examine, this option is a pretty quick way to figure out the invoking shell. Brownie points to anyone who can tell me why this is a complete waste of time in the example I'm giving here ;)

host # ps -ef|grep "[s]leeper"
user1 28884 20658 0 13:37 pts/0 00:00:00 /bin/bash ./sleeper
<-- It should be noted that this is the ps output from a straight run of a script with a shebang line of: #!/bin/bash.
host # pidof -x sleeper
28884


Generally, that shell won't be hanging around once the shell script stops running. If it doesn't die, there's no way to backward-extrapolate the script it had previously run without prior knowledge.

And finally there's the "-o" option, which let's you "omit" a process, with a certain process id, from your output, like so:

host # pidof -o 30401 dsmadmc
30691 30381 30370 24324 15596 11970 17360


For multiple omissions, you can't just add more PID's, you need to preface each with a -o flag, like so:

host # pidof -o 30401 30691 dsmadmc
30691 30381 30370 24324 15596 11970 17360
<-- The wrong way
host # pidof -o 30401 -o 30691 dsmadmc
30381 30370 24324 15596 11970 17360


The special %PPID descriptor can be used to denote that you want to make sure the parent PID doesn't show up in your output. In this case, it doesn't make any difference:

host # pidof -o %PPID dsmadmc
30691 30401 30381 30370 24324 15596 11970 17360
host # pidof dsmadmc
30691 30401 30381 30370 24324 15596 11970 17360


And, of course, just like pgrep and pkill, it's always best to be as specific as you can when naming the process you want to get the PID of. We noted above that this program is pretty good at making exact matches (no substrings matches - so "ini" won't match "init"), but you can never be too careful. Depending upon the process name, you may end up listing out PID's you didn't intend to (especially since there's no option to show both PID's and process names). For instance, if you went looking for a shell, you'd probably be running a high risk of returning false positives, like this:

host # pidof sshd
20657 20651 31593
host # ps -ef|grep "[s]shd"
root 31593 1 0 Apr11 ? 00:06:22 /usr/sbin/sshd
root 20651 31593 0 12:46 ? 00:00:00 sshd: user1 [priv]
user1 20657 20651 0 12:46 ? 00:00:00 sshd: user1@pts/0


Oh, yes, and that thing I mentioned at the beginning about "pidof" having an interesting lineage. As it turns out, this command is really just a symbolic link to the "killall5" command:

host # ls -l /sbin/pidof
lrwxrwxrwx 1 root system 8 Feb 8 2007 /sbin/pidof -> killall5


The "killall5" program's sole function is to send a signal (take your pick) to all processes except for those within the shell from which it's called. The reason this is interesting (at least to me) is that there is no option to send a signal, of any kind, in "pidof." This seems contrary to my sense of style, but arguments can be made for why this functionality was left out of "pidof." I think probably the most reasonable one is that "pidof" appears to have been written as an output producer only. A program that spits up lines of ordered and spaced numbers with the intention of having them "dealt with" by some other program on the other end of a pipe. Still, it seems a bizarre distinction to make.

But, enough of my belly-aching, "pidof" may be just the thing you're looking for. Who am I to judge? I've been around *nix too long to have a truly "objective" opinion about much of it ;)

Cheers,

, Mike




Please note that this blog accepts comments via email only. See our Mission And Policy Statement for further details.

Tuesday, August 12, 2008

Recovering Deleted Files By Inode Number In Linux And Unix

Hey there,

It should be noted, at the outset, that this post is limited in its scope. We're going to be looking at one particular way in which you can recover an accidentally deleted file on Linux or Unix ( Tested on RHEL3 and Solaris 8 ). If you ever want to scour a hard drive that you need to get lots of information back from, then (assuming that you quarantined it immediately upon noticing this and haven't written to it since) you should check out The Coroner's Toolkit. Specifically, you'll want to look at the "ils" or "icat" programs, and most probably the "grave-robber" application to recover as much of everything as possible.

In our post, we're going to look at one condition under which Unix and Linux operating systems can actually hold onto files, even after they've been deleted, so that you can recover them. Of course, you have to realize you've deleted something you wanted to keep (in most cases) immediately, and a fairly specific set of circumstances has to be in play.

Note that all demonstrations have been tested on Solaris and RedHat. We're using RedHat's output, but the differences between the two were minor enough that they didn't bear repeating.

First, we'll look at the controlled scenario: In this case, we're going to create a file. Then we're going to delete it, knowing that we want to retrieve it afterward. How many times does that happen "by accident"? ;)

host # echo "hi there" >>FILE
host # ls -lai
total 8
57794 drwxr-s--- 2 user group 4096 Aug 11 12:36 .
851795 drwxr-s--- 3 user group 4096 Aug 11 12:31 ..
57795 -rw-r----- 1 user group 9 Aug 11 12:36 FILE


Now that the file's created, we can cat it by referencing the inode number (gotten with "ls -lai" above) very easily

host # find . -inum 57795 -exec cat {} \;
hi there


Then we'll set ourselves up so that we can delete the file and still be able to get it back. In order for us to be able to retrieve the deleted file later, we'll need to associate it with a filehandle. One easy way to do that is to run a tail (or similar command) on it):

host # tail -f FILE &
[1] 4741


and then we'll delete it:

host # rm FILE
host # ls -lai
total 8
57794 drwxr-s--- 2 user group 4096 Aug 11 12:41 .
851795 drwxr-s--- 3 user group 4096 Aug 11 12:31 ..


So, now it's gone. But, and this is the only thing that's saving us a whole lot of headache, the file is still open in memory since we still have a "tail -f" job running in the background. This means that the tail command still has a filehandle open for our file FILE. Of course, we can't refer to it by that name anymore. One interesting thing to note about an inode is that it contains virtually all the information you ever wanted to know about your file... except it's name! :)

Therefore, the following query with lsof fails to produce results:

host # lsof|grep FILE

IMPORTANT NOTE: If you have followed this process closely and either wrote down or remembered the "inode number" of the FILE file before we deleted it, you can skip all of this lsof stuff. Jump straight to the next IMPORTANT NOTE in this post :)

A quick look at what pseudo-terminal we're using, coupled with the knowledge that we ran "tail -f" on the file, makes for a pretty tidy grep string (of course, you don't need to have this much information. You can do this without of a filter and just have more lsof output to muck through):

host # tty
/dev/pts/0
host # lsof|grep pts/0|grep tail
tail 4741 user 0u CHR 136,0 2 /dev/pts/0
tail 4741 user 1u CHR 136,0 2 /dev/pts/0
tail 4741 user 2u CHR 136,0 2 /dev/pts/0


Now we know the PID (second column in from the left) of the process that still has the file open and we can use lsof to drill down even further, using the output of the pwd command to whittle down the output:

host # pwd
/home/users/user
host # lsof -p 4741|grep home/users/user
COMMAND PID USER FD TYPE DEVICE SIZE NODE NAME
tail 4741 user cwd DIR 0,22 4096 57794 /home/users/user (host:/remote/users)
tail 4741 user 3r REG 0,22 9 57795 /home/users/user/FILE (host:/remote/users)


IMPORTANT NOTE: Welcome back, if you already knew the inode number, and "on we go" to everyone! One interesting thing to note about the lsof output is that there is only a "read" filehandle open for FILE. This is normal, since we're doing a "tail -f" and there doesn't need to be a write or read/write file descriptor active.

Now we can verify that the our "file" still exists by accessing it via the inode number:

host # find . -inum 57795 -exec cat {} \;
hi there


And, it's still there :) In order to preserve it (since it the inode-fd connection will be severed as soon as "tail -f" quits), we'll use similar "find" syntax to copy the inode to a filename and verify it, like so:

host # find . -inum 57795 -exec cp {} FILE.recovered \;
host # ls -lai
total 8
57794 drwxr-s--- 2 user group 4096 Aug 11 12:42 .
851795 drwxr-s--- 3 user group 4096 Aug 11 12:31 ..
57796 -rw-r----- 1 user group 9 Aug 11 12:42 FILE.recovered
host # cat FILE.recovered
hi there


Now we can quit our backgrounded "tail -f" job and not worry about it.

host # kill %%
host #
[1] + Terminated tail -f FILE


Like I said, a neat trick, but will only work if you get lucky. Pardon the double-cliche, but keeping calm when you realize that you may have royally screwed the pooch can go a long way toward keeping you from having to take the long way home (isolating the disk, scouring it with forensics tools, perhaps grepping the raw filesystem and manually reconstructing, etc).

The one thing to remember is that, if you delete a file on Linux or Unix, as long as one other process, that was using it when it existed, is still up and running after you delete it, there's a possibility that you can get your file back fairly quickly (actual results may vary. The possible scenario's are many and varied).

And, to give us a fair sendoff, here's a quick look at what you can expect if you delete a file and no process is attached to it and/or has a filehandle open against it (If you don't like watching train-wrecks, then I'll bid a good evening to you right here and now - cheers :)

host # ls -lai
total 8
57794 drwxr-s--- 2 user group 4096 Aug 11 12:43 .
851795 drwxr-s--- 3 user group 4096 Aug 11 12:31 ..
57796 -rw-r----- 1 user group 9 Aug 11 12:42 FILE
host # find . -inum 57796 -exec cat {} \;
hi there
host # rm FILE
host # find . -inum 57796 -exec cat {} \;
host # tty
/dev/pts/0
host # lsof|grep pts/0
ksh 3907 user 1u CHR 136,0 2 /dev/pts/0
ksh 3907 user 2u CHR 136,0 2 /dev/pts/0
ksh 3907 user 11u CHR 136,0 2 /dev/pts/0
lsof 5062 user 0u CHR 136,0 2 /dev/pts/0
lsof 5062 user 2u CHR 136,0 2 /dev/pts/0
grep 5063 user 2u CHR 136,0 2 /dev/pts/0
grep 5064 user 1u CHR 136,0 2 /dev/pts/0
grep 5064 user 2u CHR 136,0 2 /dev/pts/0
host # lsof|grep FILE
host # lsof|grep 57796
host # ls -lai
total 8
57794 drwxr-s--- 2 user group 4096 Aug 11 12:44 .
851795 drwxr-s--- 3 user group 4096 Aug 11 12:31 ..


...bummer.

, Mike




Please note that this blog accepts comments via email only. See our Mission And Policy Statement for further details.

Tuesday, August 5, 2008

Using Grub To Change RedHat Linux's Root Password

Hey There,

I'm back from the dead and no longer cursing Vista ( I've always thought it was strange that most people, including myself, feel disappointment or sorrow when they lose something they didn't have in the first place. The opposite seems perfectly logical. I feel very relieved that I no longer have something that I never had before ;)

Today, we're going to take a look at a quick way to get back your root password (assuming its yours) if, for some reason, you get locked out of your machine. It happens... more than I'd care to admit ;) The course of action I see followed most often is booting from CD, temporarily mounting the physical root drive, and editing /etc/passwd. This is a time-tested solution, and works on pretty much any version of Linux or Unix I've worked with, but I think this way is more fun (and slightly less dangerous). Plus, it saves you a little time (not a lot; just a little). We haven't taken a look at grub since our post on recovering failed raid disks, so I guess this post is about due.

The trick in question has only been tested on RedHat Linux ES, so I can't speak for whether it works on, say, CentOS or Fedora (although I imagine it would work on any system that uses grub for boot loading). Basically, what we're going to do is use grub's boot options to allow us to obtain root access. And, if your machine is properly secured (the /boot directory in particular), you shouldn't be able to edit /etc/grub.conf as a normal user, so physical access (or console/ALOM-type access) to the machine in question is required. It's a pretty simple procedure and goes something like the following:

1. Login to the console on the machine and type "reboot" or "shutdown -r," etc, if you have an account with privileges to initiate such an action. If you don't have an account with suitable privilege, try control-alt-delete (and power off) or hard power-down your machine (you may need to fsck later, but that's a given), take a deep breath and count to 11 ;)

2. Power on the server and wait for the grub boot screen to come up. You'll may not need the GUI for this to work, but it's the only way I've done it. When the grub boot menu comes up, hit the up or down arrow key at least once to stop the automatic boot countdown timer. If you have multiple boot options, choose the one you know (or believe) is the one currently in use (actually, this shouldn't matter, but loading up an older kernel might cause issues) and press the "e" key to enter edit mode.

3. After you enter edit mode, you'll be presented with a few lines of text (dependent on how you have your grub.conf populated). Using your arrow key again, navigate to the line that starts with "kernel." Press the "e" key again, and your cursor should show up at the end of the "kernel" line (if it doesn't, you can move it to where you need it by using the left and/or right arrow keys as necessary).

4. Now that you're in edit mode, and your cursor is in the correct position, type a "space" character followed by "single." So if your boot command line was:

kernel /boot/vmlinuz-2.6.9-34.ELsmp ro root=/dev/sda1
it would now be:
kernel /boot/vmlinuz-2.6.9-34.ELsmp ro root=/dev/sda1 single

5. Now type "b" to continue the boot process and you'll be dumped into a limited shell, as root, passwordlessly. Sometimes this has seemed not to work for me if I changed my edit-focus to a line other than the "kernel" line before typing "b", but that could just be superstition on my part. Thankfully, I don't have to do this all that often :)

6. The rest is gravy. You're root, so all you have to do is type "passwd", set the root password to whatever you like and reboot using your preferred method (reboot, shutdown -r, init 6, whatever works, etc). Since you're in a single-user shell, you can also instantiate a reboot by just typing "exit."
And you should be all set. Now you no longer have an excuse to avoid fixing problems on that machine (the downside ;)
Cheers,

, Mike



08/06/2008 - Thanks for this Additional Useful Information From zcat:

On many distros the 'single' or 'rescue' boot will still ask for a
password. You can get around this by starting linux without starting
initd, just launch a shell instead; and it's blindingly fast.

'e' to edit the boot entry, select the kernel line and press 'e'
again, then type "init=/bin/bash", enter, press 'b' to boot it. You
end up at a root prompt with / mounted read-only. (depending on the
distro, you might need /bin/sh instead)

# mount / -o remount,rw
# passwd
<change your root password here>
# mount / -o remount,ro
<three-finger salute or hit the reset button>



It's also useful for fixing up boot problems, if you're silly enough
to have put commands in various init scripts that don't actually exit
or daemonize...




Thanks for these comments from Laurent regarding an alternate way to get to single user:

Nice to see that method that I was used to apply. Especially with some servers that have been hardened with password aging implementation. And when it is stable you don't need to log on for more than 60 days sometimes....

You could also add that grub can (should?) be password protected.

Cheers

Laurent