Linux Commands
Linux Commands
Windows
dir
dir /ad
attrib h
sorting
attrib
md
rd
del
deltree
copy
Linux
General Commands
ls
ls filename or file*
ls directory or dir*
ls l - Directory listing with long filenames, owner, and permissions
ls ld - Show only the directories matching the search
ls R - Show subdirectories also ( just like dir /s )
ls al
ls Sharl sort by size, all files, including hidden
ls lart sort by date, reverse order (newest @ the bottom of list)
-S - sorts by size, largest first
-r - reverses any sort command, i.e. ls rS sorts smallest first
-t - sorts by modification time, recent first
-u - sort by last accessed time
-x - sort by file extension
Remember Linux is case sensitive, so if youre looking for a file beginning
with Vol, type ls Vol*
Colors:
Blue = directory
Green = script
Grey = file
find depth iname filename* | less - this will find anything starting
with filename, with the iname switch allowing it to be case insensitive, and
will pipe the results to the less screen so you can page through the results
using [Page Up] and [Page Down] keys. Pretty cool!
Press Q to quit
chmod
mkdir
rmdir
rm i (without the i, rm will not ask for confirmation)
rm rf *
cp i (without the i, cp will not prompt for destructive actions like file
replacement - if the file exists, it is overwritten)
How to copy all files from a CD and then change the files to read/write
mount /dev/cdrom /mnt/cdrom
mkdir /root/snortinstall
cp r -v /mnt/cdrom/* /root/snortinstall
cd /root/snortinstall
chmod R +wr /root/snortinstall/*
umount /mnt/cdrom
copy con
edit
type
move
ren
cls
help
fdisk
diskcopy
ver
whoami
set
Help
Shutdown
Working directory
Compile binary
Make Executable out of
script
Running Processes, Uptime,
etc.
Find a specific process
Mem
su username
su username
dmesg
cal month year
/etc/rc.d/rc.local
df h
du h
rpm ivh rpm_name.rpm
This installs a given rpm with install, verbose, and hash marks
To list all installed rpms:
rpm qa | sort | more
This will list all installed rpms, sort alphabetically, and display them one
screen at a time. You could redirect it to a file to peruse at your convenience
or for auditing purposes.
/boot/grub/grub.conf
/boot/grub/menu.lst
To see your path, type echo $PATH
You can send messages to other users that are connected to the same linux
box, such as on the console or SSHd to the box.
First, find out what TTY the user is connected to by simply typing w
Now, issue the write command to the username and the TTY they are on,
like this:
write root tty1
Now you can simply type away, hitting the [ENTER] key to send the line.
You can keep on typing and sending messages until you escape out by using
[CTRL]+c.
MD5 CheckSum
md5sum filename
Directory Size
This article explains 2 simple commands that most people want to know
when they start using Linux. They are finding the size of a directory and
finding the amount of free disk space that exists on your machine. The
command you would use to find the directory size is ' du '. And to find
the free disk space you could use ' df '.
All the information present in this article is available in the man pages
for du and df. In case you get bored reading the man pages and you
want to get your work done quickly, then this article is for you.
'du' - Finding the size of a directory
$ du
Typing the above at the prompt gives you a list of directories that exist
in the current directory along with their sizes. The last line of the output
gives you the total size of the current directory including its
subdirectories. The size given includes the sizes of the files and the
directories that exist in the current directory as well as all of its
subdirectories. Note that by default the sizes given are in kilobytes.
$ du /home/david
The above command would give you the directory size of the directory
/home/david
$ du -h
This command gives you a better output than the default one. The
option '-h' stands for human readable format. So the sizes of the files /
directories are this time suffixed with a 'k' if its kilobytes and 'M' if its
Megabytes and 'G' if its Gigabytes.
$ du -ah
This command would display in its output, not only the directories but
also all the files that are present in the current directory. Note that 'du'
always counts all files and directories while giving the final size in the
last line. But the '-a' displays the filenames along with the directory
names in the output. '-h' is once again human readable format.
$ du -c
This gives you a grand total as the last line of the output. So if your
directory occupies 30MB the last 2 lines of the output would be
30M .
30M total
The first line would be the default last line of the 'du' output indicating
the total size of the directory and another line displaying the same size,
followed by the string 'total'. This is helpful in case you this command
along with the grep command to only display the final total size of a
directory as shown below.
$ du -ch | grep total
This would have only one line in its output that displays the total size of
the current directory including all the subdirectories.
Note : In case you are not familiar with pipes (which makes the above command possible) refer
to Article No. 24 . Also grep is one of the most important commands in Unix. Refer to Article No.
25 to know more about grep.
$ du -s
This displays a summary of the directory size. It is the simplest way to
know the total size of the current directory.
$ du -S
This would display the size of the current directory excluding the size of
the subdirectories that exist within that directory. So it basically shows
you the total size of all the files that exist in the current directory.
$ du --exculde=mp3
The above command would display the size of the current directory along
with all its subdirectories, but it would exclude all the files having the
given pattern present in their filenames. Thus in the above case if there
happens to be any mp3 files within the current directory or any of its
subdirectories, their size would not be included while calculating the total
directory size.
'df' - finding the disk free space / disk usage
$ df
Typing the above, outputs a table consisting of 6 columns. All the
columns are very easy to understand. Remember that the 'Size', 'Used'
and 'Avail' columns use kilobytes as the unit. The 'Use%' column shows
the usage as a percentage which is also very useful.
$ df -h
Displays the same output as the previous command but the '-h' indicates
human readable format. Hence instead of kilobytes as the unit the
output would have 'M' for Megabytes and 'G' for Gigabytes.
Most of the users don't use the other parameters that can be passed to
'df'. So I shall not be discussing them.
I shall in turn show you an example that I use on my machine. I have
Grub
As you can easily guess, the first two lines cover the configuration of
the splash menu: the background image is located in /dev/hda5 and
has the name "message". Foreground: white, background: green,
selection: black, background of the selection: light gray.
The entry "default 0" in the third line indicates that the first menu
entry ("title linux") is the default selection for booting.
Line 4: The timeout is 8 seconds.
See the website for a better explanation if this didnt jog your memory.
GUI or Text Boot
To change the boot mode between GUI and Text mode, you need to set the
default runlevel in the initab file:
- vi /etc/inittab
- Find the runlevel section and the line that reads:
id:X:initdefault (where X = 3 or 5)
- Change the line for what you want as follows:
id:3:initdefault = text mode
id:5:initdefault = GUI mode
Uhoh your /etc/inittab is set to boot into GUI mode automatically, but your
screen resolution doesnt support it. How do you exit the GUI when you
cant see anything? Well, good old [CTRL] + [ALT] + [Backspace]
doesnt do the trick because it will exit GUI, but immediately go right back
into the GUI. So whats a geek to do?
To exit GUI, use [CTRL] + [ALT] + [F1]. This will exit GUI and put you
at the console (command line interface).
This is kind of like safe-mode in Windows it skips a lot of startup files and
services:
1. Power on the box
2. At the boot screen for Grub, select the version you want to boot and
type e for edit
3. Select the line that starts with kernel and type e for edit
4. Go to the end of the line and type single
5. Hit [ENTER]
6. Now type b for boot
tcpdump
example:
tcpdump i eth1 w dump host 208.159.105.98
tcpflow
Three-Finger Salute
Launch VMware
/usr/bin/vmware
rpm e VmwareWorkstation
10
Mount Floppy
Mount CD-ROM
Read a floppy or CD
11
First, you need to create a mount point (directory). I usually do this in the
/mount directory
Example:
mkdir /mnt/share
Then, mount the share:
smbmount //server/share /mnt/directory o username=username,
workgroup=domain
Example:
smbmount //ohcont04/data /mnt/data o username=bwestbro,
workgroup=corpone
unmount
smblient
umount /mnt/floppy
smbclient //server/share W domain U username%password -c put
/root/xxxx xxxxx
Example:
smbclient //ohcont04/bacup W corpone U bwestbro%password c put
/root/test.txt test.txt
To secure NFS using IPTables on Red Hat, you must first static the ports
that NFS uses. By default, NFS opens dynamic ports for the inbound service
requests. To static the ports you have to create a file name nfs in the
/etc/syconfig directory, and add the specific ports. In our example, which
you can use real-world, well static the ports to 4000, 4001 and 4002.
vim /etc/sysconfig/nfs
12
You can verify what ports RPC (e.g. NFS) is listening on now that you
reconfigured it by issuing the command:
rpcinfo -p
port
111
111
660
660
663
663
2049
2049
2049
2049
4002
4002
4002
4002
4002
4002
4001
4001
4001
4001
4001
4001
portmapper
portmapper
rquotad
rquotad
rquotad
rquotad
nfs
nfs
nfs
nfs
nlockmgr
nlockmgr
nlockmgr
nlockmgr
nlockmgr
nlockmgr
mountd
mountd
mountd
mountd
mountd
mountd
Finally, you need to allow portmapper, nfs and your new nfs ports through
IPTables. If youre setting up iptables as I usually do and are just using the
default INPUT chain, you would configure your iptables something like this:
First, delete your last DROP line:
iptables D INPUT j DROP
Next, add all the necessary TCP and UDP ports for NFS:
iptables
iptables
iptables
iptables
iptables
iptables
A
A
A
A
A
A
INPUT
INPUT
INPUT
INPUT
INPUT
INPUT
p
p
p
p
p
p
tcp
udp
tcp
udp
tcp
udp
--dport
--dport
--dport
--dport
--dport
--dport
111 j ACCEPT
111 j ACCEPT
2049 j ACCEPT
2049 j ACCEPT
4000:4002 j ACCEPT
4000:4002 j ACCEPT
13
format a: (floppy)
as Linux -->
as DOS -->
Zipped files
Linux
fdformat /dev/fd0
then
mkfs t ext2 /dev/fd0
DOS
fdformat /dev/fd0
then
mkfs t msdos /dev/fd0
1. Check /etc/lilo.conf (or /etc/grub.conf) and right down the version of
the image being loaded at boot. The line will look as follows:
image = /boot/vmlinuz-x.x.x-x.x
2. Login as root
3. Insert a blank floppy type mkbootdisk device /dev/fd0 x.x.x-x.x
4. Reboot with floppy and see if works
.tar usually means that the file is not compressed
.tar.gz or .tgz usually means that the file was first combined into a tar file,
then compressed into a zip format with gunzip.
.tar.bz usually means that the file was again first combined into a tar file,
then compressed with bzip2
Extracting: for a simple .tar file called myfile.tar, type the following
tar -xvf myfile.tar
For a file thats both tar and zipped, such as myfile.tar.gz or myfile.tgz, type
the following
tar xvzf myfile.tar.gz
To tar files, do this:
tar cvf tar_filename [files/directory]
To tar and zip files, do this:
tar zcvf tar_filename [files/directory]
14
A: floppy
B: floppy
Master drive on primary
IDE channel
First partition on master
drive on primary partition
Third partition on master
drive on primary partition
Slave drive on primary IDE
channel
Master drive on secondary
IDE channel
Slave drive on secondary
IDS channel
SCSI target ID 0
SCSI target ID 1
Second partition on the hard
disk at SCSI target ID 0
SCSI tape device
CD-ROM
Keyboard
Modem
Sound system
Interesting trick with devices - Since the keyboard is a device with a filename (/dev/tty) you can
create a text file from what you type at the keyboard...very similar to copy con.
15
IP Configuration
ipconfig
IP configuration utilities
route print
route add
route add p (permanent)
(option 1)
route delete
route add default gateway
route add default gateway
(permanent)
DNS servers
Hosts file
hostname
Change hostname
ifconfig
ifconfig
netconfig (preferred)
linuxconf (catch all)
netconf (not preferred, use CTRL+X for pulldowns)
route n (the n is no resolution and is faster)
route add net network netmask subnet_mask gw gateway_address
Add the following information to the /etc/sysconfig/static-files file (simply
make the file if it does not already exist):
- vi /etc/sysconfig/static-files
- i (for insert)
- any net x.x.x.x netmask y.y.y.y gw z.z.z.z
- :wq
Now reboot to see if the route stuck
You could also simply add a line to the rc.local (e.g. autoexec.bat) file that
runs at startup:
- vi /etc/rc.d/rc.local
- i (for insert)
- route add net network netmask subnet_mask gw
gateway_address
- :wq
route del net network netmask subnet_mask
route add default gw gateway_address
If you need the default route to survive a reboot (non-DHCP for instance),
do it in the /etc/sysconfig/network file by adding the following line:
GATEWAY=x.x.x.x
/etc/resolv.conf
/etc/hosts
- IP address, at least one space, then hostname
- You can have more than one hostname on a line for a single IP
address, just separate the hostnames by at least one space
/etc/sysconfig/network
- Change name in /etc/hosts
- Change name in /etc/sysconfig/network
HOSTNAME=xxxxx
- For Mandrake, also add the following line to the network file
DOMAINNAME=xxxxx.xxx
16
Example:
NIC Information:
IP address = 192.168.0.10
Subnet Mask = 255.255.255.0
Gateway = 192.168.0.1
Hostname = mypc.acme.com
DNS = 192.168.0.77
1. Configure the NIC and IP address with the ifconfig command:
ifconfig eth0 192.168.0.1 netmask 255.255.255.0 broadcast
192.168.0.255
(If youre dealing with a PCMCIA NIC, you be able to get a report of
the IRQ and IO values by typing cardctl config)
2. Create the local route:
route add net 192.168.0.0 netmask 255.255.255.0 dev eth0
3. Create the local gateway:
route add default gw 192.168.0.1
Static IP Address
Use the networking file for the specific interface. For eth0, use
/etc/sysconfig/network-scripts/ifcfg-eth0
PERMANENT SETUP
This will last through a
reboot
17
DCHP
Take interface up or down
Restart Network
Promiscuous mode
Determine IP Status
including whether interface
is in promiscuous mode
Listening ports netstat
IP Information
netstat tpan will show ports what ports are open on the external interface
nice to use to verify things like Apache or SSH are listening for incoming
connections
There is no man page, so use ip help instead if you need help.
ip
ip
ip
ip
a display addresses
a help further help for address
r display routes (similar to the route command)
a a 10.10.146.58/30 dev eth0 label eth0:0 add a virtual
18
Pull a File
Push a File
Pull a File
Push a File
19
Add a user
Modify a user
Delete a user
Change password
Group administration
command
Who is logged on
What group(s) do I belong
to?
User login activity
User Administration
useradd
usermod
userdel
passwd username (if logged on as root, can change anyones password if
logged on as user, can only change own password, no need to type your
username as the switch)
groupadd
groupmod
groupdel
gpasswd
users
groups
last
lastb
who
ac
Last shows the following information:
Type of Login
Process ID of login process
Device name of tty
Init ID or abbreviated ttyname
User Name
Hostname for remote login
Exit Status of a process
Time entry was made
IP address of remote host
20
chage l [account_name]
chage [account_name]
To set a non-expiring password, set the Maximum Password Age to 99999
http://www.nic.com/~dave/SecurityAdminGuide/SecurityAdminGuide5.html
Permissions Discussion
UNIX/Linux has no per-user permissions/rights/policies. Everything is done on files, making sure who
can read/write/exectute the right files.
To check the current permissions of files, run "ls -l". If you run "ls -l /", to list all files in the root
directory, you will get output that looks something like this:
Code:
drwxr-xr-x
drwxr-xr-x
drwxr-xr-x
...
2 root
4 root
20 root
root
root
root
The first column (that looks like drwxr-xr-x) is the mode of the file. The first character indicates what
kind of file it is. d, as in this case, means directory. - means regular file, and then there are some other
file types of which you need not know more now, like named FIFOs, sockets, devices, etc.
The rwxr-xr-x is the permissions of file. The first rwx means that the owner of the file can read, write
and execute the file. For directories, the right to execute it means the right to use it. Just being able to
read a directory means that you can read what files are in the directory, but you won't be able to use
them without the execute permission on the directory. The first r-x means that those that are in the same
group as the file have read and execute permissions to the file. The second r-x means that all those that
are neither the owner of the file nor are in the same group as the file have read and execute permissions
on it. So r=read, w=write and x=execute, and the first group of three applies to the owner of the file, the
second group applies to those in the same group of the file, and the third group applies to all other users.
The second column (2, 4 and 20 in this case) is the number of links that the file has. Don't care about
that for now.
21
The third column is the owner of the file, in this case root.
The fourth column is the group of the file, in this case the root group.
The fifth column is the size of the file.
The sixth is the time the file was last modified
The seventh is naturally the name of the file.
Changing Permissions
there are three command that you need to learn.
chmod /*change the ppermissions of a file*/
chown /*change the owner of the file*/
chgrp /*change the group that the file belongs to*/
example:
chmod 777 somefile.file /*this gives exe write and read to all */ not recommended for any
file.
for chmod here is a list of the numbers and what they meen
the 100's are for the owner of the file
400 reed
200 write
100 execute
10's are for the group of the file
40 read
20 write
10 execute
1's are for everyone else
4 read
2 write
1 execute
you add the number together to get different permissions
To change multiple files, you can use chmod R for an entire directory, or use wildcards like
chmod 755 *.txt.
22
XWindows
Configure XWindows from
command line
Cycle through video settings
Leave XWindows NOW
handy when you cant see
the screen due to video
resolution problems
Shoot Xwindows back
through your SSH session
Xconfigurator
[CTRL] + [ALT] + [+]
[CTRL] + [ALT] + [BACKSPACE]
Launching SSH with the X switch will forward X-windows back through
your SSH tunnel
ssh -X
23
Backup Database
MYSQL
mysql uuser ppassword
i.e. mysql uroot pwopnam
mysql uuser ppassword hip_address database_name
i.e mysql uroot pwopnam h207.169.53.5 snort
connect database_name
i.e. connect snort
show tables;
show columns from table_name;
i.e show columns from acid_event;
select max(field) from table_name;
i.e. select max(timestamp) from acid_event
show databases
use database_name
show tables
show grants for user@localhost
mysqldump u root p --opt database_name > /path/filename.sql
For example:
mysqldump u root p --opt snort > /root/snort.sql
Restore Database
For example:
mysql u root p snort < /root/snort.sql
MISC Stuff
24
*
*
*
*
from
from
from
from
users
users
users
users
order
order
order
order
by
by
by
by
user_first_name;
user_first_name desc;
user_last_name;
user_last_name desc;
select
select
select
select
*
*
*
*
from
from
from
from
users
users
users
users
where
where
where
where
user_last_name = 'Westbrook';
user_last_name != 'Westbrook';
user_first_name = 'Matt';
user_first_name != 'Matt';
25
Vi - File Editor
Batch file
echo to email
26
Secure Default
Firewall
Ruleset
As a brief explanation, the firewall rules for iptables are not really kept
in any editable file. That is, the rules, once loaded, exist in memory and
will overwrite the file they came from. So how do you configure
iptables? And how does it load its ruleset after a reboot?
* Explanation *
Well, one way is to make changes to the ruleset in memory, on the fly.
You then tell iptables to save the rules in memory to a file. When the
box reboots, iptables reads the rules from this saved file.
So why cant you just change the actual rules in file? Because its
overwritten any time that you save the rules. And you cant delete rules
by simply re-reading the file the file will append to the rules in
memory. Instead, you should create a file of your own with all your
firewall rules and comments, run your file to add, delete or modify rules
in memory, and then save the iptables memory to the
/etc/sysconfig/iptables file. Whew!
Rather then create a script to do our changes, we will perform the
changes on the fly. Well then save the memory to a file so they get
removed permanently on reboot.
To do this, we will perform the following:
1. Delete (flush) all of the current rules
2. Define our chains/tables in memory
3. Add our default rules in memory
4. Add other rules in memory as needed
5. Save the new iptables from memory to the iptables file
6. Restart iptables to verify our changes
New Default
Firewall
Ruleset
* All Distros *
27
28
MySQL
iptables -A INPUT -p tcp -m tcp --dport 3306 j ACCEPT
The very last rule we will put in is to drop all remaining packets that
didnt match any of our rules. This is simply good practice:
iptables A INPUT j DROP
Finally, save your revised rules to a file, restart iptables and then verify
your rules are all in place:
service iptables save
service iptables restart
iptables -L
Other Useful
iptables
Commands
29
GPG
Description
Key Creation
Under GPG, there is no GUI. To create a key under, perform the following
steps at a command prompt:
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
GPG
Commands
gpg --gen-key
Select 1 for DSA and ElGamal
For What keysize do you want, type 2048
For Key is valid for, enter 13m
Verify date of expiration is 13 months from today and enter Y for Is
this correct?
For Real Name, enter a logical name for the particular key you are
creating
For Email Address, enter your email address
For Comment, enter a brief comment for what the key is to be used
for or leave it blank
Review your entries, make any changes as necessary, then type O for
Okay
Create a Passphrase based on the requirements in the Standards
section above.
Reenter the passphrase
Now begin moving the mouse and typing junk at the keyboard to
create random information for the key generator.
When its completed, you will be back at the command prompt
Export the public key by typing gpg --export KeyID >
KeyID-pubkey.pgp where KeyID is the Real Name you entered
when creating the key
Export the private key by typing gpg --export-secret-key
KeyID > KeyID-seckey.pgp where KeyID is the Real Name
you entered when creating the key
Copy the two .pgp files you created to a floppy, USB, etc. for backup
purposes.
Delete the exported files from the system
The keyname referenced in the commands below can be either the ownerss
name, the users email address or the key ID. If you happen to have gpg keys
with the same owners name and email address, you can differentiate between
them based on the key ID.
What is the key ID? It is the hex ID given after the keysize. For instance,
using the command gpg --list-keys will show all the keys in your
keyring, like this:
# gpg --list-keys
pub 1024D/28394F0E 2006-09-07 [expires: 2006-10-07]
uid
MyTestKey (testkey1) <[email protected]>
sub 2048g/020D77F8 2006-09-07 [expires: 2006-10-07]
pub 1024D/2608AE83 2006-09-07 [expires: 2007-10-02]
uid
MyTestKey (testkey2) <[email protected]>
sub 2048g/C25E7EF4 2006-09-07 [expires: 2007-10-02]
You can see that there are two keys with the same name (MyTestKey) and
email address ([email protected]). However, the key IDs will always be
different. The keysize is shown, followed by the public hex key ID, shown
30
highlighed above. Using this example you can therefore use the key ID to
delete a key, like this:
gpg --delete-secret-key 2608ae83
gpg --delete-key 2608ae83
Generate (create) a key:
gpg -gen-key
Export the public key of the designated name to a file:
gpg --export a keyname > keyname-pubkey.key
Export the secret key of the designated name to a file:
gpg --export-secret-key a keyname > keynamepubkey.key
Import a public key:
gpg -import filename
Import a secret key:
gpg -allow-secret-key-import -import filename
Export the fingerprint of a key to verify a public key:
gpg --fingerprint > keyname-fingerprint
List your public key(s):
gpg --list-keys
List your secret key(s):
gpg --list-secret-key
Delete your secret-key by name:
gpg --delete-secret-keys keyname
Delete a public key:
gpg --delete-keys keyname
Sign and encrypt the given filename with your default key to the receiver:
gpg se r receiver_keyname filename
Decrypt a filename with your default-key:
gpg d filename
Trust Other
Keys
31
Note that this configuration is for a protected, internal server, NOT an Internet accessible server.
That is, you trust (relatively so) the clients on your internal network.
Configure NTP
Backup
Description
First backup your original ntp.conf file:
cp /etc/ntp.conf /etc/ntp.conf.orig
Locate an
Internet Time
Server
Configure the
Server
Create a new /etc/ntp.conf file and place the following contents in the
file:
This first line will ignore all connections by default.:
# Ignore all NTP connections by default
restrict default ignore
Allow full control of our time service from the local host while the statement
seems odd (restrict) it really means allow with the following restrictions
which there will be none:
# Allow full access from localhost
restrict 127.0.0.1
Now enter the IP addresses of the servers you chose to update from:
# Servers and their restrictions
server 198.30.92.2
server 128.10.252.7
server 130.126.24.44
Set the restrictions for our upstream servers
restrict 198.30.92.2 mask 255.255.255.255 nomodify
restrict 128.10.252.7 mask 255.255.255.255 nomodify
restrict 130.126.24.44 mask 255.255.255.255 nomodify
32
Now allow whatever hosts/networks you are going to allow to query your
server for time for example:
# Allowed clients
restrict 10.0.0.0 mask 255.0.0.0 nomodify
restrict 172.16.0.0 mask 255.255.224.0 nomodify
restrict 192.168.0.0 mask 255.255.0.0 nomodify
restrict 207.169.53.0 mask 255.255.255.0 nomodify
The server in the /etc/ntp/step-tickers file will be the ones that your server will
sync with immediately when it boots up:
vim /etc/ntp/step-tickers
Now simply add the IP addresses of your upstream servers that youre getting
time from, one on each line, such as:
198.30.92.2
128.10.252.7
130.126.24.44
Thats it. Save and close the file.
Update Your
System Clock
Run the ntpdate command against each IP address of your upstream servers 2
or 3 times each. You should see the jitter come way down between the first
time you run it and the last:
ntpdate
ntpdate
ntpdate
ntpdate
ntpdate
ntpdate
Start your
Service
198.30.92.2
198.30.92.2
128.10.252.7
128.10.252.7
130.126.24.44
130.126.24.44
Now that ntp is running, to determine if it is synchronizing properly, issue the command (wait a
couple of minutes after starting the ntpd service before running this command):
ntpq p
remote
refid
st t when poll reach delay
offset
jitter
==============================================================================
LOCAL(0)
LOCAL(0)
10 l
1
64
3
0.000
0.000
0.015
*navobs1.oar.net .USNO.
1 u
5
64
1 222.555
68.548
0.015
+darkcity.cerias .GPS.
1 u
60
64
1 44.732 -19.367
0.015
+ntp-2.gw.uiuc.e truechimer.cso. 2 u
61
64
1 22.875 -27.707
0.015
A telltale sign that you dont have proper synchronization is when all the remote servers have
jitters of 4000 with delay and reach values of zero.
remote
refid
st t when poll reach
delay
offset jitter
==============================================================================
LOCAL(0)
LOCAL(0)
10 u
64
0
0.000
0.000 4000.00
navobs1.oar.net 0.0.0.0
16 u
64
0
0.000
0.000 4000.00
darkcity.cerias 0.0.0.0
16 u
64
0
0.000
0.000 4000.00
ntp-2.gw.uiuc.e 0.0.0.0
16 u
64
0
0.000
0.000 4000.00
ntptrace d v <time_server>
Test NTP
Want to test the whole thing? Set your system and hardware clock to a wacked date, like
follows:
date 0603008501999 (this sets the current time on the software clock to June 3, 1999,
8:50am
hwclock --systohc (this sets the hardware clock to match the software clock)
Now, reboot the server and see if both of the clocks re-synched properly by issuing the following
two commands to check the software and hardware clocks, respectively:
date
hwclock
If you see some errors such as set_rtc_mmss: cant update from x to x (where x = a
number), then you need to manually set the hardware clock. This error stems from a known
kernel issue (as of October 27, 2003) when the hardware clock is off from the software clock by
more than some amount (there seems to be some debate as to what that amount is). To fix this,
set the clock manually and reboot to see if the error(s) go away:
hwclock systohc
reboot
34
Basics
All bash scripts must tell the o/s what to use as the interpreter. The first line of any script should
be:
#!/bin/bash
You must make bash scripts executable.
chmod +x filename
Variables
Create a variable - just assign value. Variables are non-datatyped (a variable can hold strings,
numbers, etc. with out being defined as such).
varname=value
Access a variable by putting $ on the front of the name
echo $varname
Values passed in from the command line as arguments are accessed as $# where #= the index of
the variable in the array of values being passed in. This array is base 1 not base 0.
command var1 var2 var3 .... varX
$1 contains whatever var1 was, $2 contains whatever var2 was, etc.
Built in variables:
Variable Use
$1-$N
$?
$0
$*
"$@"
35
Quote Marks
Regular double quotes ("like these") make the shell ignore whitespace and count it all as one
argument being passed or string to use. Special characters inside are still noticed/obeyed.
Single quotes 'like this' make the interpreting shell ignore all special characters in whatever
string is being passed.
The back single quote marks (`command`) perform a different function. They are used when you
want to use the results of a command in another command. For example, if you wanted to set the
value of the variable contents equal to the list of files in the current directory, you would type the
following command: contents=`ls`, the results of the ls program are put in the variable contents.
Numeric Comparisons
int1 -eq int2
String Comparisons
str1 = str2
str1 != str2
str
-n str
-z str
File Comparisons
-d filename
-f filename
-r filename
-s filename
-w filename
-x filename
Expression Comparisons
!expression
expr1 -a expr2
expr1 -o expr2
If Statements
If...then
if [ expression ]
then
commands
fi
If..then...else
if [ expression ]
then
commands
else
commands
fi
If..then...else If...else
if [ expression ]
then
commands
elif [ expression2 ]
then
commands
else
commands
fi
37
Case select
case string1 in
str1)
commands;;
str2)
commands;;
*)
commands;;
esac
string1 is compared to str1 and str2. If one of these strings matches string1, the commands up
until the double semicolon (; ;) are executed. If neither str1 nor str2 matches string1, the
commands associated with the asterisk are executed. This is the default case condition because
the asterisk matches all strings.
Iteration (Loops)
for var1 in list
do
commands
done
This executes once for each item in the list. This list can be a variable that contains several words
separated by spaces (such as output from ls or cat), or it can be a list of values that is typed
directly into the statement. Each time through the loop, the variable var1 is assigned the current
item in the list, until the last one is reached.
while [ expression ]
do
commands
done
until [ expression ]
do
commands
done
Functions
Create a function:
fname(){
commands
}
Debugging
The shell has a number of flags that make debugging easier:
sh -n command
Read the shell script but don't execute the commands. IE. check syntax.
sh x command
Display commands and arguments as they're executed. In a lot of my shell scripts you'll see
# Uncomment the next line for testing
# set -x
See also:
http://www.linux.org/docs/ldp/howto/Bash-Prog-Intro-HOWTO.html
39
More Resources
Understanding Linux Configuration Files
http://www-106.ibm.com/developerworks/linux/library/l-config.html
40
Switch to the first text terminal. Under Linux you can have several (6 in standard setup)
terminals opened at the same time.
<Ctrl><Alt><Fn> (n=1..6)
Switch to the nth text terminal.
tty
Print the name of the terminal in which you are typing this command.
<Ctrl><Alt><F7>
Switch to the first GUI terminal (if X-windows is running on this terminal).
<Ctrl><Alt><Fn> (n=7..12)
Switch to the nth GUI terminal (if a GUI terminal is running on screen n-1). On default, nothing
is running on terminals
8 to 12, but you can run another server there.
<Tab>
(In a text terminal) Autocomplete the command if there is only one option, or else show all the
41
available options.
THIS SHORTCUT IS GREAT! It even works at LILO prompt!
<ArrowUp>
Scroll terminal output up. Work also at the login prompt, so you can scroll through your bootup
messages.
<Shift><PgDown>
(in X-windows) Change to the next X-server resolution (if you set up the X-server to more than
one resolution). For multiple resolutions on my standard SVGA card/monitor, I have the
following line in the file /etc/X11/XF86Config (the first resolution starts on default, the largest
determines the size of the "virtual screen"):
Modes "1024x768" "800x600" "640x480" "512x384" "480x300" "400x300" "1152x864"
<Ctrl><Alt><->
(in X-windows) Kill the current X-windows server. Use if the X-windows server crushes and
cannot be exited normally.
<Ctrl><Alt><Del>
Shut down the system and reboot. This is the normal shutdown command for a user at the textmode console. Don't just press the "reset" button for shutdown!
<Ctrl>c
Kill the current process (mostly in the text mode for small applications).
<Ctrl>d
Log out from the current terminal. See also the next command.
<Ctrl>d
Send [End-of-File] to the current process. Don't press it twice else you also log out (see the
previous command).
<Ctrl>s
Resume the transfer to the terminal. Try if your terminal mysteriously stops responding.
<Ctrl>z
Logout. I can also use logout for the same effect. (If you have started a second shell, e.g., using
bash the second shell will be exited and you will be back in the first shell, not logged out.)
reset
Restore a screwed-up terminal (a terminal showing funny characters) to default setting. Use if
you tried to "cat" a binary file. You may not be able to see the command as you type it.
<MiddleMouseButton>
Paste the text which is currently highlighted somewhere else. This is the normal "copy-paste"
operation in Linux. (It doesn't work with Netscape and WordPerfect which use the MS
Windows-style "copy-paste". It does work in the text terminal if you enabled "gpm" service
using "setup".) Best used with a Linux-ready 3-button mouse (Logitech or similar) or else set "3mouse button emulation").
~
(tilde) My home directory (normally the directory /home/my_login_name). For example, the
42
command cd ~/my_dir will change my working directory to the subdirectory "my_dir" under
my home directory. Typing just "cd" alone is an equivalent of the command "cd ~".
.
(dot) Current directory. For example, ./my_program will attempt to execute the file
"my_program" located in your current working directory.
..
(two dots) Directory parent to the current one. For example, the command cd .. will change my
current working directory one one level up.
7.2 Common Linux commands--system info
pwd
Print working directory, i.e., display the name of my current directory on the screen.
hostname
Print the name of the local host (the machine on which you are working). Use netconf (as root)
to change the name of the machine.
whoami
Print user id (uid) and his/her group id (gid), effective id (if different than the real id) and the
supplementary groups.
date
Print or change the operating system date and time. E.g., I could change the date and time to
2000-12-31 23:57 using this command:
date 123123572000
To set the hardware (BIOS) clock from the system (Linux) clock, use the command (as root)
setclock
time
Determine the amount of time that it takes for a process to complete + other info. Don't confuse
it with the date command. E.g. I can find out how long it takes to display a directory content
using:
time ls
who
(=remote who) Determine all users logged on your network. The rwho service must be enabled
for this command to run. If it isn't, run setup as root to enable "rwho".
finger user_name
Show the last (1000 or so) commands executed from the command line on the current account.
The "| more" causes the display to stop after each screenful.
uptime
(=print status) List the processes currently run by the current user.
ps axu | more
List all the processes currently running, even those without the controlling terminal, together
with the name of the user that owns each process.
top
Keep listing the currently running processes, sorted by cpu usage (top users first). In KDE, you
43
can get GUI-based Ktop from "K"menu under "System"-"Task Manager" (or by executing
"ktop" in an X-terminal).
uname -a
(= Unix name with option "all") Info on your (local) server. I can also use guname (in X-window
terminal) to display the info more nicely.
free
(=disk free) Print disk info about all the filesystems (in human-readable form)
du / -bh | more
(=disk usage) Print detailed disk usage for each subdirectory starting at the "/" (root) directory
(in human legible form).
cat /proc/cpuinfo
Cpu info--it show the content of the file cpuinfo. Note that the files in the /proc directory are
not real files--they are hooks to look at information available to the kernel.
cat /proc/interrupts
(As root. Use /sbin/lsmod to execute this command when you are a non-root user.) Show the
kernel modules currently loaded.
set|more
Show the content of the environment variable "PATH". This command can be used to show
other environment variables as well. Use "set" to see the full environment.
dmesg | less
Print kernel messages (the content of the so-called kernel ring buffer). Press "q" to quit "less".
Use less /var/log/dmesg to see what "dmesg" dumped into this file right after the last system
bootup.
7.3 Basic operations
any_command --help |more
Display a brief help on a command (works with most commands). "--help" works similar to DOS
"/h" switch. The "more" pipe is needed if the output is longer than one screen.
man topic
Display the contents of the system manual pages (help) on the topic. Try man man first. Press "q"
to quit the viewer. The command info topic works similar and may contain more up-to-date
information. Manual pages can be hard to read. Try any_command --help for short, easy to
digest help on a command. If more info needed, have a look to the directory /usr/doc. To
display manual page from a specific section, I may use something like in this example: man 3
exit (this displays an info on the command exit from section 3 of the manual pages).
apropos topic
Give me the list of the commands that have something to to do with my topic.
help command
ls
List the content of the current directory. Under Linux, the command "dir" is an alias to ls. Many
users have "ls" to be an alias to "ls --color".
ls -al |more
List the content of the current directory, all files (also those starting with a dot), and in a long
form. Pipe the output through the "more" command, so that the display pauses after each
screenful.
cd directory
Change directory. Using "cd" without the directory name will take you to your home directory.
"cd -" will take you to your previous directory and is a convenient way to toggle between two
directories. "cd .." will take you one directory up.
cp source destination
Copy files. E.g., cp /home/stan/existing_file_name . will copy a file to my current
working directory. Use the "-r" option (for recursive) to copy the contents of whole directories,
e.g. , cp -r my_existing/dir/ ~ will copy a subdirectory under my current working
directory to my home directory.
mcopy source destination
Copy a file from/to a DOS filesystem (no mounting necessary). E.g., mcopy a:\autoexec.bat
~/junk . See man mtools for related commands: mdir, mcd, mren, mmove, mdel, mmd, mrd,
mformat ....
mv source destination
Move or rename files. The same command is used for moving and renaming files and directories.
ln source destination
Create a hard link called destination to the file called source. The link appears as a copy of the
original files, but in reality only one copy of the file is kept, just two (or more) directory entries
point to it. Any changes the file are automatically visible throughout. When one directory entry
is removed, the other(s) stay(s) intact. The limitation of the hard links are: the files have to be on
the same filesystem, hard links to directories or special files are impossible.
ln -s source destination
Create a symbolic (soft) link called "destination" to the file called "source". The symbolic link
just specifies a path where to look for the file. In contradistinction to hard links, the source and
destination don't not have to tbe on the same filesystem. In comparison to hard links, the
drawback of symbolic links are: if the original file is removed, the link is "broken", symbolic
links can also create circular references (like circular references in spreadsheets or databases,
e.g., "a" points to "b" and "b" points back to "a").
rm files
Remove (delete) files. You must own the file in order to be able to remove it. On many systems,
you will be asked or confirmation of deleation, if you don't want this, use the "-f" (=force)
option, e.g., rm -f * will remove all files in my current working directory, no questions asked.
mkdir directory
(recursive remove) Remove files, directories, and their subdirectories. Careful with this
command as root--you can easily remove all files on the system with such a command executed
on the top of your directory tree, and there is no undelete in Linux (yet). But if you really wanted
to do it (reconsider), here is how (as root): rm -rf /*
cat filename | more
View the content of a text file called "filename", one page a time. The "|" is the "pipe" symbol
45
(on many American keyboards it shares the key with "\") The pipe makes the output stop after
each screenful. For long files, it is sometimes convenient to use the commands head and tail that
display just the beginning and the end of the file. If you happened to use "cat" a binary file and
your terminal displays funny characters afterwards, you can restore it with the command "reset".
less filename
Scroll through a content of a text file. Press q when done. "Less" is roughly equivalent to "more"
, the command you know from DOS, although very often "less" is more convenient than "more".
pico filename
Edit a text file using the simple and standard text editor called pico.
pico -w filename
Edit a text file, while disabling the long line wrap. Handy for editing configuration files, e.g.
/etc/fstab.
find / -name "filename"
Find the file called "filename" on your filesystem starting the search from the root directory "/".
The "filename" may contain wildcards (*,?).
locate filename
Find the file name of which contains the string "filename". Easier and faster than the previous
command but depends on a database that normally rebuilds at night.
./program_name
Change the date/time stamp of the file filename to the current time. Create an empty file if the
file does not exist.
xinit
Start an X-windows server and the default windows manager. Works like typing "win" under
DOS with Win3.1
startx -- :1
Start another X-windows session on the display 1 (the default is opened on display 0). You can
have several GUI terminals running concurrently. Switch between them using <Ctrl><Alt><F7>,
<Ctrl><Alt><F8>, etc.
xterm
(in X terminal) Run a simple X-windows terminal. Typing exit will close it. There are other,
more advanced "virtual" terminals for X-windows. I like the popular ones: konsole and kvt
(both come with kde) and gnome-terminal (comes with gnome). If you need something really
fancy-looking, try Eterm.
xboing
(in X terminal). Very nice, old-fashioned game. Many small games/programs are probably
installed on your system. I also like xboard (chess).
shutdown -h now
(as root) Shut down the system to a halt. Mostly used for a remote shutdown. Use
<Ctrl><Alt><Del> for a shutdown at the console (which can be done by any user).
halt
reboot
(as root, two commands) Halt or reboot the machine. Used for remote shutdown, simpler to type
than the previous command.
Network apps
netscape
(in X terminal) Run netscape (requires a separate Netscape installation). The current versions of
46
Netscape (4.x) are known to be big and buggy. They occasionally crash by vanishing (no other
harm done). Also, when not connected to the network , Netscape likes to refuse to do anything
(looks like it hanged)-it revives when you connect.
netscape -display host:0.0
(in X terminal) Run netscape on the current machine and direct the output to machine named
"host" display 0 screen 0. Your current machine must have a permission to display on the
machine "host" (typically given by executing the command xhost current_machine_name in
the xterminal of the machine host. Other X-windows program can be run remotely the same way.
lynx file.html
View an html file or browse the net from the text mode.
pine
A good text-mode mail reader. Another good and standard one is elm. Your Netscape mail will
read the mail from your Internet account. pine will let you read the "local" mail, e.g. the mail
your son or a cron process sends to you from a computer on your home network. The command
mail could also be used for reading/composing mail, but it would be inconvenient--it is meant to
be used in scripts for automation.
elm
A basic operating system tool for e-mail. Look at the previous commands for a better e-mail
reader. mail is good if you wanted to send an e-mail from a shell script.
licq
(in X term) An icq "instant messaging" client. Another good one is kxicq. Older distributions
don't have an icq client installed, you have to do download one and install it.
talk username1
Talk to another user currently logged on your machine (or use "talk username1@machinename"
to talk to a user on a different computer) . To accept the invitation to the conversation, type the
command "talk username2". If somebody is trying to talk to you and it disrupts your work,
your may use the command "mesg n" to refuse accepting messages. You may want to use "who"
or "rwho" to determine the users who are currently logged-in.
mc
Launch the "Midnight Commander" file manager (looks like "Norton Commander" for Linux).
telnet server
Connect to another machine using the TELNET protocol. Use a remote machine name or IP
address. You will be prompted for your login name and password--you must have an account on
the remote machine to login. Telnet will connect you to another machine and let you operate on
it as if you were sitting at its keyboard (almost). Telnet is not very secure--everything you type
goes in open text, even your password!
rlogin server
(=remote login) Connect to another machine. The login name/password from your current
session is used; if it fails you are prompted for a password.
rsh server
(=remote shell) Yet another way to connect to a remote machine. The login name/password from
your current session is used; if it fails you are prompted for a password.
ftp server
Ftp another machine. (There is also ncftp which adds extra features and gftp for GUI .) Ftp is
good for copying files to/from a remote machine. Try user "anonymous" if you don't have an
account on the remote server. After connection, use "?" to see the list of available ftp
47
commands. The essential ftp command are: ls (see the files on the remote system), ASCII,
binary (set the file transfer mode to either text or binary, important that you select the proper
one ), get (copy a file from the remote system to the local system), mget (get many files at
once), put (copy a file from the local system to the remote system), mput (put many files at
once), bye (disconnect). For automation in a script, you may want to use ncftpput and
ncftpget, for example:
ncftpput -u my_user_name -p my_password -a remote.host.domain remote_dir
*local.html
minicom
(=tape archiver) Untar a tarred and compressed tarball (*.tar.gz or *.tgz) that you downloaded
from the Internet.
tar -xvf filename.tar
Decompress a zipped file (*.gz" or *.z). Use gzip (also zip or compress) if you wanted to
compress files to this file format.
bunzip2 filename.bz2
(=big unzip) Decompress a file (*.bz2) zipped with bzip2 compression utility. Used for big files.
unzip filename.zip
Decompress a file (*.zip) zipped with a compression utility compatible with PKZIP for DOS.
unarj e filename.arj
text files in e-mail (uuencode transforms any file into an ASCII file).
7.4 Process control
ps
(=print status) Display the list of currently running processes with their process IDs (PID)
numbers. Use ps axu to see all processes currently running on your system (also those of other
users or without a controlling terminal), each with the name of the owner. Use "top" to keep
listing the processes currently running.
fg PID
Send the process to the background. Opposite to fg. The same can be accomplished with
<Ctrl>z. If you have stopped jobs, you have to type exit twice in row to log out.
any_command&
Run any command in the background (the symbol "&" means "run the proceeding command in
the background").
batch any_command
Run any command (usually one that is going to take more time) when the system load is low. I
can logout, and the process will keep running.
at 17:00
Execute a command at a specified time. You will be prompted for the command(s) to run, until
you press <Ctrl>d.
kill PID
Force a process shutdown. First determine the PID of the process to kill using ps.
48
killall program_name
(in an xwindow terminal) Kill a GUI-based program with mouse. (Point with your mouse cursor
at the window of the process you want to kill and click.)
lpc
(as root) Check and control the printer(s). Type "?" to see the list of available commands.
lpq
Show the content of the printer queue. Under KDE (X-Windows), you may use GUI-based
"Printer Queue" available from "K"menu-Utilities.
lprm job_number
Run program_name adjusting its priority. Since the priority is not specified in this example, it
will be adjusted by 10 (the process will run slower), from the default value (usually 0). The
lower the number (of "niceness" to other users on the system), the higher the priority. The
priority value may be in the range -20 to 19. Only root may specify negative values. Use "top" to
display the priorities of the running processes.
renice -1 PID
(as root) Change the priority of a running process to -1. Normal users can only adjust processes
they own, and only up from the current value (make them run slower).
<Ctrl>c, <Ctrl>z, <Ctrl>s, and <Ctrl>q also belong to this chapter but they were described
previously. In short they mean: stop the current command, send the current command to the
background, stop the data transfer, resume the data transfer.
7.5 Basic administration commands
printtool
(as root in X-terminal) Configuration tool for your printer(s). Settings go to the file
/etc/printcap.
setup
(as root) Configure mouse, soundcard, keyboard, X-windows, system services. There are many
distibution-specific configuration utilities, setup is the default on RedHat. Mandrake 7.0 offers
very nice DrakConf .
linuxconfig
(as root, either in text or graphical mode). You can access and change hundreds of setting from
it. Very powerful--don't change too many things at the same time, and be careful with changing
entries you don't understand.
xvidtune
(in X-terminal). Adjust the settings of the graphical display for all resolutions so as to eliminate
black bands, shift the display right/left/up/down, etc. (First use the knobs on your monitor to fit
your text mode correctly on the screen.) To make the changes permanent, display the frequencies
on the screen and transfer them to the setup file /etc/X11/XF86Config.
alias ls="ls --color=tty"
Create an alias for the command "ls" to enhance its format with color. In this example, the alias
is also called "ls" and the "color" option is only envoke when the output is done to a terminal
(not to files). Put the alias into the file /etc/bashrc if you would like the alias to be always
accessible to all users on the system. Type "alias" alone to see the list of aliases on your
system.
49
adduser user_name
Create a new account (you must be root). E.g., adduser barbara Don't forget to set up the
password for the new user in the next step. The user home directory is /home/user_name.
useradd user_name
Remove an account (you must be a root). The user's home directory and the undelivered mail
must be dealt with separately (manually because you have to decide what to do with the files).
groupadd group_name
Create a new group on your system. Non-essential but can be handy even on a home machine
with a small number of users.
passwd
Change the password on your current account. If you are root, you can change the password for
any user using: passwd user_name
chmod perm filename
(=change mode) Change the file access permission for the files you own (unless you are root in
which case you can change any file). You can make a file accessible in three modes: read (r),
write (w), execute (x) to three classes of users: owner (u), members of the same group as the
owner (g), others on the system (o). Check the current access permissions using:
ls -l filename
The first triplet shows the file permission for the owner of the file, the second for his/her group,
the third for others. A "no" permission is shown as "-".
E.g., this command will add the permission to read the file "junk" to all (=user+group+others):
chmod a+r junk
This command will remove the permission to execute the file junk from others:
chmod o-x junk
Change the file owner and group. You should use these two commands after you copy a file for
use by somebody else.
su
(=substitute user id) Assume the superuser (=root) identity (you will be prompted for the
password). Type "exit" to return you to your previous login. Don't habitually work on your
machine as root. The root account is for administration and the su command is to ease your
access to the administration account when you require it. You can also use "su" to assume any
other user identity, e.g. su barbara will make me "barbara" (password required unless I am a
superuser).
kernelcfg
(as root in X terminal). GUI to to add/remove kernel modules. You can do the same from the
command line using the command "insmod", but "insmode" is less "newbie-friendly".
lsmod
List currently loaded kernel modules. A module is like a device driver--it provides operating
system kernel support for a particular piece of hardware or feature.
modprobe -l |more
List all the modules available for your kernel. The available modules are determined by how
your Linux kernel was compliled. Every possible module/feature can be compiled on linux as
50
either "hard wired" (fast, non-removable), "module" (maybe slower, but loaded/removable on
demand), or "no" (no support for this feature at all).
insmod parport
insmod ppa
(as root) Insert modules into the kernel (a module is roughly an equivalent of a DOS device
driver). This example shows how to insert the modules for support of the external parallel port
zip drive (it appears to be a problem to get the external zip drive to work in any other way under
RH6.0 ).
rmmod module_name
(as root, not essential). Remove the module module_name from the kernel.
setserial /dev/cua0 port 0x03f8 irq 4
(as root) Set a serial port to a non-standard setting. The example here shows the standard setting
for the first serial port (cua0 or ttyS0). The standard PC settings for the second serial port (cua1or
ttyS1) are: address of i/o port 0x02f8, irq 3. The third serial port (cua2 or ttyS2): 0x03e8, irq 4.
The forth serial port (cua3 or ttyS3): 0x02e8, irq 3. Add your setting to /etc/rc.d/rc.local if
you want it to be set at the boot time. See man setserial for good a overview.
fdisk
(as root) Linux hard drive partitioning utility (DOS has a utility with the same name).
cd /usr/src/linux-2.0.36
make xconfig
(as root in X terminal). Nice GUI front-end for configuration of the kernel options in preparation
for compilation of your customized kernel. (The directory name contains the version of your
Linux kernel so you may need to modify the directory name if your Linux kernel version is
different than 2.0.36 used in this example. You also need the "Tk" interpreter and the kernel
source code installed. ) The alternatives to "make xconfig" are: "make config" (runs a scripts
that asks you questions in the text mode) and "make menuconfig" (runs a text-based menu-driven
configuration utility). Try: less /usr/doc/HOWTO/Kernel-HOWTO for more information.
After the configuration, you may choose to proceed with kernel compilation of the new kernel
by issuing the following commands:
make dep
make zImage
The last command will take some time to complete (maybe 0.5 h, depending on your hardware).
It produces the file "zImage", which is your new Linux kernel. Next:
make modules
make modules_install
Read: /usr/doc/HOWTO/Kernel-HOWTO for information on how to install the new kernel. You
will probably also find it useful to read "man depmode". Configuration, compilation and
installation of a new kernel is not difficult but it CAN lead to problems if you don't know what
you are doing.
Compilation of a kernel is a good way to test your hardware, because it involves a massive
amount of computing. If your hardware is "flaky", you will most likely receive the "signal 11"
error (read the beatiful /usr/doc/FAQ/txt/GCC-SIG11-FAQ). See this for details on kernel
upgrade.
depmod -a
(as root) Build the module dependency table for the kernel. This can, for example, be useful after
installing and booting a new kernel. Use "modprobe -a" to load the modules.
ldconfig
(as root) Re-create the bindings and the cache for the loader of dynamic libraries ("ld"). You may
want to run ldconfig after an installation of new dynamically linked libraries on your system. (It
51
is also re-run every time you boot the computer, so if you reboot you don't have to run it
manually.)
mknod /dev/fd0 b 2 0
(=make node, as root) Create a device file. This example shows how to create a device file
associated with your first floppy drive and could be useful if you happened to accidentally erase
it. The options are: b=block mode device (c=character mode device, p=FIFO device,
u=unbuffered character mode device). The two integers specify the major and the minor device
number.
fdformat /dev/fd0H1440
mkfs -c -t ext2
(=floppy disk format, two commands, as root) Perform a low-level formatting of a floppy in the
first floppy drive (/dev/fd0), high density (1440 kB). Then make a Linux filesystem (-t ext2),
checking/marking bad blocks (-c ). Making the files system is an equivalent to the high-level
format.
badblocks /dev/fd01440 1440
(as root) Check a high-density floppy for bad blocks and display the results on the screen. The
parameter "1440" specifies that 1440 blocks are to be checked. This command does not modify
the floppy.
fsck -t ext2 /dev/hda2
(=file system check, as root) Check and repair a filesystem. The example uses the partition hda2,
filesystem type ext2.
dd if=/dev/fd0H1440 of=floppy_image
dd if=floppy_image of=/dev/fd0H1440
(two commands, dd="data duplicator") Create an image of a floppy to the file called
"floppy_image" in the current directory. Then copy floppy_image (file) to another floppy disk.
Works like DOS "DISKCOPY".
Program installation
rpm -ivh filename.rpm
(=RedhatPackageManager, query, package, list.) Read the info on the content of a yet uninstalled
package filename.rpm.
rpm -qpl filename.rpm
(=RedhatPackageManager, query, file.) Find out the name of the *.rpm package to which the file
filename (on your hardrive) belongs.
rpm -e packagename
(in X terminal, as root if you want to be able to install packages) GUI fronts to the Red Hat
Package Manager (rpm). "glint" comes with RH5.2, "gnorpm" with RH6.0, "kpackage" comes
with RH6.1 or must be installed separately but is the best of the three. Use any of them to view
which software packages are installed on your system and the what not-yet-installed packages
52
are available on your RedHat CD, display the info about the packages, and install them if you
want (installation must be done as root).
Accessing drives/partitions
mount
See here for details on mounting drives. Examples are shown in the next commands.
mount -t auto /dev/fd0 /mnt/floppy
(as root) Mount the floppy. The directory /mnt/floppy must exist, be empty and NOT be your
current directory.
mount -t auto /dev/cdrom /mnt/cdrom
(as root) Mount the CD. You may need to create/modify the /dev/cdrom file depending where
your CDROM is. The directory /mnt/cdrom must exist, be empty and NOT be your current
directory.
mount /mnt/floppy
(as user or root) Mount a floppy as user. The file /etc/fstab must be set up to do this. The
directory /mnt/floppy must not be your current directory.
mount /mnt/cdrom
(as user or root) Mount a CD as user. The file /etc/fstab must be set up to do this. The
directory /mnt/cdrom must not be your current directory.
umount /mnt/floppy
Unmount the floppy. The directory /mnt/floppy must not be your (or anybody else's) current
working directory. Depending on your setup, you might not be able to unmount a drive that you
didn't mount.
7.6 Network administration tools
netconf
Check if you can contact another machine (give the machine's name or IP), press <Ctrl>C when
done (it keeps going).
route -n
Query your default domain name server (DNS) for an Internet name (or IP number) host_to_find.
This way you can check if your DNS works. You can also find out the name of the host of which
you only know the IP number.
traceroute host_to_trace
Have a look how you messages trave to host_to_trace (which is either a host name or IP
number).
ipfwadm -F -p m
(for RH5.2, seen next command for RH6.0) Set up the firewall IP forwarding policy to
masquerading. (Not very secure but simple.) Purpose: all computers from your home network
will appear to the outside world as one very busy machine and, for example, you will be allowed
to browse the Internet from all computers at once.
echo 1 > /proc/sys/net/ipv4/ip_forward
ipfwadm-wrapper -F -p deny
ipfwadm-wrapper -F -a m -S xxx.xxx.xxx.0/24 -D 0.0.0.0/0
(three commands, RH6.0). Does the same as the previous command. Substitute the "x"s with
digits of your class "C" IP address that you assigned to your home network. See here for more
details. In RH6.1, masquarading seems broken to me--I think I will install Mandrake Linux:).
53
ifconfig
(as root) Display info on the network interfaces currently active (ethernet, ppp, etc). Your first
ethernet should show up as eth0, second as eth1, etc, first ppp over modem as ppp0, second as
ppp1, etc. The "lo" is the "loopback only" interface which should be always active. Use the
options (see ifconfig --help) to configure the interfaces.
ifup interface_name
(/sbin/ifup to it run as a user) Startup a network interface. E.g.:
ifup eth0
ifup ppp0
Users can start up or shutdown the ppp interface only when the right permission was checked
during the ppp setup (using netconf ). To start a ppp interface (dial-up connection), I normally
use kppp available under kde menu "internet".
ifdown interface_name
(/sbin/ifdown to run it as a user). Shut down the network interface. E.g.: ifdown ppp0 Also,
Get a free coffee cup holder :))). (Eject the CD ROM tray).
play my_file.wav
(in X terminal) Start the program to downolad mp3 files that other users of napster have
displayed for downloading. Really cool!
cdparanoia -B
"1-"
(CD ripper) Read the contents of an audio CD and save it into wavefiles in the current
directories, one track per wavefile. The "1-"
means "from track 1 to the last". -B forces putting each track into a separate file.
playmidi my_file.mid
Play a midi file. playmidi -r my_file.mid will display text mode effects on the screen.
sox
(argument not given here) Convert from almost any audio file format to another (but not mp3s).
See man sox.
Graphics-related commands
kghostview my_file.ps
Display a postscript file on screen. I can also use the older-looking ghostview or gv for the
same end effect.
ps2pdf my_file.ps my_file.pdf
Make a pdf (Adobe portable document format) file from a postscript file.
gimp
(in X terminal) A humble looking but very powerful image processor. Takes some learning to
use, but it is great for artists, there is almost nothing you can't do with gimp. Use your mouse
54
right button to get local menus, and learn how to use layers. Save your file in the native gimp file
format *.xcf (to preserve layers) and only then flatten it and save as png (or whatever). There is
a large user manual /usr/
gphoto
Convert the propriatory giff graphics into a raw, portable pnm file. Then convert the pnm into a
png file, which is a newer and better standard for Internet pictures (better technically plus there
is no danger of being sued by the owner of giff patents).
55
Understanding Services
Please read the guide on managing services in Fedora. This includes an explanation for
services/daemons, runlevels and various tools available to manage your services.
To control services either use chkconfig or ntsysv if you are using the command line, or use
system-config-services in the GUI. Gnome users: System > Administration > Server Settings
> Services.
Individual Services
The following is a brief explanation on usage and recommendations for services packaged with
Fedora Core 5. This is not an exhaustive list. Be careful, do not disable things that you're not
sure if need or if you do not understand or know what they are.
DO NOT DISABLE THE FOLLOWING (unless you know what you are doing).
acpid, haldaemon, messagebus, klogd, network, syslogd
Make sure to apply your changes to runlevel 5 *AND* 3.
NetworkManager, NetworkManagerDispatcher
NetworkManager is daemon meant to automate switching between network
connections. Many laptop users who switch between Wireless WiFi connections
and Ethernet connections may find this useful. Most stationary computers should
have this disabled. Some DHCP users may require this.
acpid
Advanced Configuration and Power Interface daemon which controls and allows
interfacing to power management and certain input devices. It is recommended
to be enabled for all laptops, and most desktops. Some servers may not require
acpi. Common things supported are the "Power Switch", "Battery Monitor",
"Laptop Lid Switch", "Laptop Display Brightness", "Hibernate", "Suspend", etc.
apmd
Is used by some laptops and older hardware. If your computer supports acpi,
then apmd should probably be disabled.
auditd
This saves audit records generated by the kernel. Not entirely sure how this
information is used, however it is useful for diagnosing issues with SELinux. For
now I have this enabled. This is optional, however it may useful for servers or
machines with multiple users and highly recommended for SELinux users.
autofs
This mounts removable disks (such as USB harddrives) on demand. It is
recommended to keep this enabled if you use removable media.
avahi-daemon, avahi-dnsconfd
Avahi is an implementation of zeroconf and is useful for detecting devices and
services on local network without a DNS server. This is also the same as mDNS.
Most likely this is unnecessary unless you have compatible devices/services. I
have this disabled.
bluetooth, hcid, hidd, sdpd
Bluetooth is for portable local wireless devices (NOT wifi,802.11). Some laptops
come with bluetooth support. There are bluetooth mice, headsets and cell phone
accessories. Most people do not have bluetooth support or devices, and should
disable this. Other services with bluetooth: hcid manages all devices, hidd
provides support for input devices (keyboard, mouse).
cpuspeed
This throttles your CPU runtime frequency to save power. Many modern laptop
CPU's support this feature and now some desktops also support this. Most people
should enable only if they are users of Pentium-M, Centrino, AMD PowerNow,
Transmetta, Intel SpeedStep, Athlon-64 hardware.
cron
See above.
cupsd, cups-config-daemon
Used for printing. These should be enabled only if you have CUPS compatible
printer that works in Fedora.
dc_client, dc_server
Distcache is for distributed session caching. It is primarily for SSL/TLS servers.
Apache can use this. Most desktop users should have these disabled.
dhcdbd
This basically an interface for the DBUS system to control DHCP on your
computer. It can be left to the default disabled state.
diskdump, netdump
Diskdump is a mechanism to help debug kernel crashes. It save a "dump" which
can be later analyzed. Netdump does something similar over the network. Unless
you are diagnosing a problem, these should be left as disabled.
57
firstboot
This service is specific to Fedora's installation process meant to perform certain
tasks that should only be executed once upon booting after installation. Even
though it verifies it has been run before, it can be disabled.
gpm
This is the console mouse pointer (no graphics). If you do not use the text
console (CTRL-ALT-F1,F2..) then disable this. However I leave this enabled for
runlevel 3 and disabled for runlevel 5.
hidd
See bluetooth.
hplip, hpiod, hpssd
HPLIP is a service to support HP printers in Linux, including Inkjet, DeskJet,
OfficeJet, Photosmart, Business Inkjet and some LaserJet printers. This
supported by HP through HP Linux Printing Project. HPLIP should be enabled
only if you have a supported compatible printer.
iptables
This is the standard Linux software firewall. This is required if you are directly
connected to internet (cable, DSL, T1). It is not required if you use a hardware
firewall (D-Link, Netgear, Linksys, etc) but it is highly recommended.
irqbalance
This service is to increase performance across processors on a multiprocessor
system. Since most people do not have multiple processors, it should be
disabled. However I do not know how it affects multi-core CPU's or
hyperthreaded CPU's (?). There should be no problems on single CPU systems
that do not use this.
isdn
This is another form of internet connect service/hardware. Unless you have an
ISDN modem, disable this.
kudzu
This runs the hardware probe, and optionally configures changed hardware. If
you swap hardware or need to detect/re-detect hardware this can be left
enabled. However most desktop or servers can disable this and run it only when
necessary.
lm_sensors
This monitors motherboard sensor values or specific hardware (commonly used
with laptops). It is useful for watching realtime values for PC health, etc. This is
also popular with GKrellM users. More information on lm_sensors homepage. It is
recommended to disable this unless you have a need.
mdmonitor
Is useful for monitoring Software RAID or LVM information. It is not a critical
service and be disabled.
58
messagebus
This is an IPC (Interprocess Communication) service for Linux. Specifically this
communicates with dbus, a critical component. It is highly recommended to leave
this enabled.
netdump
See diskdump.
netplugd
Netplugd can monitor network interfaces and executes commands when their
state changes. This can be left to default disabled.
netfs
This is used for automatic mounting of any shared network file space such as
NFS, Samba, etc on bootup. Useful if you connect to another server or filesharing
on your local network. Most single desktop/laptop users should have this
disabled.
nfs, nfslock
This the standard network file sharing for Unix/Linux/BSD style operating
systems. Unless you require to share data in this manner, disable this.
ntpd
This automatically updates the system time from the internet. Mentioned in the
installation process. If you have an active ("always-on") internet connection it is
recommended you enable this, but it is not required.
portmap
This is complementary service to NFS (file sharing) and/or NIS (authentication).
Unless you use those services you should disable this.
readahead, readahead_early
This services is to improve startup performance by preloading certain
applications into memory. If you wish to startup faster leave this enabled.
SSH allows other users to log into or run applications on your computer from
another computer on your network or remotely. This is a potential security issue.
This is not needed if you have no other computers or no need to login from a
remote location (work, school, etc.). Most likely this should be disabled.
xinetd
This is a special service. It can launch multiple services based on a request to a
specific port. For example: telnet is typically connected to port 23. If there is a
request for telnet access that xinetd detects on port 23, then only will the telnet
daemon be executed. For convenience this can be left to enabled. Run systemconfig-services and go to On Demand Services -or- run chkconfig --list and
look for the xinetd output to show which services are connected to xinetd.
60