five-session intensive course on playing with linux

124
Five-Session Intensive Course on Playing with Linux Presented by Adrian S. W. TAM ([email protected]) September 2002 Dedicated to the FYP students of Prof. P. C. Wong

Upload: others

Post on 02-Feb-2022

4 views

Category:

Documents


0 download

TRANSCRIPT

Five-Session Intensive Course on Playing with Linux

Presented by

Adrian S. W. TAM ([email protected])

September 2002

Dedicated to the FYP students of Prof. P. C. Wong

The Logo of LinuxA PenguinHis name is Tux

Red Hat is not LinuxRed Hat is a distribution, not a LinuxList of well-known distributions:

Mandrake-Linux (Largest in US)SuSE (Best reputation in Europe)Debian (Official Distribution of Developers)Slackware (Grandfather's memory)Red Hat (Most well-known by non-Linuxians)Red Flag (Let's BOYCOTT this one)Gentoo (Maybe the best distro ever)LFS (Real player's choice)

Other DistributionsCD Linux

DemoLinux, Virtual Linux, KnoppixFloppy Linux

floppix, tomsrtbt, Tiny LinuxFirewall / Router

gibalter, floppyfw, fli4l

What is Linux?Linux = an OS kernel

Locates between (app.) software and electronicsCoordinationError handlingSignal handlingHardware interfacingProcess handlingSecurity manipulation

What is Linux?OS needs software

User interface (sh, csh, bash, tcsh, ash, zsh, pdksh)File manipulation (cp, rm, ln, ls, mkdir, cd, rmdir)Text processing (vi, sed, awk, grep, uniq, sort)Archiving (zip, tar, bzip2, gzip, cpio, dd)User management (useradd, usermod, userdel)Process management (ps, kill, top, nice, renice)Networking (ftp, wget, telnet, ping, snort, tcpdump)Programming (gcc, gmake, g++, g77, gcj, gdb)Automation (cron, at, batch, perl, sh, bg, fg)GUI (X, xfs, gnome, xfce, kde, mozilla, xfig, lyx)

What is Linux?GNU (FSF) provides softwareLinux provides kernelCombine = GNU/Linux = Complete OS package

What is Linux?GNU/Linux is not FREE!

Money can be chargedEfforts should be paid

GNU/Linux is FREE!Freedom to do everythingFreedom to know everything

Why Linux?Linux is POWERFUL

Inherits 40 years' experience from UNIXCouples with (?) UNIX software packagesUses the wonderful design of UNIXPortabilityEfficiencyFunctionalityAvailabilityReliability

Why Linux?Linux is not so good

Weak networkingYoungNot unifiedNot guarenteed

Why Linux?Non-Linux UNIX alternatives:

FreeBSD / NetBSD / OpenBSD / BSDiCaldera SCO OpenUnixSun Microsystems SolarisIBM AIXHP-Compaq HP-UXHP-Compaq OpenVMSMicrosoft (?) XENIXApple MacOS XGNU HurdOSF Mach

Why Linux?UNIX-like Non-UNIX alternatives:

AT&T Plan9BeOSAtheOSNeXT

Non-UNIX-like non-UNIX non-alternatives:Apple MacOS <=9Microsoft WindowsPalmOSDOSCP/M

MottosEverything is a fileCommand line is wonderfulJoin the building blocksMan is powerfulGoogle is almighty

Installation

Installing LinuxHard Disk Partitioning

IBM PC Compatibles with EIDE interface hard disk1 HD <= 20 PartitionsPartitions = {Primary, Extended}Primary Partition <= 4Extended Partition <= 16U{Extended Partition} = Primary Partition 4

Installing LinuxHard Disk Partitioning

Primary Partition = /dev/hda1 to /dev/hda4Extended Partition = /dev/hda5 to /dev/hda20Primary master = /dev/hdaPrimary slave = /dev/hdbSecondary master = /dev/hdcSecondary slave = /dev/hdd

Installing LinuxFile Systems

Native file system: ext2Journaling: ext3 (Recommanded)Other Journaling: ReiserFS, XFS, JFSOther FS: NTFS, UFS, FAT, Minix, Novell, ...Network: NFS, Coda, SMB/CIFS, ...

usersKernel

Virtual File System

ext2 JFS UFS FAT ext3

Installing LinuxAccountRoot AccountGroupUID/GIDFile mode (Permissions)File attributeProcessPIDSignal

Installing LinuxFileDeviceDaemonPlumbingForeground / BackgroundVirtual Console / TerminalShellCompilation

Installing Linux isn't difficult, but there are many details to remember── Running Linux, Welsh et al

Login / Logout

LoginLogin

Debian GNU/Linux stable server1 tty1server1 login: rootPassword: xxxxxLast login: Mon Sep 2 09:32:28 2002 on tty1Linux server1 2.4.19 #24 Sun Aug 25 20:13:22 HKT 2002 i686 unknown unknown GNU/Linuxserver1:~#

Logoutexitshutdown -h nowshutdown -r now

File Hierarchy

File Hierarchy/bootBoot files (kernel, System.map, boot loader)/binEssential binary files (programs)/sbinEssential system binary files/devDevice files resides here/procProcess files resides here

File Hierarchy/etcUsually configuration files stores here/libDynamic linking libraries, system modules/tmpTemp dir/varVariable data (log files, caches, spools)/usrStatic data (C:\Program Files\ ?)

File Hierarchy/rootThe home directory of root/homeThe home directories of other users/home/adrianThe home directory of user 'adrian'

File Hierarchy/usr/bin: Not-so-essential binary/usr/sbin: Not-so-essential system binary/usr/lib: Not-so-essential libraries/usr/share: Shared data/usr/share/doc: Documentation/usr/local: Local data (user-made programs)/usr/local/bin: User-made binary programs/usr/local/sbin: User-made system binary programs

File Hierarchy/var/log: Log files/var/cache: Cache files/var/spool: Spools (print spool, etc.)/var/tmp: Temp files

File Hierarchy/|-- bin binary executables (essential)|-- boot boot files|-- dev device file system|-- etc configuration files, startup scripts|-- home home directories of users| |-- adrian home dir. of Adrian| |-- brian home dir. of Brian| `-- carson home dir. of Carson|-- lib dynamic linking libraries|-- misc miscellaneous (empty)|-- mnt mount points|-- net network mounts (empty)|-- opt optionals (empty)|-- proc process file system|-- root home dir. of root user|-- sbin binary executables for system admin use (essential)|-- swap swaps (optional)|-- tmp temporaries|-- usr (user) static data| |-- X11R6 X-Window| |-- bin application executables| |-- etc| |-- include C/C++ header files| |-- lib C/C++ static linking libraries| |-- local| |-- man man pages| |-- sbin application executables for system admin use| |-- share share files (pics, icons, ...)| |-- src source`-- var dynamic data

Important Files/etc/X11/XF86Config: XFree86 configuration/etc/inittab: init table/etc/fstab: mount table/etc/passwd: password file/etc/group: group assignments/etc/crontab: table of cron jobs/var/log/messages: Program messages/var/log/syslog: System logs/var/log/auth.log: Authentication logs

Strange??No 'drive' conceptUnified directory treeDifferent media are connected via a 'mount' process*BSD can use mount to enlarge a storage space!(Not possible in Linux, though)

So...re-partitioningExample:/dev/hda1 500MB Mounted at //dev/hda2 2 GB Mounted at /usr/dev/hda3 2 GB Mounted at /var/dev/hda4 5.5 GB/dev/hda5 500MB Swap/dev/hda6 4 GB Mounted at /home/dev/hda7 1 GB Mounted at /root

Boot Loader

x86 Booting ProcedureSystem startupChecking (CPU, RAM)Bootstraping all components togetherDo critical checkings (a.k.a. POST)Seek for peripherial devicesFollowing the booting procedure to seek for OSBoot sector is loadedControl is passed on to the boot sector from the BIOS

x86 IDE Hard DiskFirst block = Partition TableSecond block = Boot sector (A program)

Boot loaderLILO (Linux Loader)GrubThe boot loader will first do some basic jobThen loads the OS kernel and pass the control to itThe kernel then do several things:

Call the start-up scriptsLoad user interfaces (CLI / GUI)Start background jobs (daemons)

Boot loader/etc/lilo.confConfiguration file of LILO/boot/grub/menu.lstConfiguration file (menu definition) of Grub

LILO Configuration/etc/lilo.conf

lba32 #Support >1024 cylinderboot=/dev/hda #Boot sectorroot=/dev/hda1 #Default root partition

#Select boot sector: bmp/compat/menu/textinstall=/boot/menu.bmap=/boot/map

delay=20 #Wait 2 second before choosing defaultvga=794 #1280x1024 framebuffer display

default=Linux #Default boot option

image=/boot/vmlinuz label=Linux read-only

other=/dev/hda2 label=Win2000 loader=/boot/chain.b

Shell Basics

Shell BasicsRoot Prompt: #User Prompt: $

Shell BasicsGet help:

manapropos/usr/share/doc/*Googles

Shell BasicsListing directories: ls

Long listing: ls -lInclude hidden file: ls -aWith color: ls --colorWith mark: ls -FRecurrsive: ls -R

Shell Basics

[adrian@gateway adrian]$ ls -ltotal 2136-rwxr-xr-x 1 root root 1977085 Oct 29 16:52 All.pdf*drwxrwxr-x 3 adrian adrian 4096 Nov 3 03:07 Desktop/drwxr-xr-x 3 adrian adrian 4096 Nov 3 01:36 GNUstep/-rwxr--r-- 1 root root 58093 Oct 8 22:10 K38114-2.sxi*-rw-rw-r-- 1 adrian adrian 58308 Nov 3 04:07 K38114-3.sxi-rw-r--r-- 1 adrian adrian 19280 Nov 3 01:40 blackbox-menudrwx------ 2 adrian adrian 4096 Oct 29 11:43 nsmail/-rw-r--r-- 1 adrian adrian 25110 Nov 3 01:40 pwm-mdk-menu.conf-rw-rw-r-- 1 adrian adrian 0 Nov 3 04:11 sample-rw-rw-r-- 1 adrian adrian 4035 Nov 3 03:40 sample~drwxrwxr-x 3 adrian adrian 4096 Nov 3 02:00 starsuite6/drwx------ 2 adrian adrian 4096 Oct 29 19:26 tmp/[adrian@gateway adrian]$

Type

Permissions

# of hard links

Owner

Group

size

Modification date

File name

File LinksHard Links

Two symbols pointed to same content in FSNot for directories

Soft LinksA symbol pointed to another fileAlso known as symbolic linksIt is clear which is the master copy

File HandlingViewing content = catViewing by pages = more / lessCopy files = cpMoving files or rename = mvRemove files = rmMake directory = mkdirChange directory = cdRemove directory = rmdirCreate links = ln

NomenclatureDirectory separator = /Root directory = /Local directory = .Parent directory = ..Home directory = ~Escape character = \Chars to be escaped = {space,\,/,','',`,*,?,brackets}Names are case-sensitive

StreamsMake output to a file

command > fileMake file as input

command < fileMake command1's output be command2's input

command1 | command2Append output to file

command >> file

StreamsMake error and output join together

command 2>&1Here document

command << endmarkCommand substitution

command `command1`

Filename expansionWildcards: * and ?Single character substitution: ls pic-[abcdefg].jpegSingle character substitution: ls pic-[a-gA-G].jpegSingle character substitution: ls pic-[^h-z].jpegString substitution: ls pic-{mother,father}.jpeg

File modesA file can be assigned to have one user and one group of ownershipChange user owner: chownChange group owner: chgrpChange permission: chmod

[adrian@gateway adrian]$ ls -ltotal 2136-rwxr-xr-x 1 root root 1977085 Oct 29 16:52 All.pdf*drwxrwxr-x 3 adrian adrian 4096 Nov 3 03:07 Desktop/drwxr-xr-x 3 adrian adrian 4096 Nov 3 01:36 GNUstep/-rwxr--r-- 1 root root 58093 Oct 8 22:10 K38114-2.sxi*-rw-rw-r-- 1 adrian adrian 58308 Nov 3 04:07 K38114-3.sxi-rw-r--r-- 1 adrian adrian 19280 Nov 3 01:40 blackbox-menudrwx------ 2 adrian adrian 4096 Oct 29 11:43 nsmail/-rw-r--r-- 1 adrian adrian 25110 Nov 3 01:40 pwm-mdk-menu.conf-rw-rw-r-- 1 adrian adrian 0 Nov 3 04:11 sample-rw-rw-r-- 1 adrian adrian 4035 Nov 3 03:40 sample~drwxrwxr-x 3 adrian adrian 4096 Nov 3 02:00 starsuite6/drwx------ 2 adrian adrian 4096 Oct 29 19:26 tmp/[adrian@gateway adrian]$

File modeschown owner filenamechgrp group filenamechmod [augo][+-=][rwxX] filename

[augo] = {all,user,group,other}[+-=] = {allow,disallow,only}[rwxX] = {read,write,execute,execute}

chmod octal_mode filenameChange attribute on EXT2: chattr

File modes--- = No access to this filer-- = Read only-w- = Write only--x = Execute onlyA directory needs x to cd toA directory needs r to ls

Process trackingEvery running program is a processEach process has a process ID, PIDList process: ps

Common usage: ps ax / ps aux / psContinuously list process: topKilling process: kill pidStronger kill: kill -9 pid

Users and GroupsAdd user: useraddRemove user: userdelModify user: usermodAssign password: passwdAdd groups: groupaddRemove groups: groupdelModify groups: groupmodEasier to do: linuxconf

Further studyHighly recommended:Learning the bash Shell 2/eCameron Newham and Bill RosenblattO'Reilly & Associates

Further StudyEnvironment variablesEcho command$[] calculationShell programmingStreamline editor: sedhttp://pegasus.rutgers.edu/~elflord/unix/sed.htmlCommands:sort, grep, head, tail, whoami, pwd, su, tr, cut, uniq, df, du, tar, gzip, compress, bzip2, more, lessRegular Expressions

Software Management

Software for *nixEverything is a file

Unlike MS Windows, we have no registryInstall/Uninstall = Create/Delete files

InstallationPut files into correct placesExecute by calling the name of the executables

UninstallDelete corresponding executablesDelete correcponding auxillary filesNotify other program (sometimes, if needed)

Software PackagesSource tar ball

Archive of source codesRequires compilation

Binary tar ballArchive of binary programUsually a script is bundled for installation

Debian Packagesdpkg -i packagefile

Red Hat Packagesrpm -i pakcagefile

Source Tar BallMost UNIX program are written in C/C++Install tar ball:

# lssoftware-1.0.0.tar.gz# tar zxf software-1.0.0.tar.gz# lssoftware-1.0.0 software-1.0.0.tar.gz# cd software-1.0.0# ./configure --prefix=/usr..........# make..........# make install..........#

RPMThe software management system for Red Hat-alike favorsWidely usedDependancy checkingSoftware trackingAutomatic configuration during (un)install is supported

RPMInstallation

rpm -i software-1.0.0-i386.rpmUninstall

rpm -e softwareUpgrade

rpm -U software-1.0.2-i386.rpmListing

rpm -qaPackage information

rpm -qi softwareList files

rpm -ql software

DPKGThe software management system for Debian-alike favorsLess-widely usedDependancy checkingSoftware trackingAutomatic configuration during (un)install is supportedPackage listingDynamic upgradeInternet integration

DPKGInstallation / Upgrade

dpkg -i software-1.0.0.debRemove (Uninstall)

dpkg -r softwarePurge

dpkg -P softwaredListing

dpkg -lPackage information

dpkg -p softwareList files

dpkg -L software

Kernel Rebuild

Linux KernelKernel is important, essential, criticalDevelop by Linus Torvalds et alWeb site at:

Main = http://www.kernel.orgCrypto = http://www.kerneli.org

Get it from ftp://ftp.kernel.org

Rebuild KernelWe may rebuild kernel because:

UpgradeSecurity fixModify functions availableAdd driversPerformance/Stability tuningFor funOther reasons

Rebuild KernelSteps for rebuilding kernel

Get a source tar ball from somewhereExtract the tar ball to /usr/srcmake config / make menuconfig / make xconfigmake bzImage / make diskmake modulesmake modules_installmake installRe-install boot program (LILO / Grub)Reboot and use the new kernel

Rebuild KernelWhen make menuconfig, you may see some functions available as linked or available as moduleMonolithic kernel → LinkedModules: Load on request → Save memory

Kernel ModulesSometimes, a hardware developer would provide Linux drivers as compiled modules because he do not want to release the source codeExample: VIA 82C686A Sound Driver

Kernel ModulesModules location: /lib/modules/version/*List modules: lsmodRemove modules: rmmod module_nameLoad modules: modprobe module_nameLoad modules: insmod module_nameForcefully load modules: insmod -f module_nameAutomatically load modules on boot: /etc/modulesAutomatically load modules on request: /etc/modules.conf

Linux Networking

Linux NetworkingLinux is a UNIX favorNative networking: TCP/IPInherits many networking capabilities from BSD

Linux NetworkingNetwork interface configuration

RH: /etc/sysconfig/networkingDebian: /etc/network/interface

Device filesEthernet: /dev/eth0, /dev/eth1, ...PPP: /dev/ppp0, /dev/ppp1, ...Tunnels: /dev/tun0, /dev/tun1, ...

Name Resolution Setting/etc/resolv.conf/etc/hosts

Linux NetworkingNetworking commands

Config: ifconfigRouting: routeResolution: host / dig / nslookupPing: pingIP Filtering: iptables / ipchains / ipfwadmStates: netstatDownload: wget / rsyncBrowsing: lynxFTP: ftp / ncftp / ...Enable packet forwarding:echo 1 > /proc/sys/net/ipv4/forward

Basic System Administation

x86 Booting RevisitedBooting procedure:

System loader startedKernel loaded (PID = 0 ?)Initializing essential device drivers (a.k.a. modules)Execute program /sbin/init (PID = 1)init spawns other processes (PID > 1)

Follows instructions of /etc/inittab to spawnModifying /etc/inittab can cause the whole system changed

/etc/inittab# /etc/inittab: init(8) configuration.id:2:initdefault: # Default runlevelsi::sysinit:/etc/init.d/rcS # Run rc script on boot~~:S:wait:/sbin/sulogin # What to do in single user mode # /etc/init.d executes the S and K scripts upon change of runlevel.l0:0:wait:/etc/init.d/rc 0 # Haltl1:1:wait:/etc/init.d/rc 1 # single userl2:2:wait:/etc/init.d/rc 2 # multiuserl3:3:wait:/etc/init.d/rc 3 # multiuserl4:4:wait:/etc/init.d/rc 4 # multiuserl5:5:wait:/etc/init.d/rc 5 # multiuserl6:6:wait:/etc/init.d/rc 6 # reboot# Normally not reached, but fallthrough in case of emergency.z6:6:respawn:/sbin/sulogin

# What to do when CTRL-ALT-DEL is pressed.ca:12345:ctrlaltdel:/sbin/shutdown -t1 -a -r now

# /sbin/getty invocations for the runlevels.# <id>:<runlevels>:<action>:<process>1:2345:respawn:/sbin/getty 38400 tty12:23:respawn:/sbin/getty 38400 tty23:23:respawn:/sbin/getty 38400 tty34:23:respawn:/sbin/getty 38400 tty45:23:respawn:/sbin/getty 38400 tty56:23:respawn:/sbin/getty 38400 tty6

/etc/inittabModifying inittab

allows you to change the behavior of system bootingyou can make a system with no console login

unattended serverFormat of inittab

Rule of thumb: Read man-pagesEvery line is:code:runlevel(s):init action:command and parameters

Reference: Chapter 5 of Running Linux

RunlevelsRunlevels are defined by /sbin/init

Runlevel 1 = Single user modeRunlevel 2,3,4 = CLI multi-user modeRunlevel 5 = GUI multi-user modeRunlevel 6 = Reboot

/sbin/init calls different set of rc scripts on different runlevels

Do different jobs and hence different behaviors on different runlevels

RunlevelsChange runlevel (root only): init

Example: init 5Reboot: init 6Shutdown system: shutdown -h now

Do 'init 0' to kill all processes and end-up, then halt the system

Startup scriptsResides in /etc/rc.d/init.d (RH) or /etc/init.d (Debian)

rc scriptsResides in /etc/rc.d (RH) or /etc (Debian)Top-level: /etc/rc.d/rc (RH) or /etc/rc (Debian)

Startup ScriptsStartup scripts

Runlevel rc scripts directory: /etc/(rc.d/)rcN.dN = 0 to 6, correspond to runlevel

All files are symlinks to /etc/(rc.d/)init.d/*All files will be executed at that runlevelFilename Snnxxxx or Knnxxxx

nn = a number from 00 to 99, marks the sequencexxxx = name of the programK = killerS = Starter

Startup ScriptsRun all K-script, then all S-script

Kill all existing, thenStart required programs

Number indicates the order of executionIn ascending order

Virtual TerminalsAfter all scripts executed, the system loads VTs/etc/inittab contains /sbin/*getty

Starts 6 VTs for login, usuallyDifferent getty for different behaviorMandrake: mingetty, Debian: getty, Red Hat: agettyXLinux starts a Framebuffer getty for Chinese console on VT #12Switching between VTs: Ctrl+Alt+Fn

Sometimes, inittab would load xdm/kdm/gdm for GUI login on runlevel 5

Virtual TerminalKills console login: Delete all getty lines in inittab

Unattended server!Further detail on /etc/inittab and /sbin/init:

Chapter 5 of Running Linux 3/e by Matt Welsh et al

ProcessesEvery program are directly or indirectly spawned by /sbin/initEvery program has a PID > 1The information about the program are in /proc/pid/*

Everything is a file!!e.g.: Which command calls this process??

cat /proc/pid/cmdlineProcess management: kill, killall, ps, top

These program just help you to read the data from /proc/pid/*

Processesps command

ps = List processes running in current login sessionps ax = List all processes in the systemps aux = List 'ps ax' with owners' username

top commandTable Of ProcessesContinuous update

ProcessesKill processes: kill / killallKilling mother process may:

Kill its child processesCommon practice: Kick out a user = Kill its login shellAll login consoles are parent of its child processes

Make its child process orphan processThose process running in backgroundThose process programmed to run as daemon

/proc/*Some system-specific information can be obtained in /proc too

PCI bus: /proc/pciIRQ: /proc/interruptCPU: /proc/cpuinfoI/O port: /proc/ioportsUptime: /proc/uptimeCPU loading: /proc/loadavgMemory: /proc/meminfo

Sometimes we need writing to /proc for changing system behavior (e.g. enable routing)

AutomationAutomation can be done by crond and atd systemscron = Process scheduling

Regular executionConfiguration: /etc/crontabFormat: (excerpt from Running Linux 3/e)

Automationat job = Delayed execution

Preset executionRun once onlyNeed to have atd daemon runningExample:# at 16:00at> slocate -uat> (Ctrl-D)job 1 at 2002-09-07 16:00#

Final note...O'Reilly has tons of books about UNIX SysAdminRunning Linux is a very good introductory referenceA UNIX System Administrator uses vi, not pico

Reference:Learning the vi Editor 6/e (O'Reilly & Associate)Vi Pocket Reference (O'Reilly & Associate)

Emacs is an alternative to vi, but it's an all-in-one giantcreated by the GNU godfather, Richard Stallman

Pico is simple but not powerful enoughInstall through pine

Daemons

DaemonProgram?

The executable filesProcess?

The running program that noticable in psDaemon?

A special process that:Generally no parent processes (TTY = “ ? ”)Not disturbing the user, just runs interminablyUnless using some method like 'kill' command, it won't stopMostly listening on some TCP/IP ports (e.g. Apache) or monitoring something (e.g. cron)

DaemonExample:

Web: /etc/init.d/httpFTP: /etc/init.d/proftpdSSH: /etc/init.d/sshdTelnet: /etc/init.d/telnetNFS: /etc/init.d/nfsX Font Server: /etc/init.d/xfs

Example:cron: /etc/init.d/crondat: /etc/init.d/atdapm: /etc/init.d/apmd

Network Servers

Network Client/ServerTCP/IP provides 65536 TCP ports (channel) for communicationThe server takes a port, listen to itThe client talks to a port, server respond to it

Communication!

Network Client/ServerExample: HTTP

Server takes TCP/80 and listenClient sent message “get /index.html” to server TCP/80Server response:200 OKcontent-type: text/html<html><head>...</head><body>.....................

Network Client/Server

Clie

nt (b

row

ser)

Serv

er (A

pach

e)

get /index.html

200 OKcontent-type: text/html<HTML><HEAD>...</HEAD><BODY>.......</BODY></HTML>

Network Client/ServerEvery client-server pair is aimed to communicate between two processesThey may or may not be in the same hostUsing client-server mechanism for flexibility, expansibility or conventionDetails involved network programming, which is out of our scope here

Reference: UNIX Network Programming 2/e Volume 1 by W. Richard Stevens

Common ServersWeb: Apache (httpd)FTP: wu-ftpd or ProFTPdTelnet: telnetdSSH: OpenSSHX-Server: XFree86Database: Oracle, MySQL, miniSQL, PostgreSQLMail: Sendmail, postfix, qmail, eximDHCP: dhpcdNews: InterNetNews (innd)Web Proxy: SquidRouting: Zebra

Common ServersDNS: BINDVPN: PoPToP or FreeS/WANSNMP: UCD-SNMP, mrtgFile server: Samba, NFSDialup: pppdPrinting: CUPS, LPRng, LPRFirewall: ipfwadm, ipchains, ipfwadm, tcpwrapperGroupware: PHPgroupware

Common ServersTons of server softwares available for LinuxFind what you need through Googles

e.g. Find “VPN Linux”

Web Server

Web ServerApache

Most current version: 2.060%+ market shareHighly flexible, configurable, robust

kHTTPdLinux kernel patchAvailable in all recent kernelsMuch faster as it is run in kernel modePlain

Apache Web ServerAfter installation,

Server program in /usr/sbinStart-up script in /etc(/rc.d)/init.dConfiguration file in /etc/apache/httpd.confFunctionality can be extended by using modules

Configuration: modify httpd.conf

Apache Web ServerRun it:/usr/sbin/apache -d /var/www/dataServer root: /var/www/data/*-d directive: Specify server root-f directive: Specify alternative config. fileGet help:

httpd -hhttp://www.apache.org/

Apache Configration FileServerType standaloneServerRoot /etc/apacheLockFile /var/lock/apache.lockPidFile /var/run/apache.pidScoreBoardFile /var/run/apache.scoreboardTimeout 300KeepAlive OnMaxKeepAliveRequests 100KeepAliveTimeout 15MinSpareServers 5MaxSpareServers 10StartServers 5MaxClients 150MaxRequestsPerChild 100

LoadModule config_log_module /usr/lib/apache/1.3/mod_log_config.soLoadModule mime_magic_module /usr/lib/apache/1.3/mod_mime_magic.soLoadModule mime_module /usr/lib/apache/1.3/mod_mime.soLoadModule negotiation_module /usr/lib/apache/1.3/mod_negotiation.soLoadModule status_module /usr/lib/apache/1.3/mod_status.soLoadModule autoindex_module /usr/lib/apache/1.3/mod_autoindex.soLoadModule dir_module /usr/lib/apache/1.3/mod_dir.soLoadModule cgi_module /usr/lib/apache/1.3/mod_cgi.soLoadModule userdir_module /usr/lib/apache/1.3/mod_userdir.soLoadModule alias_module /usr/lib/apache/1.3/mod_alias.soLoadModule rewrite_module /usr/lib/apache/1.3/mod_rewrite.soLoadModule access_module /usr/lib/apache/1.3/mod_access.soLoadModule auth_module /usr/lib/apache/1.3/mod_auth.soLoadModule expires_module /usr/lib/apache/1.3/mod_expires.soLoadModule unique_id_module /usr/lib/apache/1.3/mod_unique_id.soLoadModule setenvif_module /usr/lib/apache/1.3/mod_setenvif.soExtendedStatus On

Port 80User www-dataGroup www-dataServerAdmin [email protected] /var/www

Apache Configration File<Directory /> Options SymLinksIfOwnerMatch AllowOverride None</Directory>

<Directory /var/www/> Options Indexes Includes FollowSymLinks MultiViews AllowOverride None Order allow,deny Allow from all</Directory>

<IfModule mod_userdir.c> UserDir public_html</IfModule>

<Directory /home/*/public_html> AllowOverride FileInfo AuthConfig Limit Options MultiViews Indexes SymLinksIfOwnerMatch IncludesNoExec <Limit GET POST OPTIONS PROPFIND> Order allow,deny Allow from all </Limit> <Limit PUT DELETE PATCH PROPPATCH MKCOL COPY MOVE LOCK UNLOCK> Order deny,allow Deny from all </Limit></Directory>

<IfModule mod_dir.c> DirectoryIndex index.html index.htm index.shtml index.cgi</IfModule>

Apache Configuration FileAccessFileName .htaccessUseCanonicalName OnTypesConfig /etc/mime.typesDefaultType text/plainCustomLog /var/log/apache/access.log combinedServerSignature OnScriptAlias /cgi-bin/ /usr/lib/cgi-bin/

<Directory /usr/lib/cgi-bin/> AllowOverride None Options ExecCGI Order allow,deny Allow from all</Directory>

<IfModule mod_perl.c> Alias /perl/ /var/www/perl/ <Location /perl> SetHandler perl-script PerlHandler Apache::Registry Options +ExecCGI </Location></IfModule>

Common Gateway InterfaceCGI = A means to do dynamic contentPrinciple:

Clie

nt (B

row

ser)

Serv

er (A

pach

e)

get /cgi-bin/foo

200 OKcontent-type: ..........

OS

(Lin

ux)

(Client) | foo.cgi

foo.cgi > (server)

Common Gateway InterfaceUser Input = Environmental variablesStandard output = Web output

Common Gateway InterfaceHow to enable CGI in Apache?

Put the scripts in some script directory, e.g. /cgi-bin/*Enable Apache to process CGIs by add directives to the configuration file

Pointing out the scripts directory (option ExecCGI)Load the CGI modules (mod_cgi.so)

Web AuthenticationYou may want to authenticate a user before he can access your webUsing the file .htaccess to control the access

Filename specified in config fileThe file contains directives that overrides those in httpd.conf

Web AuthenticationExample .htaccess:AuthType BasicAuthName "Authorized users only"AuthUserFile /home/adrian/public_html/passwordsRequire valid-user

Create password file# htpasswd -c /home/adrian/public_html/passwords adrianNew password: (password here)Re-type new password: (password here)Adding password for user adrian

PHPA very fast, robust scripting for dynamic contentFaster and more reliable than CGILow loadingIntegrated into Apache through modules

Loads mod_php.soModifies some directive in httpd.conf for identifying PHP scripts from HTML files

PHP ProgrammingPlease consult any PHP book (very easy)

Apache + SSLSSL = Secure Socket LayerAn encrypted channel for web content transferYou needs the SSL libraries and modules

Apache + SSLConfiguration:

Load SSL module (mod_ssl.so)Configure Apache to tell how, when and where to use SSL

Log filesLocated at /var/log/httpd/*Log for:

AccessErrorSecure accessProgram statusetc.

More informationMain portal of Apache: http://www.apache.org/

Conclusion

ConclusionLearning Linux = Learning *nixLearning Linux = Read tons of documentsLearning Linux = Learn to search things on InternetLearning Linux = FunLearning Linux = Get addict

Thank you very much