1. Trang chủ
  2. » Công Nghệ Thông Tin

Linux Server Hacks Volume Two phần 5 pptx

41 242 0

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 41
Dung lượng 5,51 MB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

If your system runs a TFTP server via inetd, make sure that an entry for the TFTP daemon is present and not commented out inyour /etc/inted.conf file.. Since our DHCP server only specifi

Trang 1

4.9.1.1 Configuring DHCP.

When you know for sure that your machines support PXE, you can move on to configuring your

DHCP/BOOTP server This service will respond to the PXE broadcast coming from the target node by

delivering an IP address, along with the name of a boot file and the address of a host from which the boot filecan be retrieved Here's a typical entry for a target host:

At this point, you should be able to boot the client, tell it to PXE boot, and see it get an IP address and report

to you what that address is In the event that you have a PXE implementation that tells you nothing, you cancheck the DHCP server logs for confirmation A successful DHCP request and response will look somethinglike this in the logs:

Aug 9 06:05:55 livid dhcpd: [ID 702911 daemon.info] DHCPDISCOVER from 00:

40:96:35:22:ff (jonesy-thinkpad) via 172.16.1.1

Aug 9 06:05:55 livid dhcpd: [ID 702911 daemon.info] DHCPOFFER on 192.168.

198.101 to 00:40:96:35:22:ff (jonesy-thinkpad) via 192.168.198.100

4.9.1.2 Configuring a TFTP server.

Once the machine is able to get an IP address, the next thing it will try to do is get its grubby RJ45 connectors

on a boot file This will be housed on a TFTP server On many distributions, a TFTP server is either included

or readily available Depending on your distribution, it may or may not run out of inetd or xinetd If it is runfrom xinetd, you should be able to enable the service by editing /etc/xinetd.d/in.tftpd and changing the

disable option's value to no Once that's done, restarting xinetd will enable the service If your system runs

a TFTP server via inetd, make sure that an entry for the TFTP daemon is present and not commented out inyour /etc/inted.conf file If your system runs a TFTP server as a permanent daemon, you'll just have to makesure that the TFTP daemon is automatically started when you boot your system

Next, we need to create a directory structure for our boot files, kernels, and configuration files Here's asimple, no-frills directory hierarchy that contains the bare essentials, which I'll go over in a moment:

Trang 2

First, run this command to quickly set up the directory hierarchy described above:

$ mkdir -p /tftpboot/linux-install/pxelinux.cfg

The -p option to mkdir creates the necessary parent directories in a path, if they don't already exist With thedirectories in place, it's time to get the files! The first one is the one our client is going to request: pxelinux.0.This file is a simple bootloader meant to enable the system to do nothing more than grab a configuration file,from which it learns which kernel and initial ramdisk image to grab in order to continue on its way The fileitself can be obtained from the syslinux package, which is readily available for almost any distribution on theplanet Grab it (or grab the source distribution), install or untar the package, and copy the pxelinux.0 file over

to /tftpboot/linux-install/pxelinux.0

Once that file is delivered to the client, the next thing the client does is look for a configuration file It should

be noted here that the syslinux-supplied pxelinux.0 always looks for its config file under pxelinux.cfg bydefault Since our DHCP server only specifies a boot file, and you could have a different configuration file forevery host you PXE boot, it looks for the config file using the following formula:

It looks for a file named using its own MAC address, in all-uppercase hex, prefixed by the hex

representation of its ARP type, with all fields separated by dashes So, using our example target hostwith the MAC address 00:40:96:35:22:ff, the file would be named 01-00-40-96-35-22-FF The 01 inthe first field is the hex representation of the Ethernet ARP type (ARP type 1)

1

Next, it looks for a file named using the all-uppercase hex representation of the client IP address Thesyslinux project provides a binary called gethostip for figuring out what this is, which is much nicerthan doing it in your head Feeding my IP address to this command returns COA8C665

2

If neither of these files exists, the client iterates through searching for files named by lopping onecharacter off the end of the hex representation of its IP address (COA8C66, COA8C6, COA8C,COA8…you get the idea)

Whichever way you go, the configuration file needs to tell the client what kernel to boot from, along with anyoptions to pass to the kernel as it boots If this sounds familiar to you, it should, because it looks a lot like aLILO or GRUB configuration Here's our default config file:

Trang 3

