Friday, April 25, 2008

Quick Linux Commands

1. How to have a stop watch scenario from command line terminal?

# time cat

Press Ctrl+C

2. How to measure the time of executing any executable command?

# time firefox

wait 5 seconds and close the application

3. How to CD to a user's home directory?

# cd ~userhome

4. How to CD back to home folder of a currently logged in user?

# cd

5. How to CD back to previous directory?

# cd -

6. How to show all active host IP address?

# ip address

7. How to list out all your iptables rules?

# iptables -L

8. How to save your currently loaded firewall iptable rules?

# iptables-save

9. How to download a file using wget?

# wget -c "http://website.com/file.rpm"

10. How to limit your download rate with wget?

# wget --limit-rate=30k "http://vertito.com/file.rpm"

11. How to download multiple files in one shot?

# wget -c "ftp://vertito.org/file[1-9].iso

12. How to find windows machine with shared folders?

# findsmb

13. How to look for windows netbios name?

# nmblookup -A windows-ip-address

14. How to browse for computers like network neighborhood does?

# smbtree

15. How list folder shared by a particular windows machine?

# smbclient -L windows-machine

16. How to diplay calendar without X?

# cal
# cal -3

17. How to list out all harddisk partition?

# cat /proc/partitions
# fdisk -l

18. How to list out all mounted and labeled harddisk partition?

# mount -l

19. How to show host reboot history?

# last reboot

20. How to get CPU info?

# cat /proc/cpuinfo

21. How to show all interrupts?

# cat /proc/interrupts

22. How to show last successful login users?

# lastlog

23. How to search for a yet unknown package from web repo?

# yum search *packagemaybe*
# yum whatprovides packagemaybe

24. How to setup a shell with yum?

# yum shell

25. How to use yum locally?

# yum localinstall packagename

26. How to find file with 750 file permission?

# find / -type f -perm 750

27. How to find all files not owned by any user?

# find / -nouser

28. How to find all files owned by a user?

# find /home -user vertito

29. How to find files by group name?

# find /home -group vertito

30. How to change timestamp of a file?

# touch -c -t 0707280337 testfile.txt
(YYMMDDhhmm)

31. How to change ownership of a file?

# chown user1:user1 testfile.txt

32. How to set user password details and expiration?

# chage username

33. How to change default home directory of a user?

# usermod -d /new-default-directory username

34. How to change a user finger information?

# chfn username

35. How to change a user shell information?

# chsh username

36. How to change file mode bits?

# chmod testfile.txt

37. How to change and update (multiple) user passwords in batch mode?

# chpasswd

38. How to make an ISO image from contents of a directory?

# mkisofs -V label-name -r directory-name > iso-image.iso

39. How to make an ISO image from contents of a directory and zip it in one shot?

# mkisofs -V label-name -r directory-name | gzip > iso-image.iso.gz

40. Oh, how to eject a DVD/CD disk from a mounted DVD/CD drive?

# eject

41. How to clear or erase all data from a mounted DVDRW / CDRW disk?

# cdrecord -v dev=/dev/cdrom blank=fast

42. How to add an ext3 journal to a filesystem ?

# tune2fs -j /dev/sdb1

43. How to create ext2/ext3 filesystem with bad block checking?

# mkfs.ext3 -c /dev/sdb1
# mkfs.ext2 -c /dev/sdb1

44. How to combine and sort multiple raw files in one shot?

# sort file1 file2 | uniq > newfile

45. How to compare two text files?

# diff file1 file2

46. How to get more memory information?

# cat /proc/meminfo

47. How to get the maximum number of threads of your host?

# cat /proc/sys/kernel/threads-max

48. How to get the file properties of a file or folder?

# stat testfile.txt
# stat foldername

49. How to backup harddisk to another host via ssh?

# dd bs=1M if=/dev/sda | gzip | ssh username@remote-ip-address 'dd of=hda.gz'

50. How to run a command as another user?

# runuser another-user script-name-or-program

Alert mail for root login

# Login to your server and su to root..

2. cd /root

3. pico .bashrc

4. Scroll to the end of the file then add the following:
echo 'ALERT - Root Shell Access (YourserverName) on:' `date` `who` | mail -s "Alert: Root Access from `who | cut -d"(" -f2 | cut -d")" -f1`" you@yourdomain.com

Replace YourServerName with the handle for your actual server
Replace you@yourdomain.com with your actual email address

5. Crtl + X then Y

Now logout of SSH, close the connection and log back in! You should receive an email address of the root login alert a few minutes afterwards.

Thursday, April 24, 2008





Tips for successful Kernel Recompilation in Linux
 
"Kernel compilation is a tough nut to crack" - Most frequently this would be followed by a sigh if the recompiled kernel is not booting up. Though the nut has the look of a tough one to crack, kernel recompilation is still an inescapable affair that every Linux system administrator runs into, sooner or later. I too had to. With this article, I intend to walk you through the phases of compiling a kernel. I am sure it will inspire confidence in you so that compiling a kernel is no longer a "mission impossible".
What is a kernel?

Keeping it simple, kernel is the central part of most of the operating systems. The main functions of kernel include process management,resource management etc. It is the first part of operating system that is loaded in to the RAM when the machine is booted and it will remain in the main memory. Since the kernel stays in the main memory, it is important that it should be as small as possible.

In Linux, kernel is a single file called vmlinuz which is stored in the folder /boot, where vm represents virtual memory and z at the end of the filename denotes that it is compressed.
When do we recompile a kernel?
To reduce the size of the kernel:

Suppose you are a Linux fanatic and you need an OS in your mobile. The typical OS you get has the all the miscellaneous components and has size in many MB s, which you can't afford in your mobile. If I were you, I would do a kernel recompilation, and remove unwanted modules.

When the size of the kernel is reduced removing the unwanted items, less memory will be used which in turn will increase the resource available to applications.
To add or remove support for devices:

For each device, a device driver is needed for communicating with the operating system. For example, if a USB device is attached to a computer, we need to enable the corresponding device driver for it to work. In technical terms, the support for USB driver is to be enabled in the kernel.
To modify system parameters:

System parameters include high memory support, quota support etc. For managing physical memory above 4 GB, high memory support (64 GB) needs to be enabled.
How do we recompile a kernel?
Verify and update the packages required
Obtain kernel source
Obtain current hardware details
Configure kernel
Build kernel
Configure the Boot loader
Reboot the server
1. Verify and update the packages required

You need to do this step only if you upgrade the kernel from version 2.4 to 2.6. You can skip this step if it is a 2.6.x to 2.6.x upgrade.

Before upgrading the kernel, you need to make sure that your system is capable of accepting the new kernel. Check the utilities that interact with your system, and verify that they are up-to-date. If they are not, go ahead and upgrade them first.

The main packages to be checked and upgraded are : binutils, e2fsprogs, procps, gcc and module-init-tools

You should take extreme care while upgrading module-init-tools. A module is a piece of code that can be inserted into the kernel on demand. Module-init-tools provide utilities for managing Linux kernel modules - for loading, unloading,listing and removing modules.

The main utilities available are :
insmod
rmmod
modprobe
depmod
lsmod

Both modprobe and insmod are used to insert modules. The only difference is that insmod doesn't know the location of the module and is unaware of dependencies. Modprobe does this by parsing the file /lib/modules//modules.dep

How to install module-init-tools

Get the source http://www.kernel.org/pub/linux/utils/kernel/module-init-tools/module-init-tools-3.2.2.tar.gz to the server using wget and untar it.
tar -zxf module-init-tools-3.2.2.tar.gz
2. Configure it.
cd module-init-tools-3.2.2
./configure --prefix=/
3. Rename the existing 2.4 version of this utility as utility.old
make moveold
4. Build and install.
make
make install
5. Run the script generate-modprobe.conf to convert the entries in the module configuration file for kernel version 2.4 ( /etc/modules.conf ) to a file used by kernel version 2.6 (/etc/modprobe.conf)
./generate-modprobe.conf /etc/modprobe.conf
6. Check the version of current module-init-tools
depmod -V
2. Obtain the Kernel Source

Get the kernel source from http://www.kernel.org/pub/linux/kernel/v2.6/

You can download the source to the /usr/src/kernels folder in your server. If you are planning to recompile your kernel to version 2.6.19.2, the steps would be :
[root]#cd /usr/src/kernels
[root]#wget http://www.kernel.org/pub/linux/kernel/v2.6/linux-2.6.19.2.tar.gz
[root]#tar zxf linux-2.6.19.2.tar.gz
[root]#cd linux-2.6.19.2
3. Obtain the Current Hardware Details

The current Hardware details can be obtained using the following commands:
lspci

This utility gives the details about the network card and all devices attached to the machine. If you type lspci and get an error "lscpi: command not found", you will have to install pciutils-2.1.99.test8-3.4 rpm in the server.

