(M)  s i s t e m a   o p e r a c i o n a l   m a g n u x   l i n u x ~/ · documentação · suporte · sobre

 

3.11. System and Administrative Commands

The startup and shutdown scripts in /etc/rc.d illustrate the uses (and usefulness) of these comands. These are usually invoked by root and used for system maintenance or emergency filesystem repairs. Use with caution, as some of these commands may damage your system if misused.

uname

Output system specifications (OS, kernel version, etc.) to stdout. Invoked with the -a option, gives verbose system info (see Example 3-48).

bash$ uname -a
Linux localhost.localdomain 2.2.15-2.5.0 #1 Sat Feb 5 00:13:43 EST 2000 i686 unknown
arch

Show system architecture. Equivalent to uname -m.

bash$ arch
i686
bash$ uname -m
i686
id

The id command lists the real and effective user IDs and the group IDs of the current user. This is the counterpart to the $UID, $EUID, and $GROUPS internal Bash variables (see Section 3.7).

bash$ id
uid=501(bozo) gid=501(bozo) groups=501(bozo),22(cdrom),80(cdwriter),81(audio)
bash$ echo $UID
501
who

Show all users logged on to the system.

whoami is a variant of who that lists only the current user.

w

Show all logged on users and the processes belonging to them. This is an extended version of who. The output of w may be piped to grep to find a specific user and/or process.

bash$ w | grep startx
grendel  tty1     -                 4:22pm  6:41   4.47s  0.45s  startx
users

Show all logged on users. This is the approximate equivalent of who -q.

groups

Lists the current user and the groups she belongs to. This corresponds to the $GROUPS internal variable, but gives the group names, rather than the numbers.

bash$ groups
bozita cdrom cdwriter audio xgrp
bash$ echo $GROUPS
501
hostname

Lists the system's host name, as recorded in /etc/hosts. This is a counterpart to the $HOSTNAME internal variable.

bash$ hostname
localhost.localdomain
bash$ echo $HOSTNAME
localhost.localdomain
ulimit

Sets an upper limit on system resources. Usually invoked with the -f option, which sets a limit on file size (ulimit -f 1000 limits files to 1 meg maximum). The -t option limits the coredump size (ulimit -c 0 eliminates coredumps). Normally, the value of ulimit would be set in /etc/profile and/or ~/.bash_profile (see Section 3.23).

uptime

Shows how long the system has been running, along with associated statistics.

bash$ uptime
10:28pm  up  1:57,  3 users,  load average: 0.17, 0.34, 0.27
env

Runs a program or script with certain environmental variables set or changed (without changing the overall system environment). The [varname=xxx] permits changing the environmental variable varname for the duration of the script. With no options specified, this command lists all the environmental variable settings.

su

Runs a program or script as a substitute user. su rjones starts a shell as user rjones. A naked su defaults to root. See Example A-7.

shopt

This command permits changing shell options on the fly (see Example 3-85). It often appears in the Bash setup files, but also has its uses in scripts. Works with version 2 of Bash only.

shopt -s cdspell
# Allows minor misspelling directory names with 'cd'
command.

lockfile

This utility is part of the procmail package (www.procmail.org). It creates a lock file, a semaphore file that controls access to a file, device, or resource. The lock file serves as a flag that this particular file, device, or resource is in use by a particular process ("busy"), and permitting only restricted access (or no access) to other processes. Lock files are used in such applications as protecting system mail folders from simultaneously being changed by multiple users, indicating that a modem port is being accessed, and showing that an instance of Netscape is using its cache. Scripts may check for the existence of a lock file created by a certain process to check if that process is running. Note that if a script attempts create a lock file that already exists, the script will likely hang.

cron

Administrative program scheduler, performing such duties as cleaning up and deleting system log files and updating the slocate database. This is the superuser version of at. It runs as a daemon (background process) and executes scheduled entries from /etc/crontab.

chroot

CHange ROOT directory. Normally commands are fetched from $PATH, relative to /, the default root directory. This changes the root directory to a different one (and also changes the working directory to there). A chroot /opt would cause references to /usr/bin to be translated to /opt/usr/bin, for example. This is useful for security purposes, for instance when the system administrator wishes to restrict certain users, such as those telnetting in, to a secured portion of the filesystem. Note that after a chroot, the execution path for system binaries is no longer valid.

The chroot command is also handy when running from an emergency boot floppy (chroot to /dev/fd0), or as an option to lilo when recovering from a system crash. Other uses include installation from a different filesystem (an rpm option). Invoke only as root, and use with caution.

umask