The client gets nowhere, however, until it gets a kernel and ramdisk image We've told it to use vmlinuz forthe kernel and the default initial ramdisk image, which is always initrd.img Both of these files are located inthe same directory as pxelinux.0 The files are obtained from the distribution media that we're attempting toinstall In this case, since it's Red Hat, we go to the isolinux directory on the boot CD and copy the kernel andramdisk images from there over to /tftpboot/linux-install.

4.9.2 Getting It Working

Your host is PXE-enabled; your DHCP server is configured to deliver the necessary information to the targethost; and the TFTP server is set up to provide the host with a boot file, a configuration file, a kernel, and aramdisk image All that's left to do now is boot! Here's the play-by-play of what takes place, for clarity's sake:

You boot and press a function key to tell the machine to boot using PXE

Here are some of the problems you may run into and how to tackle them:

If you get TFTP ACCESS VIOLATION errors, these can be caused by almost anything However, theobvious things to check are that the TFTP server can actually access the file (using a TFTP client) andthat the DHCP configuration for the target host lists only a filename parameter specifying

pxelinux.0, and doesn't list the BOOTP bootfile-name parameter

If you fail to get a boot file and you get a "TFTP open timeout" or some other similar timeout, check

to make sure the TFTP server is allowing connections from the client host

If you fail to get an IP address at all, grep for the client's MAC address in the DHCP logs for clues Ifyou don't find it, your client's broadcast packets aren't making it to the DHCP server, in which caseyou should look for a firewall/ACL rule as a possible cause of the issue

Hack 37 Turn Your Laptop into a Makeshift Console

Use minicom and a cable (or two, if your laptop doesn't have a serial port) to connect to the console port ofany server

Trang 4

There are many situations in which the ability to connect to the serial console port of a server can be a reallifesaver In my day-to-day work, I sometimes do this for convenience, so I can type commands on a server'sconsole while at the same time viewing some documentation that is inevitably available only in PDF format(something I can't do from a dumb terminal) It's also helpful if you're performing tasks on a machine that isnot yet hooked up to any other kind of console or if you're on a client site and want to get started right awaywithout having to learn the intricacies of the client's particular console server solution.

4.10.1 Introducing minicom

How is this possible? There's an age-old solution that's provided as a binary package by just about everyLinux distribution, and it's called minicom If you need to build from source, you can download it at

http://alioth.debian.org/projects/minicom/ minicom can do a multitude of great things, but what I use it for is

to provide a console interface to a server over a serial connection, using a null modem cable (otherwise known

as a crossover serial cable)

Actually, that's a big, fat lie My laptop, as it turns out, doesn't have a serial port! I didn't even look to confirmthat it had one when I ordered it, but I've found that many newer laptops don't come with one If you're in thesame boat, fear not! Available at online shops everywhere, for your serial connection pleasure, are

USB-to-serial adapters Just plug this thing into a USB port, then connect one end of the null modem cable tothe adapter and the other end to the server's serial port, and you're in business

With hardware concerns taken care of, you can move on to configuring minicom A default configurationdirectory is usually provided on Debian systems in /etc/minicom On Red Hat systems, the configuration filesare usually kept under /etc and do not have their own directory Customizing the configuration is generallydone by running this command as root:

$ minicom fast

Of course, this assumes that a regular user has access to that profile There is a user access file, named

minicom.users, that determines which users can get to which profiles On both Debian and Red Hat systems,all users have access to all profiles by default

A slightly simpler way to get a working configuration is to steal it Here is a barebones configuration forminicom Though it's very simple, it's really the only one I've ever needed:

# Machine-generated file - use "minicom -s" to change parameters.

pu port /dev/ttyUSB0

pu baudrate 9600

pu bits 8

Trang 5

dynamically loads it when needed, but if you build your own kernels, make sure you don't skip over thismodule! In your Linux kernel configuration file, the option CONFIG_USB_SERIAL should be set to y or m.

It should not be commented out

The next setting is the baudrate, which has to be the same on both the client and the server In this case,I've picked 9,600, not because I want to have a turtle-slow terminal, but because that's the speed configured onthe servers to which I usually connect It's plenty fast enough for most things that don't involve tailing massivelogfiles that are updated multiple times per second

The next three settings dictate how the client will be sending its data to the server In this case, a single

character will be eight bits long, followed by no parity bit and one stop bit This setting (referred to as "8N1")