A typical lspci output will be as follows :
[root@XXXXX ~]# lspci
00:01.0 PCI bridge: Broadcom BCM5785 [HT1000] PCI/PCI-X Bridge
00:02.0 Host bridge: Broadcom BCM5785 [HT1000] Legacy South Bridge
00:02.1 IDE interface: Broadcom BCM5785 [HT1000] IDE
00:02.2 ISA bridge: Broadcom BCM5785 [HT1000] LPC
00:03.0 USB Controller: Broadcom BCM5785 [HT1000] USB (rev 01)
00:03.1 USB Controller: Broadcom BCM5785 [HT1000] USB (rev 01)
00:03.2 USB Controller: Broadcom BCM5785 [HT1000] USB (rev 01)
00:05.0 VGA compatible controller: ATI Technologies Inc Rage XL (rev 27)
00:18.0 Host bridge: Advanced Micro Devices [AMD]
K8 [Athlon64/Opteron] HyperTransport Technology Configuration
00:18.1 Host bridge: Advanced Micro Devices [AMD]
K8 [Athlon64/Opteron] Address Map
00:18.2 Host bridge: Advanced Micro Devices [AMD]
K8 [Athlon64/Opteron] DRAM Controller
00:18.3 Host bridge: Advanced Micro Devices [AMD]
K8 [Athlon64/Opteron] Miscellaneous Control
01:0d.0 PCI bridge: Broadcom BCM5785 [HT1000]
PCI/PCI-X Bridge (rev b2)
01:0e.0 RAID bus controller: Broadcom BCM5785 [HT1000]
SATA (Native SATA Mode)
02:03.0 Ethernet controller: Broadcom Corporation
NetXtreme BCM5704 Gigabit Ethernet (rev 10)
02:03.1 Ethernet controller: Broadcom Corporation
NetXtreme BCM5704 Gigabit Ethernet (rev 10)
[root@XXXXX ~]#
cat /proc/cpuinfo

The processor details can be obtained from the file /proc/cpuinfo
[root@XXXX ~]# cat /proc/cpuinfo
processor : 0
vendor_id : AuthenticAMD
cpu family : 15
model : 35
model name : Dual Core AMD Opteron(tm) Processor 170
stepping : 2
cpu MHz : 1996.107
cache size : 1024 KB
physical id : 0
siblings : 2
core id : 0
cpu cores : 2
fdiv_bug : no
hlt_bug : no
f00f_bug : no
coma_bug : no
fpu : yes
fpu_exception : yes
cpuid level : 1
wp : yes
flags : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca
cmov pat pse36 clflush mmx fxsr sse sse2 ht pni syscall nx mmxext fxsr_opt
lm 3dnowext 3dnow pni
bogomips : 3992.34
[root@XXXXX ~]#
modinfo

Another useful tool to obtain hardware information is modinfo. It gives detailed description about modules. Before using modinfo, you may need to find out currently loaded modules. lsmod is the utility that lists currently loaded modules.
[root@XXXXXX ~]# lsmod
libata 105757 1 sata_svw
[root@ XXXXXX~]#
lsmod displays a module sata_svw and more details of this module can be obtained as shown below.
[root@XXXXX ~]# modinfo sata_svw
filename: /lib/modules/2.6.9-55.ELsmp/kernel/drivers/ata/sata_svw.ko
author: Benjamin Herrenschmidt
description: low-level driver for K2 SATA controller
license: GPL
version: 2.0 9FF8518CB6CD3CB4AE61E35
vermagic: 2.6.9-55.ELsmp SMP 686 REGPARM 4KSTACKS gcc-3.4
depends: libata
alias: pci:v00001166d00000240sv*sd*bc*sc*i*
alias: pci:v00001166d00000241sv*sd*bc*sc*i*
alias: pci:v00001166d00000242sv*sd*bc*sc*i*
alias: pci:v00001166d0000024Asv*sd*bc*sc*i*
alias: pci:v00001166d0000024Bsv*sd*bc*sc*i*
[root@xxxxxx~]#
4. Configure the Kernel

Once you have the source, the next step is to configure the kernel.

You can configure the kernel using any of the following :
make config - This is a text based command line interface that will ask each and every configuration question in order.
make xconfig - This is a graphical editor that requires x to be installed in the system. Hence it is not used in servers.
make oldconfig - A text based interface that takes an existing configuration file and queries for any variable not enabled in that configuration file.
make menuconfig - A text based menu configurator based on cursor-control libraries. This is the most commonly used method for configuring kernels in servers.

If you are a newbie, I would recommend using the existing configuration and use make menuconfig to configure the kernel.

Steps for configuring your kernel are :
Step 1: Copy the current kernel configuration to your new kernel source.
[root@XXXXX ~]#pwd
/usr/src/kernels/linux-2.6.19.2
[root@XXXXX ~]#cp /boot/config- .config
[root@XXXXX ~]#make oldconfig
where should be replaced with the existing kernel version in the server. You can get in the server using the command :
[root@XXXXX ~]# uname -r
2.6.9-67.ELsmp2.6.9-67.ELsmp
[root@XXXXX ~]#
When make oldconfig prompts for values, retain the old values.

Even if you retain the old values, don't forget to check the hardware of the server as well as the processor type and the model of the ethernet card. Since options change with newer kernel versions, and some options may not be there in the old .config files, it is advisable to double check all the options using menuconfig.
Step 2: make menuconfig.
[root@XXXXX ~]#make menuconfig
[Please go through the images 1.,2 and 3]
This is the main screen of menuconfig. Only some options can be compiled as modules. In menuconfig, they are marked < >. Press M to compile as a module. A [*] means compiled in, M means module.

Menuconfig offers search feature. Use "/" to search for any module. For eg: if you are not sure of the location of the module iptables, press "/" , enter the search pattern as "iptables" and press enter.



As there are a lot of options in menuconfig, I will just mention the important ones. The essential options needed for a kernel to be running is processor, file system, network card and hard disk. You can select the desired processor, file system, hard disk and network card from the options available in menuconfig.

Processor type and features

Subarchitecture Type : Select Generic architecture (Summit,bigsmp, ES7000, default)

Processor family : Select the matching processor from the available list. For eg : If the model name is Dual Core AMD Opteron(tm) Processor 170 , you can select Opteron/Athlon64/Hammer/K8 from the options available.

For a multiprocessor server, enable the options Symmetric multi-processing support and SMT (Hyper threading) scheduler support.

For RAM > 4 GB enable the option High Memory Support (64GB) . And the final output of the option Processor type and features would look like this :
[Please go through the image no:4]

Networking

Iptables is enabled in this option.
Location:
-> Networking
-> Networking support (NET [=y])
-> Networking options
-> Network packet filtering (replaces ipchains) (NETFILTER [=y])
-> Core Netfilter Configuration and IP: Netfilter Configuration

All the modules under the option Core Netfilter Configuration and IP: Netfilter Configuration should be enabled as modules.

Device Drivers

This is the most confusing part. In this, the main options you need to check are :

1. Block devices : Enable RAM disk support and Loop back device support
Include Loopback device support (module)
RAM disk support [*} compiled in
Leave the default values of RAM disk number and size.
Initial RAM disk (initrd) support [*} compiled in

2. SCSI device support : Enable corresponding model in SCSI low level drivers if it is a SCSI device.

3. Serial ATA (prod) and Parallel ATA (experimental) drivers: if hard disk is SATA, enable the corresponding driver in this. For eg: if you have Intel PIIX/ICH SATA in the server enable Intel PIIX/ICH SATA support in this option

4. Network device support : Enable the corresponding network card in the server. For eg: if lspci lists the network card as follows :
Ethernet controller: Broadcom Corporation NetXtreme BCM5704 Gigabit Ethernet

Then enable

> Network device support
> Ethernet (1000 Mbit)ss
> Broadcom NetXtremeII support

File Systems

The main modules to be enabled in this section are ext2, ext3, journaling and Quota support.

Once this is complete , save the settings and quit.
5. Build the Kernel

The next step is to build the Kernel. You can use the command make bzImage to do this. This command will create a compressed file bzImage inside arch/i386/boot in the Linux source directory and that is the newly compiled kernel.

The next step is to compile and link the modules. This can be done using the command make modules.

After this you have to copy the modules to /lib/modules/. And this is done using the command make modules_install.

The command sequence is as follows :
make -j bzImage
make -j modules
make -j modules-Install


-j tells your system to do that many jobs in Makefile together which will in turn reduce the time for compilation.

is two times the number of cpus in your system or number of virtual processors. This number can be found using the command
cat /proc/cpuinfo | grep ^processor | wc -l
[root@XXXX]# cat /proc/cpuinfo | grep ^processor | wc -l
2

Once this is done copy all these to the /boot folder as follows :
cp .config /boot/config-2.6.19.2
cp arch/i386/boot/bzImage /boot/vmlinuz-2.6.19.2
cp System.map /boot/System.map-2.6.19.2
mkinitrd /boot/initrd-2.6.9.img 2.6.19.2

mkinitrd is the program to create initial RAM Disk Image.
6. Configure Boot Loader

Boot loader is the first program that runs when a computer boots. There are two types of boot loader :
GRUB
LILO
1. Determine the currently installed boot loader :

Check first 512 bytes of the boot drive. Check for grub first:
# dd if=/dev/hda bs=512 count=1 2>&1 | grep GRUB

If it matches, the current boot loader is grub. Check for lilo if it did not match:
# dd if=/dev/hda bs=512 count=1 2>&1 | grep LILO

Note : If the hard disk is SCSI or SATA, use sda instead of hda..
2. Configure the boot loader

If your boot loader is LILO, add entries for the new kernel in the file /etc/lilo.conf. A typical lilo entry will be as given below :
image=/boot/vmlinuz-2.6.19.2
label=linux
initrd=/boot/initrd-2.6.19.2.img
read-only
append="console=tty0 console=ttyS1,19200n8 clock=pmtmr root=LABEL=/"

Run the command :
lilo -v
/sbin/lilo -R "Label for new kernel"

In the case of GRUB, add the entries for the new kernel at the end of the list of kernels in the file /etc/grub.conf. The first entry in GRUB gets the index 0. An example entry is below :
title Red Hat Linux (2.6.19.2)
root (hd0,0)
kernel /boot/vmlinuz-2.6.19.2 ro root=/dev/hda2 panic=3
initrd /boot/initrd-2.6.19.2

The "panic" parameter ensures that the server reboots to the old kernel, in the case of a kernel panic i.e the machine will be rebooted to the default option in grub.conf, if a panic occurs in 3 secs.

