Saturday, June 30, 2007

Finding Files in Linux

There are three good methods of finding files in linux:

  1. The slocate database
  2. The whereis command
  3. The find command

The slocate database

To use the locate command, you will need to have a slocate database set up on your system. On many systems it is updated periodically by the cron daemon. Try the slocate command to see if it will work on your system:

locate whereis

Will list all files that contain the string "whereis". If that command did not work you will need to run the command:

slocate -u

This command will build the slocate database which will allow you to use the locate command. This command will take a few minutes to run.

The whereis command

This command will locate binary (or executable) programs and their respective man pages. The command:

whereis linuxconf

will find all binaries and manpages with the name linuxconf.

The find command

The following are examples of the find command:

find /home -user mark


Will find every file under the directory /home owned by the user mark.

find /usr -name *spec


Will find every file under the directory /usr ending in ".spec".

find /var/spool -mtime +40


Will find every file under the directory /var/spool that has data older than 40 days.

Friday, June 29, 2007

Using Linux PAM

PAM stands for Pluggable Authentication Modules. PAM is a library, used to control the function of various applications that have the capability to use the PAM libraries. PAM is based on a series of library modules, some of which depend on configuration files. Locations of PAM configuration files and library modules are:

  • All PAM applications are configured in the directory "/etc/pam.d" or in a file "/etc/pam.conf".
  • The library modules are normally stored in the directory "/lib/security".
  • The configuration files are located in the directory "/etc/security".

To configure PAM, on systems already set up for it, you would need to edit the files for the service you want to modify in the "/etc/pam.d" directory, and modify the appropriate configuration file in the directory "/etc/security". This page will explain how to set up the configuration files and how to configure the modules so applications can use them.

The PAM configuration files

PAM is controlled a main configuration file( /etc/pam.conf) or control directory (/etc/pam.d). Some PAM module's behavior is controlled with configuration files (in /etc/security)as listed below:

  • access.conf - Login access control. Used for the pam_access.so library.
  • group.conf - Group membership control. Used for the pam_group.so library.
  • limits.conf - Set system resource limits. Used for the pam_limits.so library.
  • pam_env - Control ability to change environment variables. Used for the pam_env.so library.
  • time - Allows time restrictions to be applied to services and user privileges. Used for the pam_time.so library.

The main pam.conf file or the /etc/pam.d files

The configuration for PAM is normally in the /etc/pam.d directory which has a file for each PAM controlled application. This file or directory is used to control the behavior of applications that use the PAM modules. Some examples of PAM controlled applications are login, samba, and shutdown. PAM is controlled using the configuration file /etc/pam.conf or the configuration directory, but not both. The directory structure control has precedence. A general configuration line in one of the PAM application configuration file has the following form:

module-type   control-flag   module-path   arguments