is by far the most common setting for asynchronous serial communication These settings are so standard thatI've never had to change them in my minicom.conf filein fact, the only setting I do change is the baud rate

4.10.2 Testing It

Once you have your configuration in place, connect your null modem or USB-to-serial adapter to your laptopand connect the other end to the serial console port on the server If you're doing this for the first time, theserial console port on the server is a 15-pin male connection that looks a lot like the male version of a standardVGA port It's also likely to be the only place you can plug in a null modem cable! If there are two of them,generally the one on the top (in a vertical configuration) or on the left (in a horizontal configuration) will bettyS0 on the server, and the other will be ttyS1

After you've physically connected the laptop to the server, the next thing to do is fire up a terminal applicationand launch minicom:

$ minicom

This command will launch minicom with its default configuration Note that on many systems, launching theapplication alone doesn't do much: you have to hit Enter once or twice to get a login prompt returned to you

4.10.3 Troubleshooting

I've rarely had trouble using minicom in this way, especially when the server end is using agetty to provide its

of the communication, because agetty is pretty forgiving and can adjust for things like seven-bit charactersand other unusual settings In the event that you have no output or your output looks garbled, check to make

Trang 6

connected to the correct serial port! On the server, try typing the following to get a quick rundown of theserver settings:

$ grep agetty /etc/inittab

co:2345:respawn:/sbin/agetty ttyS0 9600 vt100-nav

$

This output shows that agetty is in fact running on ttyS0 at 9600 baud The vt100-nav option on the end isput there by the Fedora installation program, which sets up your inittab entry by default if something isconnected to the console port during installation The vt100-nav option sets the TERM environmentvariable If you leave this setting off, most Linux machines will just set this to vt100 by default, which isgenerally fine If you want, you can tell minicom to use an alternate terminal type on the client end with the

-t flag

If you're having trouble launching minicom, make sure you don't have restrictions in place in the

configuration file regarding who is allowed to use the default profile

Hack 38 Usable Documentation for the Inherently Lazy

Web-based documentation is great, but it's not very accessible from the command line

However, manpages can be with you always

I know very few administrators who are big fans of creating and maintaining documentation

It's just not fun Not only that, but there's nothing heroic about doing it Fellow administrators

aren't going to pat you on the back and congratulate you on your wicked cool documentation

What's more, it's tough to see how end users get any benefit when you document stuff that's

used only by administrators, and if you're an administrator writing documentation, it's likely

that everyone in your group already knows the stuff you're documenting!

Well, this is one way to look at it However, the fact is that turnover exists, and so does

growth It's possible that new admins will come on board due to growth or turnover in your

group, and they'll have to be taught about all of the customized tools, scripts, processes,

procedures, and hacks that are specific to your site This learning process is also a part of any

new admin's enculturation into the group, and it should be made as easy as possible for

everyone's benefit, including your own

In my travels, I've found that the last thing system administrators want to do is write

documentation The only thing that might fall below writing documentation on their lists of

things they're dying to do is writing web-based documentation I've tried to introduce

in-browser WYSIWYG HTML editors, but they won't have it Unix administrators are quite

happy using Unix tools to do their work "Give me Vim or give me death!"

Another thing administrators typically don't want to do is learn how to use tools like LaTeX,

SGML, or groff to create formal documentation They're happiest with plain text that is easily

typed and easily understood by anyone who comes across the raw file Well, I've found a tool

that enables administrators to create manpages from simple text files, and it's cool It's called

txt2man

Trang 7

Of course, it comes with a manpage, which is more than enough documentation to use the

tool effectively It's a simple shell script that you pass your text file to, along with any options

you want to pass for a more polished end result, and it spits out a perfectly usable manpage

Here's how it works

I have a script called cleangroup that I wrote to help clean up after people who have departed