Do Not change the "default" value in the file grub.conf. Enter grub command prompt by typing the command grub at the prompt. Enter the below command at the grub prompt:
savedefault --default=3 --once

This is the case if the newly added entry is having index 3. Exit from grub-shell.
7.Reboot the Server

Reboot the server using the command reboot. If by any chance, a kernel panic occurs, server will be up with the old working kernel. If everything goes fine, the server will be up with the new kernel. Once it is up with the new kernel, do not forget to change the default value in the boot loader.
Conclusion

Booting a newly recompiled kernel in your first attempt is a tough task and is at times thought impossible. Following the above steps and keeping the compilation tricks in mind, there is no doubt Kernel Compilation will now be a piece of cake.

sysctl_hardening

# Linux kernel tweaking for performance and security on a busy Linux
# server with a decent amount of memory.
#
# This file should be saved as /etc/sysctl.conf
# You can source it manually if your system has booted by using:
# sysctl -e -p /etc/sysctl.conf
#
# Paul Day, paul (at) bur.st
#
# Last updated 02/03/05 and tested on 2.6.9
#

# Increase RPC slots
sunrpc.tcp_slot_table_entries = 32
sunrpc.udp_slot_table_entries = 32
# Increase size of RPC datagram queue length
net.unix.max_dgram_qlen = 50
# Log spoofed, source routed and redirects
net.ipv4.conf.default.log_martians = 1
# Don't accept source routes
net.ipv4.conf.default.accept_source_route = 0
# Don't send redirects
net.ipv4.conf.default.send_redirects = 0
# Source route verification on - incoming packets must match outgoing routing
net.ipv4.conf.default.rp_filter = 1
# Don't accept redirects
net.ipv4.conf.default.accept_redirects = 0
# Don't forward source routes
net.ipv4.conf.default.mc_forwarding = 0
# Disable forwarding
net.ipv4.conf.default.forwarding = 0
# Log spoofed, source routed and redirects
net.ipv4.conf.all.log_martians = 1
# Don't relay bootp
net.ipv4.conf.all.bootp_relay = 0
# Don't proxy arp for anyone
net.ipv4.conf.all.proxy_arp = 0
# Don't accept source route packets
net.ipv4.conf.all.accept_source_route = 0
# Don't send redirects
net.ipv4.conf.all.send_redirects = 0
# Source route verification on - incoming packets must match outgoing routing
net.ipv4.conf.all.rp_filter = 1
# Don't accept redirects
net.ipv4.conf.all.accept_redirects = 0
# Don't forward source routes
net.ipv4.conf.all.mc_forwarding = 0
# Don't enable forwarding
net.ipv4.conf.all.forwarding = 0
# Don't allow the arp table to become bigger than this
net.ipv4.neigh.default.gc_thresh3 = 2048
# Tell the gc when to become aggressive with arp table cleaning.
# Adjust this based on size of the LAN. 256 is suitable for most
net.ipv4.neigh.default.gc_thresh2 = 1024
# Adjust where the gc will leave arp table alone - set to 32.
net.ipv4.neigh.default.gc_thresh1 = 32
# Adjust to arp table gc to clean-up more often
net.ipv4.neigh.default.gc_interval = 30
# Increase TCP
net.ipv4.neigh.default.proxy_qlen = 96
net.ipv4.neigh.default.unres_qlen = 6
# Increase size of socket buffers
net.ipv4.tcp_rmem = 4096 98304 349520
net.ipv4.tcp_wmem = 4096 65535 262142
net.ipv4.tcp_mem = 98304 262142 393216
# Turn off sack
net.ipv4.tcp_dsack = 0
# Don't use ECN because too many sites have wacky routers that can't handle it`
net.ipv4.tcp_ecn = 0
net.ipv4.tcp_reordering = 3
# Turn off sack/fack
net.ipv4.tcp_fack = 0
# Enable bad error message Protection
net.ipv4.icmp_ignore_bogus_error_responses = 1
# Ignore broadcasts pings, could become part of a Smurf
net.ipv4.icmp_echo_ignore_broadcasts = 1
# But don't ignore directed pings
net.ipv4.icmp_echo_ignore_all = 0
# Widen local port range
net.ipv4.ip_local_port_range = 33000 60000
# Bump up TCP socket queuer to help with syn floods
net.ipv4.tcp_max_syn_backlog = 2048
# Turn syn-cookie protection on
net.ipv4.tcp_syncookies = 1
# Drop it so lack of FIN times out quicker
net.ipv4.tcp_fin_timeout = 30
# How many times to retry killing an alive TCP connection
net.ipv4.tcp_retries2 = 15
net.ipv4.tcp_retries1 = 3
# Enable a fix for RFC1337 - time-wait assassination hazards in TCP
net.ipv4.tcp_rfc1337 = 1
# Drop keep-alive time
net.ipv4.tcp_keepalive_time = 3600
# Set number of times to retry a SYN-ACK in a half-open new connections
net.ipv4.tcp_synack_retries = 5
# Set number of times to retry SYN in a new connection
net.ipv4.tcp_syn_retries = 5
# Turn off sack
net.ipv4.tcp_sack = 0
# Enable really big (>65kB) TCP window scaling if we want it.
net.ipv4.tcp_window_scaling = 1
# Turn off timestamps
# Turn this back on if you're on a gigabit or very busy network
# Having it off is one less thing the IP stack needs to work on
net.ipv4.tcp_timestamps = 0
# Increase number of incoming connections backlog
net.core.somaxconn = 512
# Bump optmem_max up
net.core.optmem_max = 20480
# Increase number of incoming connections backlog
net.core.netdev_max_backlog = 1024
net.core.dev_weight = 64
# Bump up default r/wmem to max
net.core.rmem_default = 262141
net.core.wmem_default = 262141
# Bump up max r/wmem
net.core.rmem_max = 262141
net.core.wmem_max = 262141
# Increase size of file handles and inode cache
fs.file-max = 209708

Linux Files and File Permission

Linux Files and File Permission

Linux files are setup so access to them is controlled. There are three types of access:
read
write
execute

Each file belongs to a specific user and group. Access to the files is controlled by user, group, and what is called other. The term, other, is used to refer to someone who is not the user (owner) of the file, nor is the person a member of the group the file belongs to. When talking about setting permissions for "other" users to use, it is commonly referred to as setting the world execute, read, or write bit since anyone in the world will be able to perform the operation if the permission is set in the other category.
File names and permission characters

File names can be up to 256 characters long with "-", "_", and "." characters along with letters and numbers.
When a long file listing is done, there are 10 characters that are shown on the left that indicate type and permissions of the file. File permissions are shown according to the following syntax example: drwerwerwe
There are a total of 10 characters in this example, as in all Linux files. The first character indicates the type of file, and the next three indicate read, write, and execute permission for each of the three user types, user, group and other. Since there are three types of permission for three users, there are a total of nine permission bits. The table below shows the syntax: 1 2 3 4 5 6 7 8 9 10
File User Permissions Group Permissions Other Permissions
Type Read Write Execute Read Write Execute Read Write Execute
d r w e r w e r w e


Character 1 is the type of file: - is ordinary, d is directory, l is link.
Characters 2-4 show owner permissions. Character 2 indicates read permission, character 3 indicates write permission, and character 4 indicates execute permission.
Characters 5-7 show group permissions. Character 5=read, 6=write, 7=execute
Characters 8-10 show permissions for all other users. Character 8=read, 9=write, 10=execute

There are 5 possible characters in the permission fields. They are:
r = read - This is only found in the read field.
w = write - This is only found in the write field.
x = execute - This is only found in the execute field.
s = setuid - This is only found in the execute field.
If there is a "-" in a particular location, there is no permission. This may be found in any field whether read, write, or execute field.
Examples

Type "ls -l" and a listing like the following is displayed: total 10
drwxrwxrwx 4 george team1 122 Dec 12 18:02 Projects
-rw-rw-rw- 1 george team1 1873 Aug 23 08:34 test
-rw-rw-rw- 1 george team1 1234 Sep 12 11:13 datafile


Which means the following: Type and # of Files's File's Size in Date of last Filename
Permission field Links Owner Group Bytes modification
| | | | | | |
drwxrwxrwx 4 george team1 122 Dec 12 18:02 Projects


The fields are as follows:
Type field: The first character in the field indicates a file type of one of the following:
d = directory
l = symbolic link
s = socket
p = named pipe
- = regular file
c= character (unbuffered) device file special
b=block (buffered) device file special
Permissions are explained above.
Links: The number of directory entries that refer to the file. In our example, there are four.
The file's owner in our example is George.
The group the file belongs to. In our example, the group is team1.
The size of the file in bytes
The last modification date. If the file is recent, the date and time is shown. If the file is not in the current year, the year is shown rather than time.
The name of the file.
Set User Identification Attribute

The file permissions bits include an execute permission bit for file owner, group and other. When the execute bit for the owner is set to "s" the set user ID bit is set. This causes any persons or processes that run the file to have access to system resources as though they are the owner of the file. When the execute bit for the group is set to "s", the set group ID bit is set and the user running the program is given access based on access permission for the group the file belongs to. The following command:

chmod +s myfile

sets the user ID bit on the file "myfile". The command:

chmod g+s myfile

sets the group ID bit on the file "myfile".

The listing below shows a listing of two files that have the group or user ID bit set.
-rws--x--x 1 root root 14024 Sep 9 1999 chfn
-rwxr-sr-x 1 root mail 12072 Aug 16 1999 lockfile