If the /etc/pam.conf file is used to control PAM rather than the /etc/pam.d directory structure, the pam.conf lines are the same except they have an additional parameter at the start which is "service-name". The various parameters on each line are:

  1. service-name(not in directory files) - The type of service such as rlogin or ftp.
  2. module-type - The type name of the PAM module used which are
    1. auth - Authenticates the user to be sure they are who they claim to be, usually asking a password then checking it, and setting credentials like as group memberships or kerberos tickets.
    2. account - Check to see if the authentication is allowed based on available system resources such as the maximum number of users or the location of the user. Access could be denied if the account has expired or the user is not allowed to log in at this time of day.
    3. password - Used to set passwords. Typically, there is one module for each auth module-type.
    4. session - Used to make it possible for a user to use their account once they have been authenticated. This module does things that need to be done for the user before or after they can be given service such as logging of information concerning the opening or closing of some data exchange with a user, or mounting directories. This module may make the user's mailbox available.
  3. control-flag
    1. required - The success of the module is required for the module-type facility to succeed. Failure of this module will not be apparent to the user until all of the remaining modules (of the same module-type) have been executed
    2. requisite - If the module returns a failure, control is directly returned to the application. The return value is that associated with the first required or requisite module to fail. This flag can be used to protect against the possibility of a user getting the opportunity to enter a password over an unsafe medium.
    3. sufficient - If this module succeeds and no previous required module has failed, no more `stacked' modules of this type are invoked. This means subsequent required modules are not invoked. A failure of this module is not deemed as fatal to satisfying the application that this module-type has succeeded.
    4. optional - This module is not critical to the success or failure of the user's application for service. In the absence of any definite successes or failures of previous or subsequent stacked modules this module will determine the nature of the response to the application.
  4. module-path - The path and filename of the PAM library used to control the function.
  5. arguments - Arguments are optional and vary from module to module.

My "/etc/pam.d/rlogin" file looks like this:

#%PAM-1.0
auth required /lib/security/pam_securetty.so
auth required /lib/security/pam_pwdb.so shadow nullok
auth required /lib/security/pam_nologin.so
account required /lib/security/pam_pwdb.so
password required /lib/security/pam_cracklib.so
password required /lib/security/pam_pwdb.so nullok use_authtok md5 shadow
session required /lib/security/pam_pwdb.so
session optional /lib/security/pam_console.so

Thursday, June 28, 2007

Linux Configuration

In this section, the configuration tool, "linuxconf" is discussed. This configuration tool provides a means to configure much of the system. In this section, attempts are made to describe the files where this configuration information is stored (unless documented in other sections), however its accuracy cannot be guaranteed, and these files will vary somewhat from one Linux system to another.

When filly expanded, the linuxconf menu includes the following:

  • Config
    • Networking
      • Client tasks
        • Basic host information
        • Name server specification (DNS)
        • Routing and Gateways
          • Defaults
          • other routes to networks
          • other routes to hosts
          • routes to alternate local nets
          • the routed daemon
        • Host name search path
        • Network Information System (NIS)
        • IPX interface setup
        • PPP/SLIP/PLIP
      • Server tasks
        • Exported file systems (NFS)
        • IP aliases for virtual hosts
        • Apache Web server
          • Defaults
          • Virtual domains
          • Sub-directory specs
          • Files specs
          • Modules
          • Performance
          • mod_ssl configuration
        • Domain Name Server (DNS)
          • Config
            • domains
            • IP reverse mappings
            • secondaries
            • forward zones
            • forwarders
            • features
            • IP allocation space
          • Add/Edit
            • host information by domain
            • (quick edit)
          • Security
            • Access control lists
            • Access control
        • Mail delivery system (sendmail)
          • Basic
            • Basic information
            • special (domain) routing
            • complex (user) routing
            • masquerading rules
            • mail to fax gateway
            • virtual email domain
            • the mail queue
            • user aliases
            • virtual domain user aliases
            • /etc/sendmail.cf
          • Anti-spam filters
            • Rehected senders
            • 'Relay for' by IP
            • 'Relay for' by name
            • Relay to hosts
        • Samba file server
          • Defaults
          • Default setup for user's home
          • Default setup for printers
          • Netlogon setup
          • Disk shares
        • Ftp server (wu-ftpd)
          • Basic configuration
          • Virtual hosts
      • Misc
        • Information about other hosts
        • Information about other networks
        • Linuxconf network access
    • Users accounts
      • Normal
        • User accounts
        • Group definitions
        • Change root password
      • Special accounts
        • PPP accounts
        • SLIP accounts via normal login
        • UUCP accounts
        • POP accounts (mail only)
        • Virtual POP accounts (mail only)
      • Email aliases
        • user aliases
        • virtual domain user aliases
      • Policies
        • Password & account policies
        • Available user shells
        • Available PPP shells
        • Available SLIP shells
        • Message of the day - Allows you to type a new message of the day to be displayed on the console when a user logs in. This file is stored in /etc/motd.
    • File systems
      • Access local drive
      • Access nfs volume
      • Configure swap files and partitions
      • Set quota defaults
      • Check some file permissions
    • Miscellaneous services
      • Initial system services
      • Modem
    • boot mode
      • Lilo
        • LILO defaults (linux boot loader)
        • LILO linux configurations
        • LILO other OS configurations
        • default boot configuration
        • a new kernel
        • a kernel you have compiled
      • Mode
        • default boot mode
  • Control
    • Control panel
      • Activate configuration
      • Shutdown/Reboot
      • Control service activity
      • Mount/Unmount file systems
        • Control configured local drives
        • Control configured nfs volumes
        • Mount other NFS file systems
      • Configure superuser scheduled tasks
      • Archive configurations
      • Switch system profile
      • Control PPP/SLIP.PLIP links
    • Control files and systems
      • Configure all configuration files
      • Configure all commands and daemons
      • Configure file permission and ownership
      • Configure Linuxconf modules
      • Configure system profiles
      • Override Linuxconf addons
      • Create Linuxconf addons - This section allows a newly installed package to be managed using linuxconf
    • logs
      • Boot messages
      • Linuxconf logs - Shows all configuration commands issued by linuxconf
    • date & time - Allows the time zone to be set and the time to be set as stored in GMT format or local time. It also lets the time and date to be set.
    • Features - Defines special behavior of linuxconf including the keyboard map (/etc/sysconfig/keyboard), language selection, and html timeout.

Wednesday, June 27, 2007

Linux Configuration and Diagnostic Tools

System and Network Configuration

  • linuxconf - A GUI interactive interface available on Redhat 6.0 or later which includes netconf configuration.
  • netconf - A GUI interactive interface available on Redhat 6.0 and later.
  • kbdconf - A Redhat Linux tool which configures the /etc/sysconfig/keyboard file which specifies the location of the keyboard map file. This is a GUI based tool.
  • mouseconfig - A Redhat Linux tool used to configure the /etc/sysconfig.mouse file. This is a GUI tool.
  • timeconfig - A Redhat Linux tool used to configure the /etc/sysconfig/clock file. This is a GUI tool used to set timezone and whether or not the clock is set to GMT time.
  • kernelcfg - A Redhat kernel configuration utility to be started from X.
  • stty - Used to configure and print the console devices.
  • setterm - Set terminal attributes.
  • vmstat - Report statistics on virtual memory.

X Configuration

  • XF86Setup - A newer X configuration program with a GUI interface which modifies the "/etc/X11/XF86Config" configuration file.
  • xf86config - An older X configuration program with a text based interface. It also modifies the "/etc/X11/XF86Config" configuration file.
  • Xconfigurator - The Redhat tool used during system setup to configure X.
  • SuperProbe - A program that probes the video card to determine its type for use with setting up X.
  • xvidtune - This program will test video modes on the fly without modification to your X configuration. Read the usr/X11R6/lib/X11/doc/VideoModes.doc file before running this program.

Library and kernel Dependency Management

Library management:

  • ldd - Used to determine shared libraries used by binary files. Type "ldd /bin/ls" to see the shared libraries used by the "ls" command.
  • ldconfig - Used to update links and cache for system use of the most recent runtime shared libraries.

Kernel Management:

  • lsmod - List currently installed kernel modules.
  • depmod - Creates a dependency file, "modules.dep" in the directory "/lib/modules/x.x.x", later used by modprobe to automatically load the relevant modules.
  • insmod - Installs a loadable kernel module into the running kernel.
  • rmmod - Unloads modules, Ex: rmmod ftape
  • modprobe - Used to load a module or set of modules. Loads all modules specified in the file "modules.dep".

General Diagnostic

System resources

  • free - Show system memory availability and usage
  • df - Show the amount of disk free space on each mounted filesystem.
  • du - Show disk usage
  • lspci - List PCI devices
  • pnpdump - Lists ISA PNP device resource information.
  • vmstat - Reports virtual memory statistics.

Other:

  • env - List the current environment variables.
  • printenv - Print a copy of the environment.
  • set - Shows how the environment is set up. This command can be very useful when debugging the environment.
  • runlevel - List the current and previous runlevel.
  • uname - Print system information. In my case, it prints "Linux".
  • dmesg - Show the last kernel messages printed during the last boot.

Tuesday, June 26, 2007

Linux Process Control

Tools for working with processes

  • accton - Turns process accounting on and off. Uses the file /var/log/pacct. To turn it on type "accton /var/log/pacct". Use the command with no arguments to turn it off.
  • kill - Kill a process by number
  • killall - Send a signal to a process by name
  • lastcomm (1) - Display information about previous commands in reverse order. Works only if process accounting is on.
  • nice - Set process priority of new processes.
  • ps(1) - Used to report the status of one or more processes.
  • pstree(1) - Display the tree of running processes.
  • renice(8) - Can be used to change the process priority of a currently running process.
  • sa(8) - Generates a summary of information about users' processes that are stored in the /var/log/pacct file.
  • skill - Report process status.
  • snice - Report process status.
  • top - Displays the processes that are using the most CPU resources.

Checking running processes

While logged in as root, type "ps -ax |more" or "ps -aux |more". You will get a list of all processes running on your computer. You will see the process id (PID), process status (STAT) various statistics, and the command name. You can kill a process by typing "kill" and the PID number right afterwards similar to the line below.

kill 1721

You can also stop and restart processes by sending them various signals as in the below examples:

kill -STOP 1721
Stops (suspends) process 1721 by sending the STOP signal to the process. This process will still be on the task list. The process can't catch or ignore the STOP signal.
kill -CONT 1721
Continue process 1721 causing it to resume. The CONT signal is sent to the process.
kill -TERM 1721
Terminates process 1721 by sending the TERM signal to the process. This process will no longer show up on the task list if it is actually terminated. Process terminated cannot be continued. The TERM signal can be caught so TERM is not guaranteed to kill the process.
kill -HUP 1721
Stops, then restarts process 1721. This is usually done when a process is not working properly or the configuration files for that process have been changed. This command sends the HUP signal to the process which means hangup. This signal can be caught by the process.
killall -HUP myprint
Restarts any process with the name "myprint".
kill -TERM myprint
Terminates any process with the name "myprint".

Setting up and doing process control

The examples in this section use the "yes" command as an easy method for an example of a program that runs continually. The "yes" command outputs the string "y" until it is killed or stopped. When the output is ported to the /dev/null (null device or bit bucket), the output is basically dumped. Therefore this command is harmless, but is a good demonstration. To put the process in the background, append an "&" character to the end of the command as shown below.

yes > /dev/null &

The system will respond with a job number and process ID or PID similar to:

[1] 10419

Either number can be used to refer to the job. The "jobs" command can be used to check the job. When the command is entered the system will respond with a list of running jobs similar to the following:

[1]+ Running yes >/dev/null &

The job can be killed using the process ID or the job number. Either

kill %1

or:

kill 10419

Stopping and restarting jobs

Another way to put a job into the background is to

  1. Start the job normally like:
    yes > /dev/null

    The prompt does not come back.

  2. Use the key to stop the job.
  3. Use the command "bg" or "bg %1" where 1 is the job number to put the process in the background. The system reports the job number when you stop the job.
    Before the last step, the job was suspended. The "fg" command could have been used to bring the job into the foreground rather than using the "bg" command to put it in the background. If the job is running in the foreground, you can type &@60Ctrl-C> to terminate the process.

Killing or Reconfiguring a Daemon without Restarting

killall -1 inetd
Restarts inetd by sending signal number 1 which is the hangup signal.
killall -HUP inetd
Causes the daemon to reload its config file by sending the hangup signal. The difference between this example and the previous one is the signal is called by name here rather than number.

To make changes to inetd:

  1. Reconfigure /etc/inetd.conf
  2. Restart inetd by sending it the hangup signal

The easy way to reset a service that was started via the rc script files during system startup:

  1. Find the file for the service, you want to start. For example find the file for the print daemon "lpd". These files should typically be in the directory "/etc/rc.d/init.d". The file name in this case is "lpd". (Note this is a script file, that starts the daemon, not the actual binary daemon file).
  2. Go to that subdirectory "cd /etc/rc.d/init.d" and type "./lpd restart".
  3. You should get output to the screen that indicates this service has been shut down and then started.

Setting process priority

In Linux, processes have a priority number between -20 and 19. The value of -20 is the highest, and 19 is the lowest priority. Process priority can be set with the nice(1) command and changed using the renice(8) command. To set a process to have the highest priority find the process ID number using the ps command. If your process name is "myprog" type:

ps -ax |grep myprog

You should get something like:

756 tty1 S 0:00 myprog

The first number on the line is your process ID. Enter the command:

renice -20 756

This will set your process (PID=756) to priority of -20. Modify the process ID number for that of your program running on your system. You can use the nice command to determine the default priority of new processes by typing "nice" on the command line. If you want to start a process with a specific priority, use the nice(1) command when you invoke the process.

Setting limits on the number of processes that can run

The command "ulimit" is used to limit the number of processes users can run along with available system resources. All processes which will be started from the shell (bash in many cases), will have the same resource limits. See the bash manual page for more information. To set the limits for daemons which are running at boot time add ulimit command to boot scripts.

The command "ulimit -a" reports the current limits.

Monday, June 25, 2007

Linux Passwords

Most versions of Linux come with the shadow password suite of software already installed. This suite of software is recommended to enhance security since all users must be able to access the /etc/passwd file. With full access to this file, a "crack" program can be used by any user to extract all passwords on the system. The shadow password software places the actual encrypted passwords into the /etc/shadow file making this file readable only by the root user. If your system has the file /etc/shadow, you probably already have shadow passwords installed.

Linux Shadow Passwords

If your system did not come with shadow passwords and you are going to install it you will want to read the Shadow-Password-HOWTO and roughly do the following.

  1. Find the latest shadow password suite that will work on your system
  2. Backup a copy of your files listed above that the shadow password suite will replace.
  3. Install the shadow password suite.
  4. Remove old man pages that may interfere with you seeing the correct replacement man pages that came with the shadow password suite.
  5. run pwconv which creates /etc/npasswd and /etc/nshadow
  6. Backup /etc/passwd and copy the files /etc/npasswd and /etc/nshadow to /etc/passwd and /etc/shadow respectively.
  7. Be sure the /etc/shadow and /etc/passwd owners and permissions are the same as shown in listings in this manual.
  8. Verify you can login
  9. When you are sure the system runs OK, remove backup files such as the backed up copy of /etc/passwd.
  10. You may need to upgrade your xlock program to get X working. xlock is the screen saver used to lock the screen.
  11. xdm presents the login screen for X. You may need to upgrade xdm.

Sunday, June 24, 2007

Managing Linux Users

Linux Commands for managing users:

  • adduser(8) - Command used to add user accounts.
  • chage (1) - Used to change the time the user's password will expire.
  • chfn(1) - Change a user's finger information
  • chsh(1) - Change a user's shell.
  • chgrp (1) - Changes the group ownership of files.
  • chown (1) - Change the owner of file(s ) to another user.
  • gpasswd (1) - Used to administer the /etc/group file.
  • groupadd (8) - Create a new group.
  • grpconv (8) - Creates /etc/gshadow from the file /etc/group which converts to shadow passwords.
  • grpunconv (8)- Uses the files /etc/passwd and /etc/shadow to create /etc/passwd, then deletes /etc/shadow which converts from shadow passwords.
  • groupdel (8) - Delete a group
  • groupmod (8) - Modify a group
  • groups (1) - print the groups a user is in
  • grpck (8) - Verify the integrity of group files.
  • id(1) - Print group or user ID numbers for the specified user.
  • newgrp(1) - Allows a user to log in to a new group.
  • newusers (8) - Update and create new users in batch form.
  • nologin (5) - Prevent non-root users from logging onto the system.
  • passwd (1) - Used to update a user's password. The command "passwd username" will set the password for the given user.
  • pwconv (8) - Used to create the file /etc/shadow from the file /etc/passwd to convert to shadow passwords.
  • pwunconv (8) - Uses the files /etc/passwd and /etc/shadow to create /etc/passwd, then deletes /etc/shadow to convert from shadow passwords.
  • su (1) - run a shell with substitute user and group IDs
  • useradd (8) - Create a new user or update default new user information
  • userdel (8) - Delete a user account and their files from the system. The command "userdel -r newuser" will remove the user and deletes their home directory.
  • usermod (8) - Modify a user account.
Other useful commands/examples:
find / -user username -ls
Gives a list of all files owned by username.
chown -R myuser /home/myuser
Changes ownership of all files in mysuer home directory to myuser.
chmod +s filename
Sets the uid

Files

  • /etc/passwd - Where the user's name, and other pertinent information are stored. This includes the password unless your system is using shadow passwords.
  • /etc/shadow - Where the user's password is stored if you are using shadow passwords.
  • /etc/group - Where group names are stored.
  • /etc/aliases - Where the user's name is matched to a nickname for e-mail.
  • /etc/sudoers - A list of users with special privileges along with the commands they can execute.

File Formats

Note group ID numbers start at 100 and user ID numbers start at 500. The file /etc/group gives groups

The /etc/passwd file:

username:password:uid:gid:gecos:homedir:shell
Gecos contains information about the user, including the real name. Shell is the name and path of the user's default shell program.

The /etc/group file:

groupname:password:gid:members
If the entry "bigclown:*: mark,george" is in the group file, the users mark and george are members of the bigclown group.

Examples

To add a user, while logged in as root, type "adduser username".
To set a user password, while logged in as root or the user that will be changed, type "passwd username". If "passwd" is typed, the password will be changed for the user, you are logged in as.
To remove a user, while logged in as root, type "userdel -r username". This will remove the user's home directory. You can delete the user without the "-r" option and delete the user's home directory manually. If the group the user was in, is no longer needed, you may delete it by editing the "/etc/group" file.

The file "/etc/aliases" is where the user's real name is matched to their user name for e-mail accounts. Add users to this file in the form:

Firstname,Lastname:username

Then update the database by typing "newaliases".

User Process Accounting

Process accounting is supported by new kernels. To use this feature, you'll need to get the acct-1.3.73.tar.gz package or later. The package contains some programs used to manage users. The following commands are useful for user accounting:

  • ac(1) - Print statistics about users' connect time.
  • accton (8) - Turn on accounting of processes. To turn it on type "accton /var/log/pacct".
  • last(1) - Shows a list of users who have logged in.
  • lastb(1) - Shows failed login attempts. This command requires the file /var/log/btmp to exist in order to work. Type "touch /var/log/btmp" to begin logging to this file.
  • lastcomm (1) - Display information about previous commands in reverse order. Works only if process accounting is on.
  • sa(8) - Generates a summary of information about users' processes that are stored in the /var/log/pacct file.
  • utmpdump(1) - Used for debugging.
  • who(1) - Find out what users are logged onto the system.

Files that hold accounting information

  • /var/log/wtmp - Stores information about all logins and logouts.
  • /var/run/utmp - Stores information about who is currently on the system and is used by the who command.
  • /var/log/btmp - Used to store information about failed logins.

The /var/log/wtmp file, contains the following information:

  • Type of Login
  • Process ID of login process
  • The device name of the tty used
  • The init ID or abbreviated ttyname
  • User Name
  • Hostname for remote login
  • Exit Status of a process
  • The session ID
  • The time entry was made
  • IP address of remote host

See the man page for wtmp(5) for more information.

The ability to set quotas limits a user's disk storage by setting:

  1. The number of inodes the user or group may use.
  2. The number of disk blocks a user or group may use.

This limits user's ability to use up all system resources. It only works on ext2 filesystems. Quotas must be set for each filesystem that the user may use. The kernel must have quota support compiled in.

User Quotas

The ability to set quotas limits a user's disk storage by setting:

  1. The number of inodes the user or group may use.
  2. The number of disk blocks a user or group may use.

This limits the user's ability to use up all system resources. It only works on ext2 filesystems. Quotas must be set for each filesystem that the user may use. The kernel must have quota support compiled in.

Commands used to set quotas and limits are:

  • edquota(8) - Used to edit user or group quotas. This program uses the vi editor to edit the quota.user and quota.group files. If the environment variable EDITOR is set to emacs, the emacs editor will be used. Type "export EDITOR=emacs" to set that variable.
  • quota(1) - Display users' limits and current disk usage.
  • quotaoff(8) - Turns system quotas off.
  • quotaon(8) - Turn system quotas on.
  • quotacheck(8) - Used to check a filesystem for usage, and update the quota.user file.
  • repquota(8) - Lists a summary of quota information on filesystems.
  • ulimit - A bash builtin command for setting the processes a user can run. The command "ulimit -n 9000" will set the limit on open files to 9000.

Files:

  • /etc/mtab
  • quota.user - Resides on the filesystem quotas are being set on.
  • quota.group

Read the Quota mini howto for more information. Here's roughly what is needed to enable and set quotas:

  1. In your startup scripts, you should use the quotacheck and quotaon commands to start quota checking at system startup. Read the "How Linux Works" or the "Linux Startup Manual" for more information on startup scripts. This is already setup properly in most current versions of Linux.
  2. In the /etc/fstab file, add the mount options "usrquota" and "grpquota". You only need "grpquota" if you are going to set group quotas also. An example entry:
    /dev/hda2       /    ext2    defaults,usrquota,grpquota       1       1
  3. Issue the following commands, where "fs" is the name of the filesystem where quotas are to be set. The first two commands create the quota files, and the second two commands keep users from accessing those files.
    touch /fs/quota.user
    touch /fs/quota.group
    chmod 600 /fs/quota.user
    chmod 600 /fs/quota.group
  4. If you use emacs rather than vi to edit files, type "export EDITOR=emacs". You may want to add this command to your shell startup script such as $HOME/.bash_profile.
  5. Type "edquota username" to edit the quota file. You get a screen like this:
    Quotas for user george:
    /dev/hda2: blocks in use: 10672, limits (soft = 0, hard = 0)
    inodes in use: 1856, limits (soft = 0, hard = 0)
    /dev/hda3: blocks in use: 0, limits (soft = 0, hard = 0)
    inodes in use: 0, limits (soft = 0, hard = 0)

    Enter the limits you want to set and save the file. The soft limits are those that may be exceeded for limited periods of time, and the hard limits may not be exceeded.


Saturday, June 23, 2007

Keys and Linux Terminal Configuration

To really understand and work with key mapping, you should read the "Support for text" section in the "How Linux Works CTDP Guide". It explains how terminal types are set and the different layers of keymapping along with how to map keys for various applications. Linux keymapping is complex and this section will just give you a short explanation of the various utility programs available, and how to do some specific keymapping. If you must perform custom keymapping, the "How Linux Works CTDP Guide" is necessary.

Linux keymapping is performed on several levels and many programs such as the shell, less, and emacs have their own support for keymapping. Other programs such as terminal programs use the terminfo or termcap database for keymapping. The main system wide keymapping the user may deal with is keymap which maps the keycode to a set of ASC characters that each keystroke will produce. A file is created which contains these specific keymappings and it is loaded with the command "loadkeys". There is a man page describing the structure of this file. It can be accessed by typing "man keymaps". There are many symbols in this file that describe values for keys. You can see the value of many of them by typing "dumpkeys --long-info" or "dumpkeys -l". Once the keymap file is created, the easy way to permanently modify the key settings for the system is to modify the file /etc/sysconfig/keyboard to a new default value such as KEYTABLE="/etc/sysconfig/console/mykeymap".

Console key utilities and files

  • Kernel keyboard driver
    • kbd_mode - Report or set the keyboard mode to -s (scancode mode, RAW) -k (keycode mode, MEDIUMRAW) -a (ASC mode, XLATE) -u (UTF-8 mode, UNICODE). XLATE is default.
    • kbdrate - modify the keyboard repeat rate and delay time after keypress.
    • kbdconf - Configures the /etc/sysconfig/keyboard file which specifies the location of the keyboard map file.
  • For system key mapping make codes to keycodes
    • setkeycodes - used to set a translation between unusual scancodes and keycodes. This utility is not usually needed.
    • getkeycodes - Print the kernel scancode to keycode mapping table.
  • Mapping keycodes to keymaps
    • dumpkeys - dump keyboard driver translation tables in the format specified by keymaps. The output of this program will look similar to the keytable file in "/usr/lib/kbd/keytables/*.map" and the output can be saved to a file, and used to generate a new file to be used with the "loadkeys" command.
    • loadkeys - Load the keyboard translation table into the system from a specified file. Type "loadkeys -d" or "loadkeys defkeymap" to load the default keymap. Changes keys for all virtual consoles. The keyboard translation table set in the kernel (compiled in) is in the file "/usr/src/linux/drivers/char/defkeymap.map". To change the kernels keymap without having to load a new table after booting, you must modify the file, then re-compile the kernel. You would only need to do this to modify keymaps for remote boot systems that don't have access to all system programs.
    • setmetamode - define the keyboard meta key handling. Controls whether the keystroke , would send the keycode M-key or the key sequence ESC followed by key. You can have different setting in different virtual consoles.
  • Debugging tools
    • showkey - Examine the scancodes and keycodes sent by the keyboard. Options are -s (show scancodes) -k (show keycodes, default) -m (show keymap). This program outputs key values that the user presses on the keyboard. The program terminates when no keys are pressed for 10 seconds.
  • Termcap and terminfo
    • tic - Compiler for terminfo.
    • infocmp - Used to examine terminfo files.
    • /etc/termcap - The termcap database file.
    • /usr/share/terminfo - The directory structures containing the terminfo compiled database.
  • Other tools
    • consolechars - Load console screen font (was called setfont). The directory "/usr/lib/kbd/consolefonts/" is the default directory for fonts. "/usr/lib/kbd/consoletrans" is the default directory for ACM's and SFM's.
    • psfaddtable - Add a Unicode character to a console font.
    • psfgettable
    • pfsstriptable
  • For terminals and terminal key mapping
    • mesg - Use to turn others' write messaging ability to your terminal by on and off. "mesg on" to turn it on.
    • stty - Print or change the terminal line settings.
    • setterm - Set terminal attributes.
    • tput - Initialize a terminal or query terminfo database.
    • setleds - Set or output the keyboard LED settings for caps lock, num lock, and scroll lock.
    • setfont - Never use unless you know what you are doing. There is no man page for this command.
    • chvt - Change virtual terminal. Usage: chvt3.
    • deallocvt - De allocate unused virtual terminals
  • For X
    • xmodmap - Used to modify keymaps and pointer button mappings in X. Map X keycodes to keysyms. Usage "xmodmap mykeys.map".
    • xkeycaps - A GUI front end to xmodmap.
    • xev - Allows you to see key make and breaks generated on a window.
    • showfont - font dumper for X font server
    • xset - Set user preferences for the display.
    • /etc/X11/xinit/Xmodmap or $HOME/.Xmodmap - File(s) that can be uset to set keycode mapping in X
    • $HOME/.Xinitrc - A file run when X starts that is a script file. The program "xmodmap" can be invoked in this file to set keymappings for X.
    • $HOME/.Xresources - Another file where keymappings may be changed for X.
  • Bash
    • /etc/inputrc or $HOME/.inputrc - Where Bash keymapping is done.
  • Less
    • $HOME/.lessrc - Where keymapping is done for less.
  • Emacs
    • $HOME/.emacs - Where keymapping is done for emacs.
  • tsh
    • bindkey - A program supplied by tsh to allow for binding keymaps.
    • $HOME/.cshrc

Setting Keystrokes

The stty command - Used to set up keystrokes on terminals
The command will bind the Backspace key(^H) to the erase function.
Characters that are specified:

  • eof - End of file
  • eol - End of line
  • eol2 - Alternate character for ending a line
  • erase - Erase the last character typed
  • intr - The specified character will send an interrupt signal
  • kill - Erase the current line.
  • quit - Sends a quit signal.
  • start - Restart output after having stopped it.
  • stop - Stops the output.
  • susp - Sends a terminal stop signal
  • switch - Switch to a different shell layer
  • werase - erase the last word typed.
setterm -foreground white - background blue
Sets white foreground, and blue background
setterm -store
Stores the present terminal values as default

Keys and terminal configuration

Special command line keys:

  • CTRL U - Delete the line
  • CTRL C - Abort command
  • CTRL Z - Suspend command, Type fg to put it back into the foreground
  • - Auto complete command
  • F1 through F6 - Select a different virtual terminal
  • F7 - Toggle to the first X terminal, if one is running.
  • F1 - Toggle to the first text terminal from an X session.
  • CTRL D - End of file, exits the shell
  • CTRL W - Delete a word backwards
  • CTRL / - Quit, weaker than CTRL C but does a core dump.
  • CTRL S - Stop scrolling, may use "scroll lock" for this function.
  • CTRL Q - Resume scrolling

Emacs keymapping

To modify the keymap in emacs so pressing the end key will move the cursor to the end of a line rather than the end of file, add the following lines to your user's $HOME/.emacs file:

(define-key function-key-map "\e[4~" [end])
(global-set-key [end] 'end-of-line)

Friday, June 22, 2007

Configuration, Logging, and CRON

Linux System Configuration

In the subdirectory "/etc/sysconfig" are groups of files describing your system as follows:

  • mouse - Describes the type of mouse and whether a three button mouse is emulated.
  • keyboard - Describes the keyboard table.
  • network - Describes if this machine supports networking, IP forwarding, sets the host name, sets the gateway, and describes the network interface the gateway will be found on.
  • hwconf - Describes the hardware devices on your system in terms of vendor ID and device ID.
  • init - Defines many initialization items for the system.
  • static-routes - Defines the static routes if your machine is performing routing tasking. See the Networking Guide section on routing.
  • Subdirectories:
    • console - Defines your system keymapping. Normally contains the default.kmap file which is loaded when the system starts.
    • network-scripts - This directory contains files used to configure your ethernet card. such as ifcfg-eth0, ifcfg-eth1, etc. In this file you set your permanent device name, IP address, netmask and other parameters.

For more information on setting these files up and how they are formatted, read "How Linux Works".

The /proc filesystem and the sysctl utility

The /proc filesystem is used to store many system configuration parameters. It is a virtual filesystem that resides in the kernels memory. Some of the areas in this filesystem cannot be written to by the root user including /proc/sys.

To see how much memory linux is using type:
cat /proc/meminfo
or:
free
cat /proc/cpuinfo
To see information about your cpu
cat /proc/interrupts
List interrupts in use
cat /proc/version
List Linux version
cat /proc/filesystems
List the types of filesystems in use
lsmod
Show the kernel modules currently loaded


The "sysctl" program will list kernel parameters. Type "sysctl -a |more" to see a list of kernel parameters on your system.

For more in depth information on the proc filesystem, read "How Linux Works".

Linux System logging

The system daemon called syslogd is the program used to log system events such as kernel messages, login or logout messages, general system messages, etc. The /etc/syslog.conf file controls where logging information is recorded by syslogd. This file controls where your logfiles are kept. Typically these files are in the "var/log" directory.

My "/etc/syslog.conf" file"

 # Log all kernel messages to the console.
# Logging much else clutters up the screen.
#kern.* /dev/console

# Log anything (except mail, news and auth) of level info or higher.
# Don't log private authentication messages!
*.info;mail.none;news.none;authpriv.none /var/log/messages

# The authpriv file has restricted access.
authpriv.* /var/log/secure

# Log all the mail messages in one place.
mail.* /var/log/maillog

# Everybody gets emergency messages, plus log them on another
# machine.
*.emerg *

# Save mail and news errors of level err and higher in a
# special file.
uucp,news.crit /var/log/spooler

# Save boot messages also to boot.log
local7.* /var/log/boot.log

#
# INN
#
news.=crit /var/log/news/news.crit
news.=err /var/log/news/news.err
news.notice /var/log/news/news.notice

The first field is a facility followed by a "." with the second field being the priority such as "uucp,news.crit" above where the facility is uucp and news and the priority is crit. The last part of each line specifies the name of the log file where that log will be kept. This file does not like spaces in it so use tabs between sections.
Facilities are:

  • authpriv, auth (depreciated) - Security authorization messages
  • cron - The clock daemon (cron and at)
  • daemon - Other system daemons
  • kern - Kernel messages
  • lpr - Line printer subsystem
  • mail - Mail subsystem.
  • mark - For internal use
  • news - Usenet news subsystem.
  • security (depreciated, same as authpriv) - should not be used anymore.
  • syslog - Messages generated internally by syslogd.
  • user - Generic user level messages
  • uucp - UUCP (Unix-Unix copy) subsystem.
  • local0 through local7

The ``authpriv'' facility should be separated from other log data, including attempts to switch users using /bin/su, login attempts, and other user accounting information.

Priority is one of the following with the least severity listed first:

  • debug - Debug level message
  • info - Informational message
  • notice - Normal but significant conditions
  • warning, warn (depreciated) - Warning conditions
  • err, error (depreciated) - Error conditions
  • crit - Critical conditions
  • alert - Action must be taken immediately
  • emerg, panic - System is unusable

An "*" stands for all facilities or all priorities. Many distributions default to only logging the most basic information. You may want to customize system logging for your environment.

Linux Logrotate

Going hand in hand with the system logging capability is the logrotate capability which is used to manage logfiles. The logrotate program is used to rotate, compress, and/or mail system log files. It is normally run from cron. It can be configured with the file "/etc/logrotate.conf" which is specified on the command line when logrotate is run.. The logrotate configuration file on my system is listed below:

 # see "man logrotate" for details
# rotate log files weekly
weekly

# keep 4 weeks worth of backlogs
rotate 4

# send errors to root
errors root

# create new (empty) log files after rotating old ones
create

# uncomment this if you want your log files compressed
#compress

# RPM packages drop log rotation information into this directory
include /etc/logrotate.d

# no packages own lastlog or wtmp -- we'll rotate them here
/var/log/wtmp {
monthly
create 0664 root utmp
rotate 1
}

/var/log/lastlog {
monthly
rotate 1
}

# system-specific logs may be configured here

Some of the logrotate configuration directives include:

  • daily - log files are rotated every day
  • weekly - log files are rotated once a week.
  • monthly - log files are rotated once a month
  • rotate - The number of times log files are rotated before being deleted or mailed to an address specified in a mail directive.
  • include - Includes a file in this file as though it were in line. If the file is a directory, the files under that directory are included. In my copy above, there are several files under the directory "/etc/logrotate.d" which are used for logging various daemons.
  • create - "create mode owner group". Creates the file with the specified mode, owner and group ids.
  • copytruncate - truncate the original file after creating a copy so programs appending data will not have a problem.
  • compress - Old versions of the log file are compressed with gzip.
  • nocompress - Old log files are not compressed.
  • errors - Any errors during logfile processing are mailed to the address "errors address".
  • mail - When a log is rotated out of existence, it is mailed to the specified address "mail address".

There are many other directives associated with the logrotate program. Type "man logrotate" for more information.

Other system tracking files:

/var/log/wtmp - Binary info on users that have been logged on. The last command uses this info.
/var/run/utmp - Binary info on users currently logged on. The commands who, w, and finger use this info.
/var/log/lastlog - Used by finger to tell when a user was last logged in

Scheduling tasks with CRON

Cron runs commands in the /etc/crontab file, the /etc/cron.d directory, and /var/spool/cron directory that has file names of authorized users in the /etc/passwd file. Cron commands are scheduled in three locations:

  • The directory "/var/spool/cron" with files named after accounts in "/etc/passwd". The format of files here is described in the crontab(1) manpage.
  • The directory "/etc/cron.d". The format of files here is described in the crontab(5) manpage.
  • The file called "/etc/crontab". The syntax of each line in this file is:
minute, hour, day of month, Month, day of week, (user name), command

Months are specified using the numbers 1 through 12. The user name is included it the file is a system crontab file. Some example entries are listed below:

Some example crontab entries are:

*/10 * * * * root /sbin/rmmod -as
Every 10 minutes all unused kernel modules are unloaded.
0 1 * * * find /tmp -atime 3 -exec ls -l {} \;
Lists files in /tmp that are 3 or more days old, Run at 1:00
0 12 * * mon,tues,wed,thurs,fri ls -al
Lists files at noon on weekdays.

Redhat comes with the following entries:

01 * * * * root run-parts /etc/cron.hourly
Hourly task list, runs at 1 minute after the hour
02 4 * * * root run-parts /etc/cron.daily
Daily task list, runs at 4:00AM, 2 minutes after the hour
22 4 * * 0 root run-parts /etc/cron.weekly
Weekly task list, runs at 4:00AM, Sunday 22 minutes after the hour
42 4 1 * * root run-parts /etc/cron.monthly
Monthly task list, runs at 4:00AM, On the first of the month, 42 minutes after the hour

Note that for weekly and monthly tasks the number of minutes after the hour is staggered so the system does not try to do all jobs at once. Redhat therefore has the following additional directories each containing files with tasking:

  • /etc/cron.hourly
  • /etc/cron.daily
  • /etc/cron.weekly
  • /etc/cron.monthly

These files are directories. Therefore you can place any executable program in one of these directories and it will be run as scheduled above.

There is a crontab program which can be used to install, de install, or list tables used to drive cron. It has the same name as the configuration file, but is a binary program. You will see this if you type "whereis crontab".

Cron runs the following on my system:

  • cron.hourly
    1. In the file "inn-cron-nntpsend" the command "/sbin/chkconfig innd && su - news -c /usr/bin/nntpsend" is run to support internet news service.
  • cron.daily
    1. In the file "inn-cron-expire" the command "/sbin/chkconfig innd && su - news -c "/usr/bin/news.daily delayrm" " is run.
    2. In the file "inn-cron-expire" the command "/sbin/chkconfig innd && /usr/bin/rnews -U" is run.
    3. In the file "logrotate" the command "/usr/sbin/logrotate /etc/logrotate.conf" is run.
    4. In the file "makewhateis.cron" a file "/var/lock/makewhatis.lock" is created to keep the cron scripts from stepping on each other. Do a man on makewhatis for more info.
    5. In the file "slocate.cron" the command "/usr/bin/slocate -u -f "nfs,smbfs,ncpfs,proc,devpts" -e "/tmp,/var/tmp,/usr/tmp,/afs,/net" " is run to update the file location database.
    6. In the file "lsrnpull-expire" the command. Do a "man slrnpull" for more info.
    7. In the file "tetex.cron" TeX formats not used for 10 days are removed. "man tmpwatch"
    8. In the file "tmpwatch"
  • cron.weekly
    1. In the file "makewhateis.cron" a file "/var/lock/makewhatis.lock" is created to keep the cron scripts from stepping on each other. The makewhatis command updates the apropos database which is the database used when the command "man -k" is used. For more information, type "man whatis" or "man apropos".
  • cron.monthly contains no files

The system administrator can schedule tasks by adding entries to the /etc/crontab (see crontab(5)) file or on Redhat Linux, by adding entries in one of the cron.hourly, cron.daily, cron.weekly, or cron.monthly files. Users may be able to schedule cron jobs if the system is configured to allow it. If neither of the /etc/cron.allow nor the /etc/cron.deny files exist, either all users will be able to run cron commands or no users will be able to do it. If /etc/cron.allow exists, the user must be listed there in order to use cron commands. If /etc/cron.deny exists, the user must not be listed here or they will be unable to use cron.

One useful entry you can put in the /etc/cron.weekly directory in a file named something like "cleanold.cron" is:

find /var/spool/myspools -mtime +33 -exec rm -f {} \;

This entry will remove all files in the /var/spool/myspools directory whose data was changed more than 33 days ago.

The user (if allowed) can schedule cron tasks by following the below procedure:

  1. Make a crontab file called for example "mycron".
  2. Use the crontab(1) command to submit the command(s) to cron by typing "crontab mycron".
  3. You can view what you have installed by typing "crontab -l".

crontab commands:

crontab -e
Starts vi session by default to edit your crontab file. To use emacs as your editor, type "export VISUAL=emacs" before typing this command. When you exit the editor, the modified crontab is installed automatically.
crontab -r
Removes your crontab entry from the /var/spool/cron directory. Does not erase your original crontab file.
crontab -l
Lists all the user's cron tasks.

To use emacs, type "export VISUAL=emacs" before starting crontab.

Thursday, June 21, 2007

Linux Package Installation and Printing

Generally, a large part of Linux consists of the packages you load on your system. These packages may be for various specific purposes such as adding shadow passwords, adding a secure telnet client, adding some type of network service, or perhaps upgrading the Apache web server. Whatever the reason, you will need to find the appropriate package on the web, download it, compile it, and install it. The package will come with instructions on how to do this. Some are easy to install, others may be complicated. This section gives general instructions commonly found and required when installing many packages. Please be aware, however, that there may be differences between these instructions and those that come with your package. You should read the instructions that come with your package.

Package installations

tar.gz source package general instructions

  1. Read the install documentation associated with the installation
  2. Put the packed file in the directory you want it to be installed under.
  3. Examine the package with the command "tar tvzpf .tar.gz" to see where it will install.
  4. Unpack the tar.gz file in one step with "tar xvzpf .tar.gz or in two steps with "gunzip .tar.gz" and "tar xpf .tar" It will create a directory like "packagename-2.3.4" and place the extracted information here.
  5. Typically the following outlines the rest of the steps but they will vary from package to package. Go into the created subdirectory and type "./configure".
  6. Type "make all" or "./make"
  7. Type "make install" or "./make install"
Installing Redhat Packages
rpm -help
To get help
rpm -q mypack-1.0.1.rpm
Queries the database of installed packages to see if this package is installed or what version of it is installed.
rpm -ivh mypack-1.0-1.rpm
Installs mypack.
rpm -uvh mypack-2.0-1.rpm
Upgrades mypack.
rpm -qip mypack-1.2.2.rpm
To query with details about the package.
rpm -qlp mypack-1.2.2.rpm
Gives a list of files this package installs.
rpm -e mypack-1.2.2
Removes the package mypack-1.2.2.

Typically RPM packages come with binary files ready for installation so all you need to do is the install as in the line above. The compilation which is the last three steps in the tar example in the first section above don't need to be done. If you get a source file rather than a binary file, you will need to do a compile of code and an installation. If you just do the binary installation, be sure you get the package from a reliable source so you don't get lovely extras like trap doors, trojans, or viruses.

Setting Linux Print Spooling

Printing is supported by "lpd" the line printer spooler daemon, which you should activate to support print services. Once print services are setup, type "lpr ?s -Pprinter filename" where "printer" is the name of your printer (the default is lp). The '-s' option tells lpr to use symbolic links to print the file rather than copying it to its own spool file. If the '-P' option is left out, the default printer name will be assumed.

Print spooling can be set up easily in Redhat using the "printtool" configuration tool following the following steps:

  1. Type "startx" to enter an x windows session.
  2. Open a terminal under x windows
  3. Type "printtool" in the terminal and CR.
  4. Edit or add a printer. Note that lp is the default printer for the lpd daemon.
  5. You can make the name of the printer anything you want. Note: lp is default.
  6. The spool directory should be "var/spool/printername"
  7. The printer server name should be the name of the server computer that the printer is attached to. Example PRT_SRV1
  8. The print queue name is the name of the printer as the printer server computer perceives it. Example: HP_LASER1.
  9. Depending on the network and how the printer resource is shared you may or may not need a user name and password.

How it works:

  1. Note the file "/etc/printcap" defines what filter script file will be used to output the printfile. Type "man lpd" and "man printcap" for more information.
  2. The filter script gets its input from standard input sometimes using such commands as "cat -", see the cat man page. It also uses "file -" to get a description of the input.
  3. On netware print servers, you must be logged on before it will work. I use the scripts from the section on "Network printing setup and use" to logon and type "neton username".

Other useful commands for printing:

lpr - Prints a file to default lp printer
lpq - shows files to print in the print que
lpc - Line printer control program. Type "lpc status" to see status on all printers. This command can enable or disable printing or queuing.
lprm - Remove a job from the print queue using number reported by lpq. Ex: lprm 14
tunelp - A utility to optimize the printer. "tunelp /dev/lp -q" will display the IRQ for the device

The directory /var/spool/lpd contains a directory for every printer. This is where the print files are spooled.

To set up a printer on a parallel or serial port:
A printer on the first parallel port is probably /dev/lp0 or /dev/lp1.
To test the printer type "lptest > /dev/lp1" to send test output directly to the printer. If the printer is a postscript printer you need to send it a postscript file by typing "cat test.ps > /dev/lp1". The lptest program is a utility made to test a printer.
If the printer is serial, output is directed to /dev/ttyS0 or /dev/ttyS1.

The /etc/printcap file:
The printcap file begins a comment line with #
Example:

ljet4|lp|ps|Postscript|600dpi 20MB memory|end of hall|local|LPT1:\
:lp=dev/lp0:rw:\
:sd=/var/spool/lpd/ljet4:mx#0:mc#0:pl#72:pw#85:\
:lf=/var/log/lpd-errs:if=/usr/local/cap/ljet4:

On the first line (virtual), the names of the printer are shown with each name separated by '|'.
Commands include:

  • The lp line is the device name for output (local printer).
  • rw is specified if the printer can send data back to the host through the device file. A network printer uses /dev/null.
  • mx - Sets the maximum size of a print job.
  • pl - page length.
  • pw - page width.
  • The sd line is the subdirectory the files are spooled in
  • The if line tells the input filter to use
  • br-baud rate for a serial port
  • sh-suppress header
  • rp-remote printer
  • rm-remote host that controls remote printer
  • rs- restrict access to local printers to users with an account
  • rg-restricted group that can use the printer

Wednesday, June 20, 2007

Linux Kernel

The Kernel and its Modules

Most kernels are compiled so modular support is required except many used on floppy boot disks.
The package modules.tar.gz contains all the programs needed to manage modules. This should already be installed on most distributions. The kernel modules are usually in a directory pertinent to the kernel version in /lib/modules. Modules can be found in "lib/modules/2.2.12-20" for kernel version 2.2.12-20. They are loadable modules ending in ".o" that are used to support the kernel.
To load a module type "insmod module" where "module" is the name of the module to load. Ex: insmod /lib/modules/2.2.12-20/misc/ftape.o

Programs used to manage modules are:

  • lsmod - Lists all the currently loaded kernel modules
  • rmmod - Unloads modules, Ex: rmmod ftape
  • depmod - Creates a dependency file, "modules.dep", later used by modprobe to automatically load the relevant modules.
  • modprobe - Used to load a module or set of modules. Loads all modules specified in the file "modules.dep".

Modules are loaded from startup script files using "modprobe" to handle loadable modules automatically.


modprobe -l |more
Lists all the modules available for your kernel
rmmod module_name
Remove a module from the kernel

Finding the Kernel

Locate the kernel image on your hard disk. It should be in the file /vmlinuz, or /vmlinux. In some installations, /vmlinuz is a soft link to the actual kernel, so you may need to track down the kernel by following the links. On Redhat 6.1 it is in "/boot/vmlinuz". To find the kernel being used look in "/etc/lilo.conf".

Type "uname -a" to see the kernel version.

Compiling the Kernel

  1. Backup the present kernel which is in "/boot" for most systems. You can tell where it is by looking at "/etc/lilo.conf" . sometimes lilo.conf will point to a link file. Trace the link file and backup the file being pointed to.
  2. Have an alternate way to boot such as another linux system on your computer or an emergency boot disk that you can access your filesystem from in case your new kernel crashes.
  3. Back up your kernel modules in the directory "/modules". There is probably a directory full of modules so you should be able to back it up using "cp –dpr dir1 dir2" where dir1 is the name of the directory where your modules are and dir2 is where you want to put them.
  4. Go to "/usr/src/linux". There is a "/usr/src/linux/.config" file used to do the compile. It is modified by typing "make config" and the values in it are used to determine defaults while doing the "make config". Back this file up to keep your original settings if you want.
  5. Type "make config" and answer the hundreds of questions asked. On another terminal, open the file "/usr/src/linux/Documentation/Configure.help" to determine what each configuration is. Also you can type "make menuconfig" or from an X session "make xconfig".
  6. Type "make dep"
  7. Type "make clean"
  8. Type "make bzImage" or "make zImage" if the kernel is small.
  9. Type "make modules"
  10. Type "make modules_install"
  11. Copy the file "/usr/src/linux/arch/i386/boot/bzImage" to "/boot/vmlinuz".
  12. Copy the file "System.map" from "/usr/src/linux" to the "/boot" directory. Rename it "System.map=w.x.y" and make sure there is a link file called "System.map" pointing to it. This step will keep you from getting warning messages when you boot. It seems to be a step they forgot to include in the kernel-howto.
    • cp /usr/src/System.map /boot/System.map-2.2.14
    • cd /boot
    • rm System.map
    • ln –s System.map-2.2.14 System.map
  13. Run rdev on the new kernel image to verify the root filesystem device. "rdev /boot/vmlinuz /dev/hda2". Please note that this step may be optionally dependent on whether you want to use the boot loader, lilo, to point to the root device.
  14. Make sure the /etc/lilo.conf file is correct (image=/boot/vmlinuz)
  15. If your kernel has a feature supported by a module that is required to boot, you will need to make a RAM disk boot image or your system won't boot.
    • Type "lsmod" and look to see if the "loop" module is loaded. If it is skip the next step.
    • Type "insmod /lib/modules/2.2.14/block/loop.o"
      Use this command if the loopback module is not installed. This assumes you compiled the support into your kernel. In my example, I used kernel version 2.2.14, but your kernel version may have a different number. Substitute the appropriate values.
    • Type "mkinitrd /boot/initrd-2.2.14.img 2.2.14"
      Again, this example is for kernel version 2.2.14. This command will create a RAM image module for your kernel to load into.
    • Add an entry similar to "initrd=/boot/initrd-2.2.14.img" to the "/etc/lilo.conf" file for the stanza that is used to boot this kernel. An example of the stanza follows.
       image=/boot/vmlinuz
      label=rhl
      initrd=/boot/initrd-2.2.14.img
      read-only
      root=/dev/hda2

      Read the section about LILO for more information or read the lilo and lilo.conf man pages.

  16. Run lilo by typing "lilo". If you didn't set the root device in step 12, you will need a line like "root=/dev/hda2" in /etc/lilo.conf in the group of commands for your kernel. This will tell the kernel where your root filesystem is.

This step may be necessary if you are using a kernel previous to the 2.2 series. In the directory "/usr/include" may be several link files such as "asm", "linux", and "scsi". These are normally softlinks through "/usr/src/linux". If they are, you can direct the softlink file "usr/src/linux" to your new kernel file which may be in the form "linux-2.2.14". If you don't have the "linux" softlink file and don't want to create it, you will need to remove and redirect the softlink files in "/usr/include" to the proper location of your new kernel source.

The sysctl tool

This tool is worth mentioning in this section since it is used to manipulate kernel parameters. If you type "sysctl -a |more" you will see a long list of kernel parameters. You can use this sysctl program to modify these parameters. However, I have been unable to add new parameters.

Tuesday, June 19, 2007

Linux Environment Settings, Shell Selection and Startup Scripts

Linux Environment Variables and Settings

There are many environment variables, some of which are listed below. The command used to add or modify environment variables is the export builtin command provided by the bash shell. See the bash(1) man page for more information on this built in command.

PS1="[\u@h \w]\\$ "
Used to set the command line string to output user,machine and name of directory the user is in. In Redhat, to effectively change this value, it must be changed in the file "/etc/bashrc" and in "/etc/profile".
export PATH=$PATH:/usr/sbin
Adds /usr/sbin to the path in the system environment
MANPATH
Sets the path for man pages

Other environment variables include:

  1. USERNAME
  2. HOSTNAME
  3. LOGNAME
  4. MAIL
  5. EDITOR - Specifies the editor to be used by default for some commands such as edquota. Usually it is set to vi or emacs with a command like "export EDITOR=emacs".
  6. TERM - The type of terminal being used.
  7. PATH - The path the system looks in to find commands that the user has entered.
  8. HOME - The current user's home directory
  9. SHELL - The current shell program that is being executed
  10. USER - The name of the current user.
  11. TMPDIR - Allows programs that use the tempnam(3) function call to use the directory specified by this variable rather than the /tmp directory.
  12. SHLVL - Shows how many shells the user has invoked.
You can type "env" to see a listing of all current environment variables.
SHLVL indicates how many shells deep the user is. If the level is 2, you must type "exit", then logout to exit.
Setting noclobber=1 - keeps files from being clobbered by the shell.

Shell Selection for users

The file "/etc/shells" lists the valid shells and shell paths on your system. An example file is:

/bin/bash
/bin/sh
/bin/tcsh
/bin/csh
/bin/ash
/bin/bsh
/bin/bash2
/bin/ksh
/bin/zsh

The command "chsh" can be used by the user to set his preferred shell. Also the root user can use this command to set any user's shell. This command with the -l option will list the available shells. The -s option will allow the user to change their shell. For example type the following to determine and modify the user's shell.

  1. chsh -l
  2. chsh -s /bin/sh

The first line will show available shells, and the second entry will change it. The full path of the shell must be entered for the command to work.


Startup Scripts

The following scripts are run by bash if the –noprofile option is not used with the shell:

/etc/profile
This script file is run first for all users during the login process
$HOME/.bash_profile
This script file is run for individual user's customized setup
$HOME/.bash_login
If the .bash_profile above does not exist, this file is run
$HOME/.profile
This script file is run if $HOME/.bash_profile and .bash_login don't exist

If bash is invoked as "sh" it will run only "/etc/profile" and "$HOME/.profile", above.

The man page says that "$HOME/.bashrc" is run for non-login interactive shells. I'm not sure if it also runs for login interactive shells, but believe it does. If it does, I'm not sure whether it is run after the scripts above, but believe it is.
$HOME/.bash_logout
Run when the user logs off the system.

Key bindings:
If the shell variable "INPUTRC" is set, probably in "/etc/profile" the keybindings are set by the file declared in the INPUTRC value. Usually this is "/etc/inputrc". Otherwise the keybindings are set in the file "$HOME/.inputrc" for each individual user.
$HOME/.inputrc - User's keybindings definition
/etc/inputrc - Global keybindings definition
Other scripts and files:
/etc/bashrc
On my Redhat system, this file is run by $HOME/.bashrc.
/etc/login.defs
Used with shadow passwords to set initial PATH and other parameters including how often a user must change passwords and what is acceptable as a password..

Put any new script files in /usr/bin or /usr/local/bin. If you put them in /usr/local/bin, they will be easier to keep track of, but you may want to add /usr/local/bin to your path environment to make them more accessible. You can put the command "export PATH=$PATH:/usr/local/bin" in one of the above scripts or add it to the path statement in /etc/profile.

Therefore to modify parameters for all users, edit:

/etc/profile
For users environment setup and other customized items.
/etc/inputrc
For keybindings on some systems if INPUTRC is set to it.

To customize user's setup edit: (Note: In /home/user's name/...)

HOME/.bash_profile - Users environment stuff and startup programs
$HOME/.bashrc - user aliases and functions
$HOME/.bash_logout - User actions to be done at logout
$HOME/.inputrc - Contains keybindings and other bits.

The tcsh shell operates as follows:

/etc/csh.login is run
$HOME/.tcshrc or .cshrc is run
$HOME/.login is run

Other files in the users home directory may be:

.emacs - For the emacs editor. Consists of LISP functions.
.exrc - For the vi editor
.fvwmrc - For the fvwm window manager
.twmrc - For the twm window manager
.newsrc - For newsreaders. Contains a list of newsgroups offered at this site.
.Xdefaults - For programs using the X window system
.xinitrc - Shell commands that run when the user logs into an X session.