User file creation MASK. Limit the default file attributes for a particular user. All files created by that user take on the attributes specified by umask. The (octal) value passed to umask defines the the file permissions disabled. For example, umask 022 ensures that new files will have at most 755 permissions (777 NAND 022). [1] Of course, the user may later change the attributes of particular files with chmod.The usual practice is to set the value of umask in /etc/profile and/or ~/.bash_profile (see Section 3.23).

ldd

Show shared lib dependencies for an executable file.

bash$ ldd /bin/ls
libc.so.6 => /lib/libc.so.6 (0x4000c000)
/lib/ld-linux.so.2 => /lib/ld-linux.so.2 (0x80000000)
logname

Show current user's login name (as found in /var/run/utmp). This is equivalent to whoami, above.

bash$ logname
bozo
bash$ whoami
bozo
tty

Echoes the name of the current user's terminal. Note that each separate xterm window counts as a different terminal.

bash$ tty
/dev/pts/1
stty

Shows and/or changes terminal settings.

Example 3-68. secret password: Turning off terminal echoing

#!/bin/bash

echo
echo -n "Enter password "
read passwd
echo "password is $passwd"
echo -n "If someone had been looking over your shoulder, "
echo "your password would have been compromised."

echo && echo  # Two line-feeds in an "and list".

stty -echo   # Turns off screen echo.

echo -n "Enter password again "
read passwd
echo
echo "password is $passwd"
echo

stty echo   # Restores screen echo.

exit 0
wall

This is an acronym for "write all", i.e., sending a message to all users every terminal logged on in the network. It is primarily a system administrator's tool, useful, for example, when warning everyone that the system will shortly go down due to a problem (see Example 3-94).

wall System going down for maintenance in 5 minutes!
logger

Appends a user-generated message to the system log (/var/log/messages). You do not have to be root to invoke logger.

logger Experiencing instability in network connection at 23:10, 05/21.
# Now, do a 'tail /var/log/messages'.

dmesg

Lists all system bootup messages to stdout. Handy for debugging and ascertaining which device drivers were installed and which system interrupts in use. The output of dmesg may, of course, be parsed with grep, sed, or awk from within a script.

fuser

Identifies the processes (by pid) that are accessing a given file, set of files, or directory. May also be invoked with the -k option, which kills those processes. This has interesting implications for system security, especially in scripts preventing unauthorized users from accessing system services.

pidof

Identifies process id (pid) of a running job. Job control commands, such as kill and renice act on the pid of a process, rather than its name. This is the counterpart of the $PPID internal variable (see Section 3.7).

Example 3-69. pidof helps kill a process

#!/bin/bash
# kill-process

NOPROCESS=2

process=xxxyyyzzz  # Use nonexistent process.
# For demo purposes only...
# ... don't want to actually kill any actual process with this script.
# If, for example, you wanted to use this script to logoff the Internet     process=pppd

t=`pidof $process`       # Find pid (process id) of $process.
# The pid is needed by 'kill' (can't 'kill' by program name).

if [ -z $t ]    # If process not present, 'pidof' returns null.
then
  echo "Process $process was not running."
  echo "Nothing killed."
  exit $NOPROCESS
fi  

kill $t     # May need 'kill -9' for stubborn process.

# Need a check here to see if process allowed itself to be killed.
# Perhaps another " t=`pidof $process` ".

exit 0
nice

Show or change the priority of a background job. Priorities run from 19 (lowest) to -20 (highest). Only root may set the negative (higher) priorities. Related commands are renice, snice, and skill.

nohup

Keeps a command running even after user logs off. The command will run as a foreground process unless followed by &. If you use nohup within a script, consider coupling it with a wait to avoid creating an orphan or zombie process.

free

Shows memory and cache usage in tabular form. The output of this command lends itself to parsing, using grep, awk or Perl.

bash$ free
                total       used       free     shared    buffers     cached
   Mem:         30504      28624       1880      15820       1608       16376
   -/+ buffers/cache:      10640      19864
   Swap:        68540       3128      65412
sync

Forces an immediate write of all updated data from buffers to hard drive. While not strictly necessary, a sync assures the sys admin or user that the data just changed will survive a sudden power failure. In the olden days, a sync sync was a useful precautionary measure before a system reboot.

init

The init command is the parent of all processes. Called in the final step of a bootup, init determines the runlevel of the system from /etc/inittab. Invoked by its alias telinit, and by root only.

telinit

Symlinked to init, this is a means of changing the system runlevel, usually done for system maintenance or emergency filesystem repairs. Invoked only by root. This command can be dangerous - be certain you understand it well before using!