The files chfn and lockfile are located in the directory "/usr/bin". The "s" takes the place of the normal location of the execute bit in the file listings above. This special permission mode has no meaning unless the file has execute permission set for either the group or other as well. This means that in the case of the lockfile, if the other users (world execute) bit is not set with permission to execute, then the user ID bit set would be meaningless since only that same group could run the program anyhow. In both files, everyone can execute the binary. The first program, when run is executed as though the program is the root user. The second program is run as though the group "mail" is the user's group.

For system security reasons it is not a good idea to set many program's set user or group ID bits any more than necessary, since this can allow an unauthorized user privileges in sensitive system areas. If the program has a flaw that allows the user to break out of the intended use of the program, then the system can be compromised.
Directory Permissions

There are two special bits in the permissions field of directories. They are:
s - Set group ID
t - Save text attribute (sticky bit) - The user may delete or modify only those files in the directory that they own or have write permission for.
Save text attribute

The /tmp directory is typically world-writable and looks like this in a listing:
drwxrwxrwt 13 root root 4096 Apr 15 08:05 tmp

Everyone can read, write, and access the directory. The "t'' indicates that only the user (and root, of course) that created a file in this directory can delete that file.

To set the sticky bit in a directory, do the following:

chmod +t data

This option should be used carefully. A possible alternative to this is
Create a directory in the user's home directory to which he or she can write temporary files.
Set the TMPDIR environment variable using each user's login script.
Programs using the tempnam(3) function will look for the TMPDIR variable and use it, instead of writing to the /tmp directory.
Directory Set Group ID

If the setgid bit on a directory entry is set, files in that directory will have the group ownership as the directory, instead of than the group of the user that created the file.

This attribute is helpful when several users need access to certain files. If the users work in a directory with the setgid attribute set then any files created in the directory by any of the users will have the permission of the group. For example, the administrator can create a group called spcprj and add the users Kathy and Mark to the group spcprj. The directory spcprjdir can be created with the set GID bit set and Kathy and Mark although in different primary groups can work in the directory and have full access to all files in that directory, but still not be able to access files in each other's primary group.

The following command will set the GID bit on a directory:

chmod g+s spcprjdir

The directory listing of the directory "spcprjdir":

drwxrwsr-x 2 kathy spcprj 1674 Sep 17 1999 spcprjdir

The "s'' in place of the execute bit in the group permissions causes all files written to the directory "spcprjdir" to belong to the group "spcprj" .
Examples
Below are examples of making changes to permissions:chmod u+x myfile Gives the user execute permission on myfile.
chmod +x myfile Gives everyone execute permission on myfile.
chmod ugo+x myfile Same as the above command, but specifically specifies user, group and other.
chmod 400 myfile Gives the user read permission, and removes all other permission. These permissions are specified in octal, the first char is for the user, second for the group and the third is for other. The high bit (4) is for read access, the middle bit (2) os for write access, and the low bit (1) is for execute access.
chmod 764 myfile Gives user full access, group read and write access, and other read access.
chmod 751 myfile Gives user full access, group read and execute permission, and other, execute permission.
chmod +s myfile Set the setuid bit.
chmod go=rx myfile Remove read and execute permissions for the group and other.


Below are examples of making changes to owner and group:chown mark test1 Changes the owner of the file test1 to the user Mark.
chgrp mark test1 Changes the file test1 to belong to the group "mark".


Note: Linux files were displayed with a default tab value of 8 in older Linux versions. That means that file names longer than 8 may not be displayed fully if you are using an old Linux distribution. There is an option associated with the ls command that solves this problem. It is "-T". Ex: "ls al -T 30" to make the tab length 30.
Umask Settings

The umask command is used to set and determine the default file creation permissions on the system. It is the octal complement of the desired file mode for the specific file type. Default permissions are:
777 - Executable files
666 - Text files

These defaults are set allowing all users to execute an executable file and not to execute a text file. The defaults allow all users can read and write the file.

The permission for the creation of new executable files is calculated by subtracting the umask value from the default permission value for the file type being created. An example for a text file is shown below with a umask value of 022:
666 Default Permission for text file
-022 Minus the umask value
-----
644 Allowed Permissions

Therefore the umask value is an expression of the permissions the user, group and world will not have as a default with regard to reading, writing, or executing the file. The umask value here means the group the file belongs to and users other than the owner will not be able to write to the file. In this case, when a new text file is created it will have a file permission value of 644, which means the owner can read and write the file, but members of the group the file belongs to, and all others can only read the file. A long directory listing of a file with these permissions set is shown below.
-rw-r--r-- 1 root workgrp 14233 Apr 24 10:32 textfile.txt

A example command to set the umask is:

umask 022

The most common umask setting is 022. The /etc/profile script is where the umask command is usually set for all users.

Red Hat Linux has a user and group ID creation scheme where there is a group for each user and only that user belongs to that group. If you use this scheme consistently you only need to use 002 for your umask value with normal users.
Ubuntu 7.10 LAMP Server

For the Desktop Edition users:-

System->Administration->Synaptic Package Manager->Edit->Mark Packages by Taskel.

Click on LAMP Server.

You are done.



If you are looking for simple LAMP Server setup in 15min including webmin installation this is for you
Ubuntu 7.10 LAMP Server Step By Step Guide

(This requires the server version of Gutsy Gibbon, not the standard desktop edition)
[edit]
How to install Apache and PHP5

Install Apache
sudo aptitude install apache2

Install PHP5 and the Apache PHP5 module
sudo aptitude install php5 libapache2-mod-php5

Restart Apache
sudo /etc/init.d/apache2 restart

Go to http://localhost to verify the installation. If you want to change the port, edit the file /etc/apache/ports.conf and change where it says "Listen 80" to say "Listen" + the desired port number, e.g. "Listen 8080"
[edit]
How to Install Webmin

Webmin is an browser-based administration tool for Apache, PHP, MySQL, and Much More.
wget http://garr.dl.sourceforge.net/sourceforge/webadmin/webmin_1.400_all.deb