from our department (see "Clean Up NIS After Users Depart" [Hack #77]) It goes through

our NIS map and gets rid of any references made to users who no longer exist in the NIS

password map It's a useful script, but because I created it myself there's really no reason that

our two new full-time administrators would know it exists or what it does So I created a new

manpage directory, and I started working on my manpages for all the tools written locally

that new admins would need to know about Here is the actual text I typed to create the

cleangroup is a perl script used to check each uid found in the group file

against the YP password map If the user doesn't exist there, the user is

removed from the group.

The only argument to the file is groupfile, which is required.

Brian Jones jonesy@linuxlaboratory.org

The headings in all caps will be familiar to anyone who has read his fair share of manpages I

saved this file as cleangroup.txt Next, I ran the following command to create a manpage

called cleangroup.man:

$ txt2man -t cleangroup -s 8 cleangroup.txt > cleangroup.man

When you open this manpage using the man command, the upper-left and right corners will

display the title and section specified on the command line with the -t and -s flags,

respectively Here's the finished output:

Trang 8

The only argument to the file is groupfile, which is required.

Brian Jones jonesy@cs.princeton.edu

For anyone not enlightened as to why I chose section 8 of the manpages, you should know

that the manpage sections are not completely arbitrary Different man sections are for

different classes of commands Here's a quick overview of the section breakdown:

Table 4-1.

1

User-levelcommands such

as ls and man

2

System callssuch as

gethostname

and setgid

3

Library callssuch as

isupper and

getchar

4

Special filessuch as fd andfifo

5

Configurationfiles such asldap.conf andnsswitch.conf

MAKEDEV and

pvscan

Some systems have a section 9 for kernel documentation If you're planning on making your own manpagesection, try to pick an existing one that isn't being used, or just work your manpages into one of the existingsections Currently, man only traverses manX directories (where X is a single digit), so man42 is not a validmanpage section

Though the resulting manpage isn't much different from the text file, it has the advantage that you can actuallyuse a standard utility to read it, and everyone will know what you mean when you say "check out man 8cleangroup." That's a whole lot easier than saying "go to our intranet, click on Documentation, go to Systems,

Trang 9

then Linux/Unix, then User Accounts, and click to open the PDF."

If you think that txt2man can handle only the simplest of manpages, it has a handy built-in help that you cansend to itself; the resulting manpage is a pretty good sample of what txt2man can do with just simple text Runthis command (straight from the txt2man manpage) to check it out:

$ txt2man -h 2>&1 | txt2man -T

This sends the help output for the command back to txt2man, and the -T flag will preview the output for youusing more or whatever you've set your PAGER environment variable to This flag is also a quick way topreview manpages you're working on to make sure all of your formatting is correct instead of having to create

a manpage, open it up, realize it's hosed in some way, close it, and open it up again in your editor Give it atry!

Hack 39 Exploit the Power of Vim

Use Vim's recording and keyboard macro features to make monotonous tasks lightning fast

Every administrator, at some point in his career, runs into a scenario in which it's unclear whether a task can

be performed more quickly using the Vim command (a period) and one or two other keystrokes for everychange, or using a script Often, admins wind up using the command because they figure it'll take less timethan trying to figure out the perfect regex to use in a Perl, sed, or awk script

However, if you know how to use Vim's "recording" feature, you can use on-the-fly macros to do your dirtywork with a minimum of keystrokes What's more, if you have tasks that you have to perform all the time inVim, you can create a keyboard macros for those tasks that will be available any time you open your editor.Let's have a look!

4.12.1 Recording a Vim Macro

The best way to explain this is with an example I have a file that is the result of the dumping of all the data in

my LDAP directory It consists of the LDIF entries of all the users in my environment

One entry looks like this:

Trang 10

o: Linuxlaboratory.orgou: Systems Group

There are roughly 1,000 entries in the file What I need to do, for every user, is tag the end of every

labeledURI line with a value of ~username This will reflect a change in our environment in whichevery user has some web space accessible in her home directory, which is found on the Web using the URLhttp://www.linuxlibrary.org/~username Some entries have more lines than others, so there's not a wholeheckuva lot of consistency or predictability to make my job easy You could probably write some really uglyshell script or Perl script to do this, but you don't actually even have to leave the cozy confines of Vim to get itdone First, let's record a macro Step 1 is to type (in command mode) qn, where n is a register label Validregister labels are the values 09 and az Once you do that, you're recording, and Vim will store in register n

every single keystroke you enter, so type carefully! Typing q again will stop the recording

Here are the keystrokes I used, including my keystrokes to start and stop recording:

Now I have a nice string of keystrokes stored in register z, which I can view by typing the following

command:

:register z

Trang 11

"z /uid: ^Mwwyw/labeledURI: ^MA/~^[p

If you can see past the control characters (^M is Enter and ^[ is Escape), you'll see that everything I typed isthere Now I can call up this string of keystrokes any time I want by typing (again, in command mode) @z It

so happens that there are 935 entries in the file I'm working on (I used wc l on the file to get a count), one ofwhich has been edited already, so if I just place my cursor on the line underneath the last edit I performed andtype 934@z, that will make the changes I need to every entry in the file Sadly, I have not found a way tohave the macro run to the end of the file without specifying a number

4.12.2 Creating Vim Shortcut Keys

I happen to really like the concept of WYSIWYG HTML editors I like the idea of not having to be concernedwith tag syntax To that extent, these editors represent a decent abstraction layer, enabling me to concentratemore on content than form They also do away with the need to remember the tags for things such as greaterthan and less than characters and nonbreaking spaces, which is wonderful

Unfortunately, none of these shiny tools allows me to use Vim keystrokes to move around within a file I'mnot even asking for search and replace or any of the fancy register stuff that Vim offersjust the simple ability

to move around with the h, j, k, and l keys, and maybe a few other conveniences It took me a long time

to figure out that I don't need to compromise anymore! I can have the full power of Vim and use it to create anenvironment where the formatting, while not completely invisible, is really a no-brain-required activity

Here's a perfect example of one way I use Vim keyboard shortcuts every day I have to write some of mydocumentation at work in HTML Any time my document contains a command that has to be run, I enclosethat command in <code></code> tags This happens a lot, as the documentation I write at work is for anaudience of sysadmins like me The other two most common tags I use are the <p></p> paragraph tags andthe <h2></h2> tags, which mark off the sections in the documentation Here's a line I've entered in my

~/.vimrc file so that entering code tags is as simple as hitting F12 on my keyboard

imap <F12> <code> </code> <Esc>2F>a

The keyword imap designates this mapping as being active only in insert mode I did this on purpose,

because I'm always already in insert mode when I realize I need the tags Next is the key I'm mapping to,which is, in this case, F12 After that are the actual tags as they will be inserted Had I stopped there, hittingF12 in insert mode would put in my tags and leave my cursor to the right of them Because I'm too lazy tomove my cursor manually to place it between the tags, I put more keystrokes on the end of my mapping First,

I enter command mode using the Esc key The 2F> bit says to search from where the cursor is backward tothe second occurrence of >, and then the a places the cursor, back in insert mode, after the > character I nevereven realize I ever left insert modeit's completely seamless!

Hack 40 Move Your PHP Web Scripting Skills to the Command Line

PHP is so easy, it's made web coders out of three-year-olds Now, move that skill to the CLI!

Trang 12

These days, it's rare to find a person who works with computers of any kind for a living who has not gottenhooked on PHP The barrier to entry for coding PHP for the Web is a bit lower than coding Perl CGI scripts, ifonly because you don't have to compile PHP scripts in order to run them I got hooked on PHP early on, but I

no longer code much for the Web What I have discovered, however, is that PHP is a very handy tool forcreating command-line scripts, and even one-liners on the command line

Go to the PHP.net function reference (http://www.php.net/manual/en/funcref.php) and check out what PHPhas to offer, and you'll soon find that lots of PHP features of PHP are perfect for command-line programming.PHP has built-in functions for interfacing with syslog, creating daemons, and utilizing streams and sockets Iteven has a suite of POSIX functions such as getpwuid and getpid

For this hack, I'll be using PHP5 as supplied in the Fedora Core 4 distribution PHP is readily available inbinary format for SUSE, Debian, Red Hat, Fedora, Mandrake, and other popular distributions Some distroshave not yet made the move to PHP5, but they'll likely get there sooner rather than later

Obviously, the actual code I use in this hack will be of limited use to you The idea is really to make you thinkoutside the box, using skills you already have, coding in PHP and applying it to something unconventionallike system administration

Yucky It's even worse if you have to do this type of search often I suppose you could write a shell script, but

I found that PHP was perfectly capable of handling the task without relying on the ldapsearch tool being onthe system at all In addition, PHP's universality is a big pluseveryone in my group has seen PHP before, butsome of them code in tcsh, which is different enough from ksh or bash to be confusing Don't forget that thecode you write today will become someone else's problem if a catastrophic bug pops up while you're on a shipsomewhere sipping margaritas, far from a cell phone tower Anyway, here's my script, which I call dapsearch:

$answer = ldap_search($conn, "dc=linuxlaboratory,dc=org", "($argv[1])") ;

$output = ldap_get_entries($conn, $answer);

for ($i=0; $i < count($output); $i++) {

Trang 13

There are a couple of things to note in the code above On the first line is your everyday "shebang" line, whichcontains the path to the binary that will run the code, just like in any other shell or Perl script If you're coding

on your desktop machine for later deployment on a machine you don't control, you might replace that linewith one that looks like this:

#!/usr/bin/env php

This does away with any assumption that the PHP binary is in a particular directory by doing a standard PATH

search for it, which can be more reliable

In addition, you'll notice that the <?php and ?> tags are there in the shell script, just like they are in webscripts This can be useful in cases where you have static text that you'd like output to the screen, because youcan put that text outside the tags instead of using echo statements Just close the tag, write your text, then open

a new set of tags, and the parser will output your text, then start parsing PHP code when the tags open again

Also, you can see I've simplified things a bit by hard-coding the attribute to be returned (the dn attribute), aswell as the server to which I'm connecting This script can easily be altered to allow for that information to bepassed in on the command line as well Everything you pass on the command line will be in the argv array

4.13.2 Running the Code

Save the above script to a file called dapsearch, make it executable, and then run it, passing along the attributefor which you want to search In my earlier ldapsearch command, I wanted the distinguished name attributes

of all users with the last name "Jones." Here's the (greatly shortened) command I run nowadays to get thatinformation:

$ dapsearch sn= Jones

This calls the script and passes along the search filter, which you'll see referenced in the code as $argv[1].This might look odd to Perl coders who are used to referencing a lone argument as either @_, $_,or

$argv[0] In PHP, $argv[0] returns the command being run, rather than the first argument handed to it

on the command line

Speaking of the argv array, you can run into errors while using this feature if your installation of PHP

doesn't enable the argv and argc arrays by default If this is the case, the change is a simple one: just open

up your php.ini file (the configuration file for the PHP parser itself) and set register_argc_argv to on

Hack 41 Enable Quick telnet/SSH Connections from the Desktop

Desktop launchers and a simple shell script make a great combo for quick telnet and SSH connections toremote systems

Trang 14

Many of us work with a large number of servers and often have to log in and out of them Using KDE orGNOME's Application Launcher applet and a simple shell script, you can create desktop shortcuts that

enabled you to quickly connect to any host using a variety of protocols

To do this, create a script called connect, make it executable, and put it in a directory that is located in your

PATH This script should look like the following:

if [ "$type" != "multi" ]; then

konsole -T "${proto}::${fqdn}" nomenubar notoolbar ${extraargs} -e ${proto} ${fqdn} ${args}

Trang 15

To use this script when you are using KDE, right-click on the desktop and select Create New File

Link to Application This displays a dialog like the one shown in Figure 4-2 Enter the name of the script thatyou want to execute and the host that you want to connect to, and save the link

Figure 4-2 Creating a desktop launcher in KDE

To use this script when you are using GNOME, right-click on the desktop and select Create Launcher Thisdisplays a dialog like the one shown in Figure 4-3 Enter the name of the script that you want to execute andthe host that you want to connect to, and save the link

Figure 4-3 Creating a desktop launcher in GNOME

Trang 16

Using either of these methods, you quickly create desktop shortcuts that allow you to initiate a connection to aremote system by clicking on the link on your desktopno fuss, no muss!

4.14.1 See Also

"Execute Commands Simultaneously on Multiple Servers" [Hack #29]

Lance Tost

Hack 42 Speed Up Compiles

While compiling, make full use of all of your computers with a distributed compiling daemon

Many other distribution users make fun of the Gentoo fanboys, because Gentoo users have to spend a lot oftime compiling all of their code And even though these compiles can take hours or days to complete,

Gentooists still tout their distribution as being one of the fastest available Because of their constant need tocompile, Gentoo users have picked up a few tricks on making the process go faster, including using distcc tocreate a cluster of computers for compiling distcc is a distributed compiling daemon that allows you tocombine the processing power of other Linux computers on your network to compile code It is very simple toset up and use, and it should produce identical results to a completely local compile Having three machineswith similar speeds should make compiling 2.6 times faster The distcc home page at http://distcc.samba.org

has testimonials concerning real user's experiences using the program Using this hack, you can get distcc towork with any Linux distribution, which will make compiling KDE and GNOME from scratch quick andeasy

distcc does not require the machines in your compile farm to have shared filesystems,synchronized clocks, or even the same libraries and headers However, it is a goodidea to make sure you are on the same major version number of the compiler itself

Before getting started with distcc, first you must know how to perform a parallel make when building code

To perform a parallel make, use the j option in your make command:

dbrick@rivendell:$ make j3; make j3 modules

This will spawn three child processes that will make maximum use of your processor power by ensuring thatthere is always something in the queue to be compiled A general rule of thumb for how many parallel makes

to perform is to double the number of processors and then add one So a single processor system will have j3

and a dual processor system j5 When you start using distcc, you should base the j value on the total number

of processors in your compiling farm If you have eight processors available, then use j17

Trang 17

dbrick@rivendell:$ ./configure && make && sudo make install

You must install the program on each machine you want included in your compile farm On each of thecompiling machines, you need to start the distccd daemon:

root@bree:# distccd daemon N15

root@moria:# distccd daemon N15

These daemons will listen on TCP port 3632 for instructions and code from the local machine (the one whichyou are actually compiling software for) The N value sets a niceness level so the distributed compiles won'tinterfere too much with local operations Read the distccd manpage for further options

On the client side, you need to tell distcc which computers to use for distributed compiles You can do this bycreating an environment variable:

dbrick@rivendell:$ export DISTCC_HOSTS='localhost bree moria'

Specify localhost to make sure your local machine is included in the compiles If your local machine is

exceptionally slow, or if you have a lot of processors to distribute the load to, you should consider not

including it at all You can use machine IP addresses in place of names If you don't want to set an

environment variable, then create a distcc hosts file in your home directory to contain the values:

dbrick@rivendell:$ mkdir ~/.distcc

dbrick@rivendell:$ echo "localhost bree moria" > ~/.distcc/hosts

To run a distributed compile, simply pass a CC=distcc option to the make command:

dbrick@rivendell:$ make j7 CC=distcc

It's that simple to distribute your compiles Read the manpages for distcc and distccd to learn more about theprogram, including how to limit the number of parallel makes a particular computer in your farm will

perform

4.15.2 Distribute Compiles to Windows Machines

Though some clever people have come up with very interesting ways to distribute compiles to a Windowsmachine using Cygwin, there is an easier way to perform the same task using a live CD distribution known asdistccKnoppix, which you can download from http://opendoorsoftware.com/cgi/http.pl?p=distccKNOPPIX

Trang 18

Be sure to download the version that has the same major version number of gcc as your local machine.

To use distccKnoppix, simply boot the computer using the CD, note it's IP address, and then enter that in yourdistcc hosts file or environment variable as instructed earlier Happy compiling!

David Brickner

Hack 43 Avoid Common Junior Mistakes

Get over the junior admin hump and land in guru territory

No matter how "senior" you become, and no matter how omnipotent you feel in your current role, you willeventually make mistakes Some of them may be quite large Some will wipe entire weekends right off thecalendar However, the key to success in administering servers is to mitigate risk, have an exit plan, and try tomake sure that the damage caused by potential mistakes is limited Here are some common mistakes to avoid

on your road to senior-level guru status

4.16.1 Don't Take the root Name in Vain

Try really hard to forget about root Here's a quick comparison of the usage of root by a seasoned vet versus

by a junior administrator

Solid, experienced administrators will occasionally forget that they need to be root to perform some function

Of course they know they need to be root as soon as they see their terminal filling with errors, but running su-root occasionally slips their mind No big deal They switch to root, they run the command, and they exitthe root shell If they need to run only a single command, such as a make install, they probably just run

Trang 19

specifically to grant unprivileged access to things that should only be accessible by root!

I was logged into a client's machine (as a normal user, of course), poking around because the user had

reported seeing some odd log messages One of my favorite commands for tracking down issues like this is

ls -lahrt/etc, which does a long listing of everything in the directory, reverse sorted by modificationtime In this case, the last thing listed (and hence, the last thing modified) was /etc/shadow Not too odd ifsomeone had added a user to the local machine recently, but it so happened that this company used NIS+, andthe permissions had been changed on the file!

I called the number they'd told me to call if I found anything, and a junior administrator admitted that he haddone that himself because he was writing a script that needed to access that file Ugh

4.16.2 Don't Get Too Comfortable

Junior admins tend to get really into customizing their environments They like to show off all the cool thingsthey've recently learned, so they have custom window manager setups, custom logging setups, custom emailconfigurations, custom tunneling scripts to do work from their home machines, and, of course, custom shellsand shell initializations

That last one can cause a bit of headache If you have a million aliases set up on your local machine and someother set of machines that mount your home directory (thereby making your shell initialization accessible),things will probably work out for that set of machines More likely, however, is that you're working in amixed environment with Linux and some other Unix variant Furthermore, the powers that be may havestandard aliases and system-wide shell profiles that were there long before you were

At the very least, if you modify the shell you have to test that everything you're doing works as expected onall the platforms you administer Better is just to keep a relatively bare-bones administrative shell Sure, setthe proper environment variables, create three or four aliases, and certainly customize the command prompt ifyou like, but don't fly off into the wild blue yonder sourcing all kinds of bash completion commands, printingthe system load to your terminal window, and using shell functions to create your shell prompt Why not?

Well, because you can't assume that the same version of your shell is running everywhere, or that the shellwas built with the same options across multiple versions of multiple platforms! Furthermore, you might notalways be logging in from your desktop Ever see what happens if you mistakenly set up your initializationfile to print stuff to your terminal's titlebar without checking where you're coming from? The first time youlog in from a dumb terminal, you'll realize it wasn't the best of ideas Your prompt can wind up being longerthan the screen!

Just as versions and build options for your shell can vary across machines, so too can "standard"

commandsdrastically! Running chown -R has wildly different effects on Solaris than it does on Linuxmachines, for example Solaris will follow symbolic links and keep on truckin', happily skipping about yourdirectory hierarchy and recursively changing ownership of files in places you forgot existed This doesn'thappen under Linux To get Linux to behave the same way, you need to use the -H flag explicitly There arelots of commands that exhibit different behavior on different operating systems, so be on your toes!

Also, test your shell scripts across platforms to make sure that the commands you call from within the scriptsact as expected in any environments they may wind up in

4.16.3 Don't Perform Production Commands "Off the Cuff"

Many environments have strict rules about how software gets installed, how new machines are built andpushed into production, and so on However, there are also thousands of sites that don't enforce any such

Trang 20

rules, which quite frankly can be a bit scary.

Not having the funds to come up with a proper testing and development environment is one thing Having ablatant disregard for the availability of production services is quite another When performing softwareinstallations, configuration changes, mass data migrations, and the like, do yourself a huge favor (actually, acouple of favors):

Script the procedure!

Script it and include checks to make sure that everything in the script runs without making anyassumptions Check to make sure each step has succeeded before moving on

Script a backout procedure.

If you've moved all the data, changed the configuration, added a user for an application to run as, andinstalled the application, and something blows up, you really will not want to spend another 40minutes cleaning things up so that you can get things back to normal In addition, if things blow up inproduction, you could panic, causing you to misjudge, mistype, and possibly make things worse.Script it!

The process of scripting these procedures also forces you to think about the consequences of what you'redoing, which can have surprising results I once got a quarter of the way through a script before realizing thatthere was an unmet dependency that nobody had considered This realization saved us a lot of time and somecleanup as well

4.16.4 Ask Questions

The best tip any administrator can give is to be conscious of your own ignorance Don't assume you knowevery conceivable side effect of everything you're doing Ask If the senior admin looks at you like you're anidiot, let him Better to be thought an idiot for asking than proven an idiot by not asking!

Hack 44 Get Linux Past the Gatekeeper

What not to do when trying to get Linux into your server room

Let's face it: you can't make use of Linux Server Hacks (Volume One or Two) unless you have a Linux server

to hack! I have learned from mistakes made by both myself and others that common community ideals aremeaningless in a corporate boardroom, and that they can be placed in a more tiefriendly context when

presented to decision-makers If you use Linux at home and are itching to get it into your machine room, hereare some common mistakes to avoid in navigating the political side of Linux adoption in your environment

4.17.1 Don't Talk Money

If you approach the powers that be and lead with a line about how Linux is free (as in beer), you're likelydoing yourself a disservice, for multiple reasons First, if you point an IT manager at the Debian web site(home of what's arguably the only "totally free in all ways" Linux distribution) and tell him to click around

Ngày đăng: 09/08/2014, 04:22

TỪ KHÓA LIÊN QUAN