runlevel

Shows the current and last runlevel, that is, whether the system is halted (runlevel 0), in single-user mode (1), in multi-user mode (2 or 3), in X Windows (5), or rebooting (6).

halt, shutdown, reboot

Command set to shut the system down, usually just prior to a power down.

exec

This is actually a system call that replaces the current process with a specified command. It is mostly seen in combination with find, to execute a command on the files found (see Example 3-47). When used as a standalone in a script, it forces an exit from the script when the exec'ed command terminates. An exec is also used to reassign file descriptors. exec <zzz-file replaces stdin with the file zzz-file (see Example 3-72).

Example 3-70. Effects of exec

#!/bin/bash

exec echo "Exiting $0."
# Exit from script.

# The following lines never execute.
echo "Still here?"

exit 0
ifconfig

Network interface configuration utility.

route

Show info about or make changes to the kernel routing table.

netstat

Show current network information and statistics, such as routing tables and active connections.

mknod

Creates block or character device files (may be necessary when installing new hardware on the system).

mount

Mount a filesystem, usually on an external device, such as a floppy or CDROM. The file /etc/fstab provides a handy listing of available filesystems, including options, that may be automatically or manually mounted. The file /etc/mtab shows the currently mounted filesystems (including the virtual ones, such as /proc).

mount -t iso9660 /dev/cdrom /mnt/cdrom
# Mounts CDROM
mount /mnt/cdrom
# Shortcut, if /mnt/cdrom listed in /etc/fstab

umount

Unmount a currently mounted filesystem. Before physically removing a previously mounted floppy or CDROM disk, the device must be umount'ed, else filesystem corruption may result.

umount /mnt/cdrom

lsmod

List installed kernel modules.

insmod

Force insertion of a kernel module. Must be invoked as root.

modprobe

Module loader that is normally invoked automatically in a startup script.

depmod

Creates module dependency file, usually invoked from startup script.

rdev

Get info about or make changes to root device, swap space, or video mode. The functionality of rdev has generally been taken over by lilo, but rdev remains useful for setting up a ram disk. This is another dangerous command, if misused.

Using our knowledge of administrative commands, let us examine a system script. One of the shortest and simplest to understand scripts is killall, used to suspend running processes at system shutdown.

Example 3-71. killall, from /etc/rc.d/init.d

#!/bin/sh

# --> Comments added by the author of this HOWTO marked by "-->".

# --> This is part of the 'rc' script package
# --> by Miquel van Smoorenburg, <miquels@drinkel.nl.mugnet.org>

# --> This particular script seems to be Red Hat specific
# --> (may not be present in other distributions).

# Bring down all unneeded services that are still running (there shouldn't 
# be any, so this is just a sanity check)

for i in /var/lock/subsys/*; do
        # --> Standard for/in loop, but since "do" is on same line,
        # --> it is necessary to add ";".
	# Check if the script is there.
	[ ! -f $i ] && continue
	# --> This is a clever use of an "and list", equivalent to:
	# --> if [ ! -f $i ]; then continue

	# Get the subsystem name.
	subsys=${i#/var/lock/subsys/}
	# --> Match variable name, which, in this case, is the file name.
	# --> This is the exact equivalent of subsys=`basename $i`.
	
	# --> It gets it from the lock file name, and since if there
	# --> is a lock file, that's proof the process has been running.
	# --> See the "lockfile" entry, above.


	# Bring the subsystem down.
	if [ -f /etc/rc.d/init.d/$subsys.init ]; then
	    /etc/rc.d/init.d/$subsys.init stop
	else
	    /etc/rc.d/init.d/$subsys stop
	# --> Suspend running jobs and daemons
        # --> using the 'stop' shell builtin.
	fi
done

That wasn't so bad. Aside from a little fancy footwork with variable matching, there is no new material there.

Exercise. In /etc/rc.d/init.d, analyze the halt script. It is a bit longer than killall, but similar in concept. Make a copy of this script somewhere in your home directory and experiment with it (do not run it as root). Do a simulated run with the -vn flags (sh -vn scriptname). Add extensive comments. Change the "action" commands to "echos".

Now, look at some of the more complex scripts in /etc/rc.d/init.d. See if you can understand parts of them. Follow the above procedure to analyze them. For some additional insight, you might also examine the file sysvinitfiles in /usr/doc/initscripts-X.XX, which is part of the "initscripts" documentation.

Notes

[1]

NAND is the logical "not-and" operator. Its effect is somewhat similar to subtraction.