(If newer version exist, just replace x.400 with newer version number.
sudo apt-get install libnet-ssleay-perl libauthen-pam-perl libio-pty-perl libmd5-perl

If hasn't setup ed the root password yet, type: sudo passwd root (In Ubuntu root password is not setuped during install process.) If prefer not to setup root password, must manual enter user name and password for webmin administrator account, if root exist, just use it to login with.
sudo dpkg -i webmin_1.400_all.deb

To use webmin, type the following in a browser: (Make sure to use HTTPS not HTTP)
https://localhost:10000
[edit]
Sun Java Application Server (Java EE)

Official documentation
[edit]
Installing Application Server

Sun Java Application Server is the heart of Java EE. Download either of the following versions:
Java EE 5 SDK Update 3
Java Application Platform SDK Update 3 Beta
Sun Java System Application Server 9.1 (under individual download section)

Alternately you can download GlassFish application server (community maintained):
With Netbeans Web & Java EE pack
Download GlassFish directly

Make the download file executable and run as root by:
chmod +x Desktop/filename
sudo ./Desktop/filename

Lets assume $JAVAEE_HOME indicates the installation directory. The default installation directory for Sun Java System Application Server 9.1 is /opt/SUNWappserver/. Now, either add $JAVAEE_HOME/bin in your PATH or make a link of asadmin and asant in your path by
sudo ln -s $JAVAEE_HOME/bin/asadmin /usr/local/bin/asadmin
sudo ln -s $JAVAEE_HOME/bin/asant /usr/local/bin/ant

The command 'asadmin' is the main and most important command for Java Application server. Ant is also useful to automate building process.
[edit]
Application Server configuration

When Java EE installs, a domain 'domain1' is automatically installed with it in $JAVAEE_HOME/domains/ which is the default directory for all domains. Generally this directory ($JAVAEE_HOME/domains/) is not writable. So, as a unprivileged user you can create your own domain in your home directory.
[edit]
Application Server domain settings

To create, start, stop and delete a domain in your home directory:
asadmin create-domain --adminport 4848 --domaindir ~ mydomain
asadmin start-domain --domaindir ~ mydomain
asadmin stop-domain --domaindir ~ mydomain
asadmin delete-domain --domaindir ~ mydomain

Alternately you can make $JAVAEE_HOME/domains/ writable to do domain-related works from default domain directory. E.g.
sudo chmod a+w $JAVAEE_HOME/domains/
asadmin create-domain --adminport 4848 mydomain
asadmin start-domain mydomain
asadmin stop-domain mydomain
asadmin delete-domain mydomain

If you have only one domain in the default domains directory ($JAVAEE_HOME/domains/) then you do not have to give the domain name to start or stop a domain. E.g.
asadmin start-domain
asadmin stop-domain

You can save the login information to ~/.asadminpass file in order to administer an application server domain from command line. If you do not login, you have to provide username and password for each administrative work (analogous to su and sudo commands). To login:
asadmin login --host localhost --port 4848

Deploying and un-deploying a web or ejb module is very easy. Just do the following:
asadmin deploy test1.war
asadmin deploy test2.ear

asadmin undeploy test1.war
asadmin undeploy test2.ear
[edit]
Application Server data Source settings

DataSource configuration can be done easily from web based administration console. Here command line method is given:
sudo ln -s /usr/share/java/postgresql.jar /opt/SUNWappserver/domains/domain1/lib/postgresql.jar
asadmin create-jdbc-connection-pool --datasourceclassname org.postgresql.ds.PGSimpleDataSource --property
serverName=localhost:portNumber=5432:databaseName=database:user=user:password=pass jdbc/postgresql
asadmin create-jdbc-resource --connectionpoolid jdbc/postgresql database

First, we have made this driver accessible from the domain. In the second command, we have created a data source connection pool which has been assigned a JNDI name in the third command. Here all the colon (:) separated values are database related. Change them according to your database settings. Now you can create a Connection by, e.g.:
Context ic = new InitialContext();
DataSource ds = (DataSource)ic.lookup("database");
Connection conn = ds.getConnection();

To see available data sources and their corresponding JNDI names:
asadmin list-jdbc-connection-pools
asadmin list-jdbc-resources

To delete both connection pool, you have to delete JNDI name first. E.g.
asadmin delete-jdbc-resource database
asadmin delete-jdbc-connection-pool jdbc/postgresql
[edit]
Tomcat 6
[edit]
Installing tomcat

Tomcat can be found in universe repository but it has some drawbacks (e.g. lots of dependencies, unavailability of version 6.x, do not use Sun Java). Thus manual installation is recommended.

Download latest stable version of tomcat from http://tomcat.apache.org/download-60.cgi and extract it in /usr/local as root. Add "JAVA_HOME=/usr/lib/jvm/java-6-sun/" to /usr/local/apache-tomcat-6.x.x/bin/setclasspath.sh after the first occurrence of "CLASSPATH=". Make sure that sun-java6-jre is installed. Make a soft-link of /usr/local/apache-tomcat-6.x.x/bin/catalina.sh as /usr/local/bin/tomcat to access easily. Optionally you can remove .exe and .bat files and edit .sh files to remove cygwin, os400 and darwin related codes.

Although not necessary, but the ant program would be useful here. You can also install its documentation.
[edit]
OpenEJB Server

OpenEJB is an open source, modular, configurable, and extendable EJB Container System and EJB Server. Visit here to see the installation instructions for OpenEJB under Tomcat 6.
[edit]
Using tomcat with NetBeans

You have to make the configuration files readable because Netbeans generally do not run with administrative privilege. To use Tomcat with with NetBeans, you have to set a user with manager role. A typcal $CATALINA_HOME/conf/tomcat-users.xml file would look like:










Edit this file after you have started tomcat once. Any data placed in the element is erased during the first start of tomcat. You can also use tomcat that comes with NetBeans web & Java EE pack.
[edit]
Configure Database Connection Pool (DBCP) of Tomcat

A database connection pool creates and manages a pool of connections to a database. Recycling and reusing already existing connections to a dB is more efficient than opening a new connection. It is still possible and valid to open and close connection for each servlet/jsp (visit #Using_JDBC_driver for details).

Before proceeding, let's assume that $CATALINA_HOME denotes tomcat installation directory (typically: /usr/local/apache-tomcat-6.0.14).
echo $CATALINA_HOME
sudo ln -s /usr/share/java/postgresql.jar $CATALINA_HOME/lib/postgresql.jar
sudo mkdir $CATALINA_HOME/webapps/dataSourceTest
sudo chown $USER:$USER $CATALINA_HOME/webapps/dataSourceTest
cd $CATALINA_HOME/webapps/dataSourceTest
mkdir META-INF WEB-INF WEB-INF/classes

Create WEB-INF/web.xml and set its content:


xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
version="2.5">


PostgreSQL connectivity
jdbc/postgresql
javax.sql.DataSource
Container



Page for testing

Testing page

pgsqlVersion
pgsqlVersion


pgsqlVersion
/pgsqlVersion



Create META-INF/context.xml and set its content (replace hostname, database instance name, user id and password):


name="jdbc/postgresql"
auth="Container"
type="javax.sql.DataSource"
driverClassName="org.postgresql.Driver"
url="jdbc:postgresql://host/database"
username="user"
password="password"
maxActive="20"
maxIdle="10"
maxWait="-1"/>
WEB-INF/web.xml
META-INF/context.xml


Create pgsqlVersion.java and set its content:
import java.io.*;
import java.sql.*;
import javax.sql.*;
import javax.naming.*;
import javax.servlet.*;
public class pgsqlVersion extends GenericServlet {
public void service(ServletRequest request, ServletResponse response) {
try {
response.setContentType("text/html");
PrintWriter pw=response.getWriter();
Context initContext = new InitialContext();
Context envContext = (Context)initContext.lookup("java:/comp/env");
DataSource ds = (DataSource)envContext.lookup("jdbc/postgresql");
Connection conn = ds.getConnection();
Statement stat=conn.createStatement();
ResultSet rs=stat.executeQuery("SELECT version()");
rs.next();
pw.println(rs.getString("version"));
rs.close();
stat.close();
} catch(Exception e) { }
}
}

Create index.html and set its content:
"http://www.w3.org/TR/html4/frameset.dtd">


PostgreSQL datasource







Then compile the servlet:
export CLASSPATH=$CATALINA_HOME/lib/postgresql.jar:$CATALINA_HOME/lib/servlet-api.jar:.
javac -d WEB-INF/classes/ pgsqlVersion.java

Finally, visit http: //host:8080/dataSourceTest. Thats all!
[edit]
Nagios Network Monitoring Server
Nagios Monitoring Server Setup Guide

It should be noted that this howto instructs you to build nagios from its sources, while it exists on the official repositories.
[edit]
NFS Server
Read Linux NFS FAQ
Run this command for each computer to determine the IP Addresses for each one:
ifconfig
[edit]
Installing NFS Server

Use this script or follow the guide:
sudo apt-get install nfs-kernel-server nfs-common portmap

Reconfigure Portmap to not bind to loopback interface:
sudo dpkg-reconfigure portmap
sudo /etc/init.d/portmap restart

Define which folders to share (export):
sudo nano /etc/exports

Add share (export) definitions:

This will export path to all IP addresses between 192.168.1.1 and 192.168.1.254 with Read/Write access:
/path/to/shared/files 192.168.1.0/24(rw,no_root_squash,async)

This will export path to all IP addresses between 192.168.1.1 and 192.168.1.254 with Read Only access:
/path/to/shared/files 192.168.1.0/24(ro,async)

192.168.1.0/24 above would be the clients IP Address

When finished, save changes and restart the NFS Server:
sudo /etc/init.d/nfs-kernel-server restart

Export your new configuration:
sudo exportfs -a
[edit]
Installing NFS Client

Use this script (For installing nfs client and mounting automatically) or follow the guide:
sudo apt-get install portmap nfs-common
[edit]
Mounting Manually
cd ~
mkdir temp
sudo mount 192.168.1.1:/path/to/shared/files temp

192.168.1.1 above would be the Servers IP Address

You may need to restart NFS services:
sudo /etc/init.d/portmap restart
sudo /etc/init.d/nfs-common restart
[edit]
Mounting Automatically

Create mountpoint:
sudo mkdir /mnt/files

Edit configuration:
gksudo gedit /etc/fstab

Add something similar to below:
192.168.1.1:/path/to/shared/files /mnt/files nfs rsize=8192,wsize=8192,timeo=14,intr 0 0

Test new configuration:
sudo mount -a

Reboot to test automatic mounting.
[edit]
Hardware
[edit]
NVidia Driver

First, determine what kernel you have running:
user@localhost:~$ uname -a
Linux localhost 2.6.22-14-generic #1 SMP Sun Oct 14 23:05:12 GMT 2007 i686 GNU/Linux

I have the generic kernel, so I need to install the following:
sudo apt-get install linux-restricted-modules-generic


After that's done, go to System > Administration > Restricted Drivers Manager and turn on the driver.

Some users may receive an error screen: "The software source for the packsge nvidia-glx-new is not enabled." This can be overcome by going to System > Administration > Software Sources and ticking all the boxes under the heading "Downloadable from the Internet", click close and then allow Ubuntu to reload the package lists. The NVidia drivers can then be enabled using the method above.

You can optionally prevent showing NVidia logo on startup by:
sudo nvidia-xconfig --no-logo
[edit]
Envy- nvidia driver installer script

Alternatively you can auto install nvidia drivers using Envy. Download and run the application.
[edit]
Overclock NVIDIA graphics card and change fan speeds

Download NVClock: http://www.linuxhardware.org/nvclock/#download

Extract package to your home folder.

In Terminal, input the following commands in order:
cd nvclock0.8b2
./configure
make
sudo make install

To set video card fan speed to run at startup, input the following into “Sessions,” where X = % maximum fan speed:
nvclock -f -F X
[edit]
Wacom tablet

By default, options for the Wacom tablet are commented out. Type the following command to edit the xorg.conf file.
gksu gedit /etc/X11/xorg.conf

Uncomment the following by removing the "#" or just replace the tree lines:
InputDevice "stylus" "SendCoreEvents"
InputDevice "cursor" "SendCoreEvents"
InputDevice "eraser" "SendCoreEvents"

Save and restart your X-session by typing CTRL-ALT-BACKSPACE.
[edit]
Microsoft Intellimouse

To get the scroll wheel and side buttons to be recognized, change your /etc/X11/xorg.conf mouse section to look like the following:
Section "InputDevice"
Identifier "Configured Mouse"
Driver "mouse"
Option "CorePointer"
Option "Device" "/dev/input/mice"
Option "Protocol" "ExplorerPS/2"
Option "ZAxisMapping" "4 5"
Option "Emulate3Buttons" "true"
Option "Buttons" "7"
Option "ButtonMapping" "1 2 3 6 7"
EndSection

If you want the wheel scroll button to scroll in firefox rather than the side buttons make "ZAxisMapping" "6 7" and "ButtonMapping" "1 2 3 4 5".

At this point you can reboot your computer or restart X (Ctrl-Alt-BackSpace) to see if your forward/back buttons work in FireFox. You can test in a terminal with xev.
[edit]
Logitech Marble Mouse

To get the scrollwheel effect on Logitech trackball (Marble Mouse), change your /etc/X11/xorg.conf mouse section to look like the following:
Section "InputDevice"
Identifier "MarbleMouse"
Driver "mouse"
Option "Protocol" "auto"
Option "CorePointer"
Option "Device" "/dev/input/mice"
Option "Buttons" "5"
Option "ButtonMapping" "1 8 3 6 7"
Option "EmulateWheel" "true"
Option "EmulateWheelTimeout" "300" # msec
Option "EmulateWheelButton" "6"
Option "YAxisMapping" "4 5"
EndSection

Make sure that you have "MarbleMouse" under the server layout section as well.

The big left and right buttons work normally (click, right click) and pressing them at the same time acts as a middle click. Holding the small left button will let you scroll up and down with the trackball. Clicking small left and right buttons will let you go back/forward in firefox.

Thanks to imjustabill and Buffalo Soldier from the Ubuntu Forum. This works well on my computer.
[edit]
Logitech MX510

To have the extra buttons on your MX510 working with X, you'll have to install and configure the evdev-drivers. Open up a terminal and enter:
sudo apt-get install xserver-xorg-input-evdev

Now, all you have to do is configure Xorg to work with the new driver. Always remember to back up original files before altering:
sudo cp /etc/X11/xorg.conf /etc/X11/xorg.conf.bak
gksudo gedit /etc/X11/xorg.conf

Locate and replace the InputDevice section which holds the information for your mouse, for example with the identifier Configured Mouse, and replace it with:
Section "InputDevice"
Identifier "Configured Mouse"
Driver "evdev"
Option "CorePointer"
Option "Name" "Logitech MX510"
EndSection

Logout or kill the X session using and login again. This should get all of your buttons and scrollwheel up and running, and even let you navigate the webbrowser history using the thumb buttons on the side.
[edit]
Logitech MX518

I got the side mouse buttons on my Logitech MX518 working in Firefox. I am using the "evdev" driver, not the "mouse" driver. I am using Kubuntu 7.10 Gutsy, which already has the package "xserver-xorg-input-evdev" installed by default.

Simply change the mouse section of your /etc/X11/xorg.conf to this:


Section "InputDevice"
Identifier "Configured Mouse"
Driver "evdev"
Option "CorePointer"
Option "Buttons" "7"
Option "ZAxisMapping" "4 5"
Option "ButtonMapping" "1 2 3 6 7"
Option "Name" "Logitech USB-PS/2 Optical Mouse"
EndSection
[edit]
Disable CAPS LOCK

I like to remap mine to . Just run gnome-keyboard-properties with "System > Preferences > Keyboard", click on the "Layout Options" tab and then on the arrow next to "Ctrl key position". Selecting "Make CapsLock an additional Ctrl" does the trick.
[edit]
Enabling NUM LOCK at boot

The Default behavior is for the NUM LOCK key to be off; if you are on a desktop and have a keypad though, entering digits from it can be much quicker and you may wish to have it enabled for entering login password, etc. Here's how:
From Synaptic, download and install "numlockx," or, from the command line;
sudo apt-get install numlockx
To get it working, you now have to edit the appropriate startup file. First, make sure you have a working backup of the file:
sudo cp /etc/gdm/Init/Default /etc/gdm/Init/Default.bak
Next, modify the gdm/Init file. In terminal:
gksudo gedit /etc/gdm/Init/Default
Scroll down to the end of the file, and above the line that says "exit 0" add the following:
if [ -x /usr/bin/numlockx ]; then
/usr/bin/numlockx on
fi
Next time you reboot, your NUM LOCK should default to "on."
[edit]
BSNL Broadband (dataone) speedup

BSNL Broadband or Dataone provides high speed (2Mbps) Internet connectivity in India. The DNS servers provided by the BSNL (61.1.96.69 and 61.1.96.71) are very slow. Instead use Either of these:

208.67.222.222 and 208.67.220.220 or

4.2.2.1 and 4.2.2.2 or

search Google for free DNS service providers.
[edit]
Citrix ICA client

The Citrix client no longer suffers from any of the previous Ubuntu version's problems of UTF8 font issues, OpenMotif depends, or flaky/broken browser integration. It just works!
Download the latest en.linuxx86.tar.gz (currently v10.6) from Citrix.com and save to your desktop
Right-click tar.gz file, and Extract Here
Open a Terminal
Programs > Accessories > Terminal
Change to the directory where we extracted the client
cd Desktop/en.linuxx86
Run the setup program
./setupwfc
Select the defaults

Now, web files from Metaframe Presentation Server, Citrix Access Gateway, etc webpages will work fine in Firefox.

Someone may wish to add an entry on how to use the client to connect to a local Citrix farm.
[edit]
WINE

Latest install instructions are always at: WineHQ.org

Add repository key:
wget -q http://wine.budgetdedicated.com/apt/387EE263.gpg -O- | sudo apt-key add -

Add repository to apt sources:
sudo wget http://wine.budgetdedicated.com/apt/sources.list.d/gutsy.list -O /etc/apt/sources.list.d/winehq.list

Update apt sources:
sudo apt-get update

Install WINE:
sudo apt-get install wine

The program menu then appears in Programs under Wine, or double-click a Windows/DOS .exe file.
[edit]
Install Internet Explorer 6 for Wine

IE 6 is not recommended for general usage, but some Windows packages (installed under Wine) require IE6 to complete installation. Furthermore, IE 6 is useful for checking code for developers who want to see how their web pages appear under IE 6.

Install the required package cabextract from Synaptic Package Manager (or from apt-get install cabextract).

Download and run the IEs4Linux installation script from the IEs4Linux website:
wget http://www.tatanka.com.br/ies4linux/downloads/ies4linux-latest.tar.gz
tar zxvf ies4linux-latest.tar.gz
cd ies4linux-*
./ies4linux


There is a beta version of the install at http://www.tatanka.com.br/ies4linux/downloads

If you hit advance you have the option to install IE7. I have not gotten it to work as of yet, but IE6 installs with no issues on amd64 and i386

Accept all the defaults for installation.
[edit]
Wine-Doors

Wine-Doors http://www.wine-doors.org/ packages Windows applications for Wine. The current package list includes Internet Explorer 6.

Debian/Ubuntu package (single click) available for download.
[edit]
QEMU

Qemu http://fabrice.bellard.free.fr/qemu/ process emulator.
[edit]
How to run windows XP under qemu

If your hardware supports virtualization, run this script after giving it executing permissions.
[edit]
VMWare Server

Until the Commercial Ubuntu repository includes the VMWare Server, you can use the following 'How To' to compile from source.
Step By Step Vmware server setup guide including Screenshots
[edit]
VMWare Tools

If you want to install VMware tools on ubuntu gutsy follow this steps
VMWare Tools Setup Guide Including Screenshots

To be able to use usb devices look at following bug comment at https://bugs.launchpad.net/ubuntu/+source/kvm/+bug/156085/comments/5
[edit]
Parallels Virtualization Software in Ubuntu

If you want to install Parallels Virtualization Software in Ubuntu try this
Parallels Virtualization Software Setup in Ubuntu
[edit]
How to install Broadcom wireless driver
This worked for me Kubuntu 7.10 32 bit but there are several ways
First, make sure you have the appropriate hardware
lspci | grep Broadcom
Output should match this
02:03.0 Network controller: Broadcom Corporation BCM4306 802.11b/g Wireless LAN Controller (rev 02)
Then you have to add a repository
gksu gedit /etc/apt/sources.list
Add
deb http://ubuntu.cafuego.net gutsy-cafuego bcm43xx
Then do this to add the signature
wget http://ubuntu.cafuego.net/AF425CB5.gpg -O- | sudo apt-key add -
Back in the console
sudo apt-get update
sudo apt-get install bcm43xx-firmware
Just press yes, let it install, and reboot! Thanks to Pete and the 7.04 guide for this.
[edit]
Requests

If you have requests that you would like to be part of this guide, write them in Ubuntu_talk:Gutsy.
[edit]

Ubuntu Security and Samba Concerns.


Security

How to Add standard Users
sudo useradd -d /home/ -m

The -d is for creating the Home directory for the user

To Set the password for the new account use this;
sudo passwd

Or if you want to have ubuntu run you through a wizard like process that asks for every piece of information use this:
sudo adduser
[edit]
How to Delete users accounts
sudo userdel

This will however not delete the Home directory. To delete the Home directory just use this:
sudo rm -r /home//
[edit]
How to recover user passwords
sudo apt-get install john
sudo john /etc/shadow
[edit]
How to reset root password

Restart Ubuntu in safe mode and type:
passwd

to change root password.
[edit]
How to create or change GRUB menu password

Visit here.
[edit]
How to change root password if grub password is forgotten

Visit here. To prevent this, you have to set a bios password and set hard disk as the first boot device.
[edit]
How to install TrueCrypt

See TrueCrypt with GUI on Ubuntu 7.10.
[edit]
Servers
[edit]
DHCP Server
[edit]
How to share your internet connection with PCs connected to your server

Read the full article on wiki.steenbe.nl


[edit]
Samba Server
[edit]
How to install Samba Server for files/folders sharing service
Read #General Notes
Read #How to add extra repositories
sudo apt-get install samba smbfs
[edit]
How to add/edit/delete network users
Read #General Notes
Read #How to install Samba Server for files/folders sharing service
To add network user
Read #How to add/edit/delete system users
sudo smbpasswd -a system_username
gksudo gedit /etc/samba/smbusers
Insert the following line into the new file
system_username = "network username"
Save the edited file
To add network user
sudo smbpasswd -a system_username
To delete network user
sudo smbpasswd -x system_username
To enable network user
sudo smbpasswd -e system_username
To disable network user
sudo smbpasswd -d system_username
By Default network users are disabled after adding them, make sure you run the enable network user command above.
[edit]
How to share home folders with read only or read/write permission (Authentication=Yes)
Read #General Notes
Read #How to install Samba Server for files/folders sharing service
sudo cp /etc/samba/smb.conf /etc/samba/smb.conf_backup
gksudo gedit /etc/samba/smb.conf
Find this line
...
; security = user
...
Replace with the following lines
security = user
username map = /etc/samba/smbusers
Remove the ; in front of the following lines (there will text in between explaining what they do):
;[homes]
;comment = Home Directories
;browseable = no
;valid users = %S
;writable = yes
If you want other network users to be able to edit to the folder then change
# By default, the home directories are exported read-only. Change next
# parameter to 'yes' if you want to be able to write to them.
; writable = no
Replace with the following lines
writable = yes
Save the edited file
Read #How to add/edit/delete network users
sudo testparm
sudo /etc/init.d/samba restart
[edit]
How to share group folders with read only permission (Authentication=Yes)
Read #General Notes
Read #How to install Samba Server for files/folders sharing service
sudo mkdir /home/group
sudo chmod 777 /home/group/
sudo cp /etc/samba/smb.conf /etc/samba/smb.conf_backup
gksudo gedit /etc/samba/smb.conf
Find this line
...
; security = user
...
Replace with the following lines
security = user
username map = /etc/samba/smbusers
Append the following lines at the end of file
[Group]
comment = Group Folder
path = /home/group
public = yes
writable = no
valid users = system_username1 system_username2
create mask = 0700
directory mask = 0700
force user = nobody
force group = nogroup
Or if you want other network users to be able to edit to the folder change
writable = yes
Save the edited file
Read #How to add/edit/delete network users
sudo testparm
sudo /etc/init.d/samba restart
[edit]
How to share public folders with read only or read/write permissions (Authentication=Yes)
Read #General Notes
Read #How to install Samba Server for files/folders sharing service
sudo mkdir /home/public
sudo chmod 777 /home/public/
sudo cp /etc/samba/smb.conf /etc/samba/smb.conf_backup
gksudo gedit /etc/samba/smb.conf
Find this line
...
; security = user
...
Replace with the following lines
security = user
username map = /etc/samba/smbusers

Then follow either 1. or 2.
1. Save the edited file.
sudo testparm
sudo /etc/init.d/samba restart
1. Right click the folder and select 'Share folder'. Then change 'Do not share' to share with the network you would like.
1. In Share Properties note the read box. If you want other network users to be able to edit to the folder un-tick this.

OR
2. Append the following lines at the end of file
[public]
comment = Public Folder
path = /home/public
public = yes
writable = yes
create mask = 0777
directory mask = 0777
force user = nobody
force group = nogroup
2. Or if you want other network users to be able to edit to the folder
writable = yes
2. Save the edited file
2. Read #How to add/edit/delete network users
sudo testparm
sudo /etc/init.d/samba restart
[edit]
How to share public folders with read only or read/write permissions (Authentication=No)
Read #General Notes
Read #How to install Samba Server for files/folders sharing service
sudo mkdir /home/public
sudo chmod 777 /home/public/
sudo cp /etc/samba/smb.conf /etc/samba/smb.conf_backup
gksudo gedit /etc/samba/smb.conf
Find this line
...
; security = user
...
Replace with the following line
security = share

Then follow either 1. or 2.
1. Save the edited file.
sudo testparm
sudo /etc/init.d/samba restart
1. Right click the folder and select 'Share folder'. Then change 'Do not share' to share with the network you would like.
1. In Share Properties note the read box. If you want other network users to be able to edit to the folder un-tick this.

OR
2. Append the following lines at the end of /etc/samba/smb.conf (for a read-only folder)
[public]
comment = Public Folder
path = /home/public
public = yes
writable = no
create mask = 0777
directory mask = 0777
force user = nobody
force group = nogroup
2. Or if you want other network users to be able to edit to the folder
writable = yes


2. Save the edited file
sudo testparm
sudo /etc/init.d/samba restart
[edit]
How to print on remote Ubuntu machine via samba
Read #Print Server (cupsd)
Make sure your Ubuntu printers are configured properly.
sudo cp /etc/samba/smb.conf /etc/samba/smb.conf.backup
gedit /etc/samba/smb.conf
Find the following lines
...
# printing = cups
# printcap name = cups
...
and uncomment them.
printing = cups
printcap name = cups
Restart cups server
sudo /etc/init.d/cupsys restart
Now printers working on your Ubuntu machine should be acessible via samba.

What is Ubuntu?


What is Ubuntu?


Ubuntu is a community developed operating system that is perfect for laptops, desktops and servers. Whether you use it at home, at school or at work Ubuntu contains all the applications you'll ever need, from word processing and email applications, to web server software and programming tools.

Ubuntu is and always will be free of charge. You do not pay any licensing fees. You can download, use and share Ubuntu with your friends, family, school or business for absolutely nothing.

We issue a new desktop and server release every six months. That means you'll always have the the latest and greatest applications that the open source world has to offer.

Ubuntu is designed with security in mind. You get free security updates for at least 18 months on the desktop and server. With the Long Term Support (LTS) version you get three years support on the desktop, and five years on the server. There is no extra fee for the LTS version, we make our very best work available to everyone on the same free terms. Upgrades to new versions of Ubuntu are and always will be free of charge.

Think about Debian! [Part 1]


# dpkg
--------
This is the main package management program. dpkg can be invoked with many options. Some common uses are:

Find out all the options: dpkg --help.

Print out the control file (and other information) for a specified package: dpkg --info foo_VVV-RRR.deb

Install a package (including unpacking and configuring) onto the file system of the hard disk: dpkg --install foo_VVV-RRR.deb.

Unpack (but do not configure) a Debian archive into the file system of the hard disk: dpkg --unpack foo_VVV-RRR.deb. Note that this operation does not necessarily leave the package in a usable state; some files may need further customization to run properly. This command removes any already-installed version of the program and runs the preinst (see What is a Debian preinst, postinst, prerm, and postrm script?, Section 7.6) script associated with the package.

Configure a package that already has been unpacked: dpkg --configure foo. Among other things, this action runs the postinst (see What is a Debian preinst, postinst, prerm, and postrm script?, Section 7.6) script associated with the package. It also updates the files listed in the conffiles for this package. Notice that the 'configure' operation takes as its argument a package name (e.g., foo), not the name of a Debian archive file (e.g., foo_VVV-RRR.deb).

Extract a single file named "blurf" (or a group of files named "blurf*" from a Debian archive: dpkg --fsys-tarfile foo_VVV-RRR.deb | tar -xf - blurf*

Remove a package (but not its configuration files): dpkg --remove foo.

Remove a package (including its configuration files): dpkg --purge foo.

List the installation status of packages containing the string (or regular expression) "foo*": dpkg --list 'foo*'.
# APT
---------
APT is the Advanced Package Tool and provides the apt-get program. apt-get provides a simple way to retrieve and install packages from multiple sources using the command line. Unlike dpkg, apt-get does not understand .deb files, it works with the packages proper name and can only install .deb archives from a source specified in /etc/apt/sources.list. apt-get will call dpkg directly after downloading the .deb archives[5] from the configured sources.

Some common ways to use apt-get are:

To update the list of package known by your system, you can run:
apt-get update

(you should execute this regularly to update your package lists)

To upgrade all the packages on your system, run:
apt-get upgrade

To install the foo package and all its dependencies, run:
apt-get install foo

To remove the foo package from your system, run:
apt-get remove foo

To remove the foo package and its configuration files from your system, run:
apt-get --purge remove foo

To upgrade all the packages on your system to a new Debian GNU/Linux release, run:
apt-get dist-upgrade

Note that you must be logged in as root to perform any commands that modify the system packages.

The apt tool suite also includes the apt-cache tool to query the package lists. You can use it to find packages providing specific functionality through simple text or regular expression queries and through queries of dependencies in the package management system. Some common ways to use apt-cache are:

To find packages whose description contain word:
apt-cache search word

To print the detailed information of a package:
apt-cache show package

To print the packages a given package depends on:
apt-cache depends package

To print detailed information of the versions available for a package and the packages that reverse-depends on it:
apt-cache showpkg package

For more information, install the apt package and read apt-get(8), sources.list(5) and install the apt-doc package and read /usr/share/doc/apt-doc/guide.html/index.html.
# aptitude
--------------
aptitude is a package manager for Debian GNU/Linux systems that provides a frontend to the apt package management infrastructure. aptitude is a text-based interface using the curses library, it can be used to perform management tasks in a fast and easy way.

aptitude provides the functionality of dselect and apt-get, as well as many additional features not found in either program:

aptitude offers access to all versions of a package.

aptitude logs all its actions in /var/log/aptitude.

aptitude makes it easy to keep track of obsolete software by listing it under "Obsolete and Locally Created Packages".

aptitude includes a fairly powerful system for searching particular packages and limiting the package display. Users familiar with mutt will pick up quickly, as mutt was the inspiration for the expression syntax.

aptitude tracks which packages have been installed due to dependencies and removes them automatically when the packages that needed them are removed from the system.

aptitude can automatically install Recommended: packages[6].

aptitude can be used to install the predefined tasks available. For more information see tasksel, Section 8.1.4.

aptitude in full screen mode has su functionality embedded and can be run by a normal user. It will call su (and ask for the root password, if any) when you really need administrative privileges

You can use aptitude through a visual interface (simply run aptitude) or directly from the command line. The command line syntax used is very similar to the one used in apt-get. For example, to install the foo package, you can run aptitude install foo.

Note that aptitude is the preferred program for package management from console both for package installations and package or system upgrades.

For more informations, read the manual page aptitude(8) and install the aptitude-doc-en package.
# tasksel
------------
When you want to perform a specific task it might be difficult to find the appropiate suite of packages that fill your need. The Debian developers have defined tasks, a task is a collection of several individual Debian packages all related to a specific activity. Tasks can be installed through the tasksel program or through aptitude.

The Debian installer will typically install automaticaly, the task associated with a standard system and a desktop environment. The specific desktop environment installed will depend on the CD/DVD media used, most commonly it will be the GNOME desktop (gnome-desktop task). Also, depending on your selections throughout the installation process, tasks might be automatically installed in your system. For example, if you selected a language, the task associated with it will be installed automatically too and if you are running in a laptop system the installer recognises the laptop task will be installed too.
# dselect
-------------
This program is a menu-driven interface to the Debian package management system. This was the main package management interface for for first-time installations, but users are encouraged to use aptitude instead. Some users might feel more comfortable using aptitude and it is also recommended over dselect for large-scale upgrades. For more information on aptitude please see aptitude, Section 8.1.3.

dselect can:

guide the user as he/she chooses among packages to install or remove, ensuring that no packages are installed that conflict with one another, and that all packages required to make each package work properly are installed;

warn the user about inconsistencies or incompatibilities in their selections;

determine the order in which the packages must be installed;

automatically perform the installation or removal; and

guide the user through whatever configuration process are required for each package.

dselect begins by presenting the user with a menu of 7 items, each of which is a specific action. The user can select one of the actions by using the arrow keys to move the highlighter bar, then pressing the key to select the highlighted action.

What the user sees next depends on the action he selected. If he selects any option but Access or Select, then dselect will simply proceed to execute the specified action: e.g., if the user selected the action Remove, then dselect would proceed to remove all of the files selected for removal when the user last chose the Select action.

Both the Access menu item and the Select menu item lead to additional menus. In both cases, the menus are presented as split screens; the top screen gives a scrollable list of choices, while the bottom screen gives a brief explanation ("info") for each choice.

Extensive on-line help is available, use the '?' key to get to a help screen at any time.

The order in which the actions are presented in the first dselect menu represents the order in which a user would normally choose dselect to install packages. However, a user can pick any of the main menu choices as often as needed (including not at all, depending on what one wants to do).

Begin by choosing an Access Method. This is the method by which the user plans on accessing Debian packages; e.g., some users have Debian packages available on CD-ROM, while others plan to fetch them using anonymous FTP. The selected "Access Method" is stored after dselect exits, so if it does not change, then this option need not be invoked again.

Then Update the list of available packages. To do this, dselect reads the file "Packages.gz" which should be included in the top level of the directory where the Debian packages to be installed are stored. (But if it is not there, dselect will offer to make it for you.)

Select specific packages for installation on his system. After choosing this menu item, the user is first presented with a full screen of help (unless the `--expert' command line option was used). Once the user exits the Help screen, he sees the split-screen menu for choosing packages to install (or remove).

The top part of the screen is a relatively narrow window into the list of Debian's 18200 packages; the bottom part of the screen contains description of the package or group of packages which are highlighted above.

One can specify which packages should be operated on by highlighting a package name or the label for a group of packages. After that, you can select packages:
to be installed:

This is accomplished by pressing the `+' key.
to be deleted:

Packages can be deleted two ways:

removed: this removes most of the files associated with the package, but preserves the files listed as configuration files (see What is a Debian conffile?, Section 7.5) and package configuration information. This is done by pressing the `-' key.

purged: this removes every file that is part of the package. This is done by pressing the `_' key.

Note that it's not possible to remove "All Packages". If you try that, your system will instead be reduced to the initial installed base packages.
to be put "on hold"

This is done by pressing `=', and it effectively tells dselect not to upgrade a package even if the version currently installed on your system is not as recent as the version that is available in the Debian repository you are using (this was specified when you set the Access Method, and acquired when you used Update).

Just like you can put a package on hold, you can reverse such setting by pressing `:'. That tells dselect that the package(s) may be upgraded if a newer version is available. This is the default setting.

You can select a different order in which the packages are presented, by using the `o' key to cycle between various options for sorting the packages. The default order is to present packages by Priority; within each priority, packages are presented in order of the directory (a.k.a. section) of the archive in which they are stored. Given this sort order, some packages in section A (say) may be presented first, followed by some packages in section B, followed by more packages (of lower priority) in section A.

You can also expand meanings of the labels at the top of the screen, by using the `v' (verbose) key. This action pushes much of the text that formerly fit onto the display off to the right. To see it, press the right arrow; to scroll back to the left, press the left arrow.

If you select a package for installation or removal, e.g., foo.deb, and that package depends on (or recommends) another package, e.g., blurf.deb, then dselect will place the you in a sub-screen of the main selection screen. There you can choose among the related packages, accepting the suggested actions (to install or not), or rejecting them. To do the latter, press Shift-D; to return to the former, press Shift-U. In any case, you can save your selections and return to the main selection screen by pressing Shift-Q.

Users returning to the main menu can then select the "Install" menu item to unpack and configure the selected packages. Alternatively, users wishing to remove files can choose the "Remove" menu item. At any point, users can choose "Quit" to exit dselect; users' selections are preserved by dselect.
* Other package management tools
===========================================
# dpkg-deb
----------------------
This program manipulates Debian archive(.deb) files. Some common uses are:

Find out all the options: dpkg-deb --help.

Determine what files are contained in a Debian archive file: dpkg-deb --contents foo_VVV-RRR.deb)

Extract the files contained in a named Debian archive into a user specified directory: dpkg-deb --extract foo_VVV-RRR.deb tmp extracts each of the files in foo_VVV-RRR.deb into the directory tmp/. This is convenient for examining the contents of a package in a localized directory, without installing the package into the root file system.

Note that any packages that were merely unpacked using dpkg-deb --extract will be incorrectly installed, you should use dpkg --install instead.

More information is given in the manual page dpkg-deb(1).
# dpkg-split
-----------------
This program splits large package into smaller files (e.g., for writing onto a set of floppy disks), and can also be used to merge a set of split files back into a single file. It can only be used on a Debian system (i.e. a system containing the dpkg package), since it calls the program dpkg-deb to parse the debian package file into its component records.

For example, to split a big .deb file into N parts,

Execute the command dpkg-split --split foo.deb. This will produce N files each of approximately 460 KBytes long in the current directory.

Copy those N files to floppy disks.

Copy the contents of the floppy disks onto the hard disk of your choice on the other machine.

Join those part-files together using dpkg-split --join "foo*".
8.2 Debian claims to be able to update a running program; how is this accomplished?

The kernel (file system) in Debian GNU/Linux systems supports replacing files even while they're being used.

We also provide a program called start-stop-daemon which is used to start daemons at boot time or to stop daemons when the runlevel is changed (e.g., from multi-user to single-user or to halt). The same program is used by installation scripts when a new package containing a daemon is installed, to stop running daemons, and restart them as necessary.
# How can I tell what packages are already installed on a Debian system?
------------------------------------------------------------------------------------------------
To learn the status of all the packages installed on a Debian system, execute the command
dpkg --list

This prints out a one-line summary for each package, giving a 2-letter status symbol (explained in the header), the package name, the version which is installed, and a brief description.

To learn the status of packages whose names match the string any pattern beginning with "foo" by executing the command:
dpkg --list 'foo*'

To get a more verbose report for a particular package, execute the command:
dpkg --status packagename
# How to display the files of a package installed?
----------------------------------------------------------------------
To list all the files provided by the installed package foo execute the command
dpkg --listfiles foo

Note that the files created by the installation scripts aren't displayed.
# How can I find out what package produced a particular file?
--------------------------------------------------------------------------------------
To identify the package that produced the file named foo execute either:

dpkg --search filename

This searches for filename in installed packages. (This is (currently) equivalent to searching all of the files having the file extension of .list in the directory /var/lib/dpkg/info/, and adjusting the output to print the names of all the packages containing it, and diversions.)

A faster alternative to this is the dlocate tool.
dlocate -S filename

zgrep foo Contents-ARCH.gz

This searches for files which contain the substring foo in their full path names. The files Contents-ARCH.gz (where ARCH represents the wanted architecture) reside in the major package directories (main, non-free, contrib) at a Debian FTP site (i.e. under /debian/dists/etch). A Contents file refers only to the packages in the subdirectory tree where it resides. Therefore, a user might have to search more than one Contents files to find the package containing the file foo.

This method has the advantage over dpkg --search in that it will find files in packages that are not currently installed on your system.

apt-file search foo

If you install the apt-file, similar to the above, it searches files which contain the substring or regular expression foo in their full path names. The advantage over the sample above is that there is no need to retrieve the Contents-ARCH.gz files as it will do this automatically for all the sources defined in /etc/apt/sources.list when you run (as root) apt-file update.
# Why doesn't get `foo-data' removed when I uninstall `foo'? How do I make sure old unused library-packages get purged?
--------------------------------------------------------
Some packages that are split in program (`foo') and data (`foo-data'). This is true for many games, multimedia applications and dictionaries in Debian and has been introduced since some users might want to access the raw data without installing the program or because the program can be run without the data itself, making it optional.

Similar situations occur when dealing with libraries: generally these get installed since packages containing applications depend on them. When the application-package is purged, the library-package might stay on the system. Or: when the application-package no longer depends upon e.g. libdb4.2, but upon libdb4.3, the libdb4.2 package might stay when the application-package is upgraded.

In these cases, `foo-data' doesn't depend on `foo', so when you remove the `foo' package it will not get automatically removed by most package management tools. The same holds true for the library packages. This is necessary to avoid circular dependencies. If you use aptitude (see aptitude, Section 8.1.3) as your package management tool it will, however, track automatically installed packages and remove them when no packages remain that need them in your system.