Ecw course

99
Last updated 16/03/2010 21:37 A Guide to Computer Ports Universal Serial Bus (or USB) Port Original Universal Serial Bus Logo The basic USB logo The SuperSpeed USB Logo The USB 3.0 Icon The USB 3.0 Icon A universal serial bus port, introduced around 1997, is the gateway to your computer. It s used to connect all kinds of external devices, such as external hard drives, printers, mice, scanners and more. There are normally two half-inch long USB ports on the back of computers built since 1998. Sometimes there are USB ports built into a hatch on the front of a computer. If you use a USB hub, you can connect as many as 127 devices to a USB port. It can transfer data to a speed of 12 megabits per second, but those 127 devices have to share that speed. Since USB-compliant devices can draw power from a USB port only a few power drawing devices can connect at the same time without the computer system complaining. In 2003, USB 2.0 connectors were introduced on computers. These transfer data at 480 Mbps. Older USB devices work with USB 2.0 ports, but at 12 Mbps. USB 2.0 devices also work with older USB ports, again at the lower speed. USB 3.0 On September 18, 2007, Pat Gelsinger demonstrated USB 3.0 at the Intel Developer Forum. The USB 3.0 Promoter Group announced on November 17, 2008, that version 3.0 of the specification had been completed and was transitioned to the USB Implementers Forum (USB-IF), the managing body of USB specifications. This move effectively opened the spec to hardware developers for implementation in future products. The first certified USB 3.0 consumer products were announced January 5, 2010, at the Las Vegas Consumer Electronics Show (CES), including two motherboards, by ASUS and Gigabyte Technology

Transcript of Ecw course

Page 1: Ecw course

Last updated 16/03/2010 21:37

A Guide to Computer Ports Universal Serial Bus (or USB) Port

Original Universal

Serial Bus Logo The basic USB

logo The SuperSpeed USB

Logo The USB 3.0 Icon The USB 3.0 Icon

A universal serial bus port, introduced around 1997, is the gateway to your computer. It s used to connect all kinds of external devices, such as external hard drives, printers, mice, scanners and more. There are normally two half-inch long USB ports on the back of computers built since 1998. Sometimes there are USB ports built into a hatch on the front of a computer. If you use a USB hub, you can connect as many as 127 devices to a USB port. It can transfer data to a speed of 12 megabits per second, but those 127 devices have to share that speed. Since USB-compliant devices can draw power from a USB port only a few power drawing devices can connect at the same time without the computer system complaining. In 2003, USB 2.0 connectors were introduced on computers. These transfer data at 480 Mbps. Older USB devices work with USB 2.0 ports, but at 12 Mbps. USB 2.0 devices also work with older USB ports, again at the lower speed.

USB 3.0 On September 18, 2007, Pat Gelsinger demonstrated USB 3.0 at the Intel Developer Forum. The USB 3.0 Promoter Group announced on November 17, 2008, that version 3.0 of the specification had been completed and was transitioned to the USB Implementers Forum (USB-IF), the managing body of USB specifications. This move effectively opened the spec to hardware developers for implementation in future products. The first certified USB 3.0 consumer products were announced January 5, 2010, at the Las Vegas Consumer Electronics Show (CES), including two motherboards, by ASUS and Gigabyte Technology

Page 2: Ecw course

Last updated 16/03/2010 21:37

Video DB15 Port - a video port for your monitor

This connector is used to attach a computer display monitor to a computer s video card. The connector has 15 holes. It sort of looks like a serial port connector, however that port has pins not holes in it.

Power Connector - for your power plug

This three-pronged plug looks like a recessed power plug. It connects to the computer s power cable that plugs into a power bar or wall socket.

Optical Audio (Used by the TOSLINK Cable)

This is an optical (not electrical) cable to connect your compuer to a set of high-end speakers. The digital format is S/PDIF, which in the PC world is often sent over a regular electrical cable (usually with an RCA phono plug). The geeky advantage of the optical cable (note the red glow) is that it s totally immune to electromagnetic interference--long speaker wires can act as an antenna, picking up the stray 60hz hum that pervades the universe. My powered speaker cables would actually pick up CB radio, so they d occasionally spit out little snatches of conversation as truckers would go by. It happened rarely enough that I d begun to doubt my own sanity before my wife figured out what was going on.

TOSLINK (connects to the Optical Audio Port)

TOSLINK or Optical Cable is a standardized optical fibre connection system. Its most common use is in consumer audio equipment (via a digital optical socket), where it carries a digital audio stream between

components such as MiniDisc and CD players and DAT recorders. Although TOSLINK supports several different media formats and physical standards, digital audio connections using the rectangular EIAJ/JEITA RC-5720 (also CP-1201 and JIS C5974-1993 F05) connector are by far the most common.

Page 3: Ecw course

Last updated 16/03/2010 21:37

Coaxial Digital (S/PDIF)

S/PDIF is a Data Link Layer protocol and a set of Physical Layer specifications for carrying digital audio signals between devices and stereo components over either optical or electrical cable. The name stands for Sony/Philips Digital Interconnect Format (more commonly known as Sony Philips Digital InterFace), Sony and Philips being the primary designers of S/PDIF. S/PDIF is standardized in IEC 60958 where it is known as IEC 60958 type II. S/PDIF is essentially a minor modification of the original AES/EBU standard, for consumer use, providing small differences in the protocol and requiring less-expensive hardware.

Sound card colour code:

Colour Connector

Lime Green Line-Out, Front Speakers, Headphones

Pink Microphone

Light Blue Stereo Line In

Orange Subwoofer and Center out

Black Rear Surround Speakers for 5.1 and 7.1 systems

Gray Middle Surround Speakers for 7.1 systems

Gold Midi / Game port (Joystick)

Note: The number of jack connectors you ll find on your soundcard will depend on how many audio channels it has:

Stereo cards with just two audio channels will have only the green (output), blue (input) and pink (microphone) jacks.

A few sound cards with 8 (7.1) audio channels do not provide the gray (Middle Surround Speakers) connector. If your computer is equipped with this type of card and you want to use all the 8 channels you will need to connect your motherboard to a 7.1 home theater system using the SPDIF digital connector.

Some motherboards with 4 or 6 channels don t have the black (Rear Surround) and orange (Subwoofer and Center) jacks. These cards will use the blue jack for both line in and rear surround speakers out, and the pink jack for both mic input and subwoofer/center out. Therefore, whenever you want to use any of these jacks for a different function, you will have to manually remove one jack connector and plug in another.

Page 4: Ecw course

Last updated 16/03/2010 21:37

HDMI Port

HDMI (High-Definition Multimedia Interface) is a compact audio/video interface for transmitting uncompressed digital data. It represents a digital alternative to consumer analogue standards, such as radio frequency (RF) coaxial cable, composite video, S-Video, SCART, component video, D-Terminal, or VGA. HDMI connects digital audio/video sources - such as set-top boxes, up convert DVD players, HD DVD players, Blu-ray Disc players, personal computers (PCs), video game consoles such as the PlayStation 3 and Xbox 360, and AV receivers - to compatible digital audio devices, computer monitors, and digital televisions.[

DVI Port

DVI stands for (D)igital (V)ideo (I)nterface. DVI is a new form of video interface technology made to maximize the quality of flat panel LCD monitors and high-end video graphics cards. It is a replacement for the P&D Plug & Display standard, and a step up from the digital-only DFP format for older flat panels. DVI is becoming increasingly popular with video card manufacturers, and most cards purchased include both a VGA and a DVI output port. More here

Page 5: Ecw course

Last updated 16/03/2010 21:37

S-VHS

S-VHS (Super VHS) is an improved version of the VHS standard for consumer video cassette recorders. It is used to connect to a TV / Monitor.

Ethernet or Network Port - connect to a network and high speed Internet

Above, an Ethernet port with network cable not plugged in. Below is an Ethernet port with plug inserted.

For faster Internet connections and for networking, an Ethernet or network port is used. This looks like an oversized North American telephone jack. The port is used to connect network cabling to a computer. Cable plugged into this port can lead either to a network hub (a junction box that can wire lots of network cables together), directly to a cable modem or DSL modem (both used for high speed Internet) or to an Internet gateway which shares a fast Internet connection between computers. Most newer computers have one of these ports. They can either be built-in to or appear on the exposed part of an Ethernet PCI card, which inserts into a slot inside the computer. Data moves through them at speeds of either 10 megabits or 100 megabits or 1 gigabit (1,000 megabits) depending on what speed the network card in the computer supports. Little monitor lights on these devices flicker when in use. The ACT light flickers when data is moving through the network to or from the port. The 10 or 100 lights relate to data speed. 10 means data is moving across the network at 10 Megabits per second. 100 means the network is moving data at 100 megbits per second.

Page 6: Ecw course

Last updated 16/03/2010 21:37

SATA

The serial ATA or SATA computer bus, is a storage-interface for connecting host bus adapters to mass storage devices such as hard disk drives and optical drives. The SATA host adapter is integrated into almost all modern consumer laptop computers and desktop motherboards.

Serial ATA was designed to replace the older ATA (AT Attachment) standard (also known as EIDE). It is able to use the same low level commands, but serial ATA host-adapters and devices communicate via a high-speed serial cable over two pairs of conductors. In contrast, the parallel ATA (the redesignation for the legacy ATA specifications) used 16 data conductors each operating at a much lower speed.

SATA offers several compelling advantages over the older parallel ATA (PATA) interface: reduced cable-bulk and cost (reduced from 80 wires to seven), faster and more efficient data transfer, and hot swapping.

As of 2009, SATA has mostly replaced parallel ATA in all shipping consumer PCs. PATA remains in industrial and embedded applications dependent on CompactFlash storage although the new CFast storage standard will be based on SATA

IEEE 1394 or Firewire Port - fast camcorder connector

This port is used to transfer large amounts of data very quickly. Usually camcorders and other video equipment use this port to get data onto a computer. Data can move across the port at up to 400 megabits per second. Apple invented this technology and had branded it Firewire. It was also adopted as an industry standard and is called IEEE 1394 on non-Apple computers. Other companies call it i.link and Lynx. Creative Labs which incorporated it into their SoundBlaster Audigy Platinium products call it SB 1394. IEEE 1394 connectors can be used to connect up to 63 external devices to a machine. TOP: A 6-Pin FireWire 400 connector Middle: A 4-Pin FireWire 400 connector. This connector is not powered. Bottom: A 9-Pin FireWire 800 connector

Page 7: Ecw course

Last updated 16/03/2010 21:37

Modem

Connects a PC s modem to the telephone network. This is an ordinary phone jack, like you d find in any telephone.

Serial Port - for external modems and old computer mice

A serial port is used to connect external modems or an older computer mouse to the computer. It comes in two versions a 9-pin version or a 25-pin model. The 9-pin is found on most newer computers. Data travels over a serial port at 115 kilobits per second.

Parallel Port - connector for scanners and printers

A parallel port is used to connect external devices such as scanners and printers. The 25-pin port is sometimes it is called a printer port. It s also known by the gruesome named: IEEE 1284-compliant Centronics port. The port is sometimes also called more simply a printer port. There are two variants for this type of interface. The ports look exactly like the traditional parallel port but are called ECP (Extend Capabilities Port) and EPP (Enhanced Parallel Port). These interfaces are ten times faster than the older printer port and can support two-way data so that computers can ask for information from a printer as well as send it.

PS/2 Port - keyboard and mouse interface

A PS/2 port, sometimes called a mouse port, was developed by IBM. It is used to connect a computer mouse or keyboard. Most computers come with two PS/2 ports. Sometimes webcams piggyback on the ports in conjunction with a parallel port. Sometimes it is not necessary to use a mouse port, as some keyboards and mice can be used with a USB port.

Page 8: Ecw course

Last updated 16/03/2010 21:37

AT Keyboard Port

Connect a PC to an older keyboard. If you don t plug in a keyboard here, you get the famous BIOS boot error: Keyboard not found. Press F1 to continue. This giant port is a holdover from the ancient IBM PC AT. It s apparently physically the same connector found on MIDI synthesizers and instruments, although it s electrically totally different.

Gameport

Connect a PC to a joystick (or two). This port is now mostly replaced by USB. This DB-15 connector has several (extremely primitive) analogue inputs and a small number of digital inputs and outputs. Because the MIDI (Musical Instrument Digital Interface) standard scavenged two pins from this port, the port is almost always located on the sound card. Apparently people that use MIDI normally have some sort of big ugly dongle that extracts MIDI signals from their joystick port.

SCSI

Short for Small Computer System Interface, SCSI pronounced as Scuzzy is the second most commonly used interface for disk

drives. Unlike competing standards SCSI is capable of supporting eight devices or sixteen devices with Wide SCSI. SCSI-1 is the original SCSI standard developed back in 1986 as ANSI X3.131-1986. SCSI-1 is capable of transferring up to eight bits a second SCSI-2 approved in 1990 SCSI-2 added new features such as Fast and Wide SCSI, support for additional devices, SCSI-3 was approved in 1996 as ANSI X3.270-1996 SCSI is a standard for parallel interface that transfers information at rate of eight bits per second and faster which is faster than the average parallel interface. SCSI-2 and above supports up to seven peripheral devices , such as a hard drive, CD-ROM, and scanner can attach to a single SCSI port on a system s bus. SCSI ports were designed for Apple Macintosh and Unix computers, but also can be used with PCs.

http://www.cablestogo.com/resources/connector_guide.asp?

Page 9: Ecw course

RJ45 Cable Wiring: T-568-B Straight-through & Crossover RJ-45 cabling

RJ-45 conductor data cable contains 4 pairs of wires each consists of a solid colored wire and a strip of the same color. There are two wiring standards for RJ-45 wiring: T-568A and T-568B. Although there are 4 pairs of wires, 10BaseT/100BaseT Ethernet uses only 2 pairs: Orange and Green. The other two colors (blue and brown) may be used for a second Ethernet line or for phone connections. The two wiring standards are used to create a cross-over cable (T-568A on one end, and T-568B on the other end), or a straight-through cable (T-568B or T-568A on both ends).

To create a straight-through cable, you'll have to use either T-568A or T-568B on both ends of the cable. The diagram depicted on the left and right shows clip of the RJ-45 connector down.

To create a cross-over cable, you'll wire T-568A on one end and T-568B on the other end of the cable.

The straight-through cables are used when connecting Data Terminating Equipment (DTE) to Data Communications Equipment (DCE), such as computers and routers to modems (gateways) or hubs (Ethernet Switches). The cross-over cables are used when connecting DTE to DTE, or DCE to DCE equipment; such as computer to computer, computer to router; or gateway to hub connections. The DTE equipment terminates the signal, while DCE equipment do not.

More on straight-through and cross-over connections The RJ45 data cables we use to connect computers to a Ethernet switch is straight-through cables. As noted above, the RJ45 cable uses only 2-pairs of wires: Orange (pins 1 & 2) and Green (pins 3 & 6). Pins 4, 5 (Blue) and 7, 8 (Brown) are NOT used. Straight-through cable, as its name suggests, connects pin 1 to pin 1, pin 2 to pin 2, pin 3 to pin 3, and pin 6 to pin 6. Cross-over cables are used to connect TX+ to RX+, and TX- to RX-, which connects pin 1 to pin 3, pin 2 to pin 6, pin 3 to pin 1 and pin 6 to pin 2. The unused pins are generally connected straight-through in both straight-through and cross-over cables.

To network two computers without a hub, a cross-over cable is used. Cross-over cable is also used to connect a router to a computer, or ethernet switch (hub) to another ethernet switch without an uplink. Most ethernet switches today provide an uplink port, which prevents a use of cross-over cable to daisy chain another ethernet switch. Straight-through cables are used to connect a computer to an ethernet switch, or a router to an ethernet switch.

Page 10: Ecw course

Pin Number Designations There are pin number designations for each color in T-568B and T-568A.

T-568B T-568A -------------------------- ------------------------ Pin Color Pin Name Color Pin Name --- ------------- -------- ------------- -------- 1 Orange Stripe Tx+ Green Stripe Rx+ 2 Orange Tx- Green Rx- 3 Green Stripe Rx+ Orange Stripe Tx+ 4 Blue Not Used Blue Not Used 5 Blue Stripe Not Used Blue Stripe Not Used 6 Green Rx- Orange Tx- 7 Brown Stripe Not Used Brown Stripe Not Used 8 Brown Not Used Brown Not Used

RJ45 Color-Coded Scheme RJ45 cables have 8 color-coded wires, and the plugs have 8 pins and conductors. Eight wires are used as 4 pairs, each representing positive and negative polarity. The most commonly used wiring standard for 100baseT is T-586B stanrard described above. Prior to EIA 568A and 568B standards, the color-coded scheme was used to wire RJ45 cables. The table below depicts pin and color schemes used in traditional and standardized setup.

Pin Colored Scheme T-568B (Common) T-568A 1 Blue Orange Stripe Green Stripe 2 Orange Orange Green 3 Black Green Stripe Orange Stripe 4 Red Blue Blue

5 Green Blue Stripe Blue Stripe 6 Yellow Green Orange 7 Brown Brown Stripe Brown Stripe 8 White (or Grey) Brown Brown

RJ-45 Wiring FAQ 1. What are T-568A and T-568B wiring standards, and how are they different? T-568A and T-568B are the two wiring standards for RJ-45 connector data cable specified by TIA/EIA-568-A wiring standards document. The difference between the two is the position of the orange and green wire pairs. It is preferable to wire to T-568B standards if there is no pre-existing pattern used within a building.

Page 11: Ecw course

2. What is RJ stands for? RJ stands for Registered Jacks. These are used in telephone and data jack wiring registered with FCC. RJ-11 is a 6-position, 4-conductor jack used in telephone wiring, and RJ-45 is a 8-position, 8-conductor jack used in 10BaseT and 100BaseT ethernet wiring.

3. What is the Category Rating System? Electronic Industries Association (EIA) developed the TIA/EIA-568-A standard, which specifies wiring and performance standards for Unshielded Twisted Pair (UTP) cabling. Category Rating System specifies the definition of performance categories for 100 ohm UTP cabling system.

Category 3 specifies the twisted pair cable and connecting hardware that can support transmission frequency up to 16MHz, and data rates up to 10Mbps. This is primarily used in telephone wiring.

Category 4 specifies cables and connectors that supports up to 20MHz and data rates up to 16Mbps. With introduction of category 5, this is a rarely used category.

Category 5 specifies cables and connectors that supports up to 100MHz and data rates up to 100Mbps. With 100BaseT Ethernet today, Category 5 is a widely used cabling system that matches todays high-speed data requirements.

Category TIA/EIA Standard Description Cat 1 None POTS, ISDN and doorbell wiring Cat 2 None 4 Mbps token ring networks Cat 3 TIA/EIA 568-B 10 Mbps Ethernet - frequency up to 16MHz Cat 4 None 16 Mbps token ring networks - frequency up to 20MHz

Cat 5 None 100 Mbps Ethernet - frequency up to 100 MHz Not suitable for GigE (1000BaseT)

Cat 5e TIA/EIA 568-B 100 Mbps & GigE Ethernet - frequency up to 100 MHz

Cat 6 TIA/EIA 568-B 2x Performance of Cat 5 & 5e - frequency up to 250 MHz

Cat 6a None Future specification for 10Gbps application

Cat 7 ISO/IEC 11801 Class F

Designed for transmission at frequencies up to 600 MHz

4. What is UTP Cable? UTP stands for Unshielded Twisted Pair. It is the cabling system with one or more pairs of twisted insulated copper wires contained in a single sheath. It is the most widely used cabling system in telecommunications and data communications environment today.

Page 12: Ecw course

What is the difference between Cross Cable and Straight Cable

Now days, LAN card has intelligence, so that both cables can work.

They have a feature on lots of switches and hubs etc called "auto-mdix" or

cable you use, it will just auto detect the proper connection type no matter which cable you use.

The cable can be categorized as Cat 5, Cat 5e, and Cat 6 UTP cable. Cat 5 UTP cable can support 10/100 Mbps Ethernet network, whereas Cat 5e and Cat 6 UTP cable can support Ethernet network running at 10/100/1000 Mbps. You might hear about Cat 3 UTP cable, it's not popular anymore since it can only support 10 Mbps Ethernet network.

Straight and crossover cable can be Cat3, Cat 5, Cat 5e or Cat 6 UTP cable, the only difference is each type will have different wire arrangement in the cable for serving different purposes.

Ethernet network cables are straight and crossover cable. This Ethernet network cable is made of 4 pair high performance cable that consists of twisted pair conductors that used for data transmission. Both end of cable is called RJ45 connector.

There are two types of network cables commonly used in PC networks - Straight-through and cross-over.

Straight Cable

Usually use straight cable to connect different type of devices. This type of cable will be used most of the time and can be used to:

1) Connect a computer to a switch/hub's normal port.

2) Connect a computer to a cable/DSL modem's LAN port.

3) Connect a router's WAN port to a cable/DSL modem's LAN port.

4) Connect a router's LAN port to a switch/hub's uplink port. (Normally used

Page 13: Ecw course

for expanding network)

5) Connect two switches/hubs with one of the switch/hub using an uplink port and the other one using normal port.

If you need to check how straight cable looks like, it's easy. Both sides (side A and side B) of cable have wire arrangement with same color.

Crossover Cable

Sometimes you will use crossover cable, it's usually used to connect same type of devices. A crossover cable can be used to:

1) Connect two computers directly.

2) Connect a router's LAN port to a switch/hub's normal port. (Normally used for expanding network)

3) Connect two switches/hubs by using normal port in both switches/hubs.

In you need to check how crossover cable looks like, both side (side A and side B) of cable have wire arrangement with following different color.

This cable (either straight cable or cross cable) has total 8 wires (or we can say lines), i.e. four twisted pairs (4x2=8) with different color codes. Right

the cable (but there is a standard).

In straight cable connectivity is like as follows

RJ451 Connected to RJ452

Pin1------------------------------------- Pin1

Pin2------------------------------------- Pin2

Pin3------------------------------------- Pin3

Pin4------------------------------------- Pin4

Page 14: Ecw course

Pin5------------------------------------- Pin5

Pin6------------------------------------- Pin6

Pin7------------------------------------- Pin7

Pin8------------------------------------- Pin8

In cross cable connectivity is like as follows

RJ451 Connected to RJ452

Pin1------------------------------------- Pin3

Pin2------------------------------------- Pin6

Pin3------------------------------------- Pin1

Pin4------------------------------------- Pin4

Pin5------------------------------------- Pin5

Pin6------------------------------------- Pin2

Pin7------------------------------------- Pin7

Pin8------------------------------------- Pin8

Purpose of this cross cable is RX (receiving terminal) connects to TX (transmitting) of one pc to another PC and vice versa.

As we use two PCs (same devices), straight cable will connect TX to TX and RX to RX of two computers, so cross cable is required. If you use HUB or switch, then straight cable will work because it has internal arrangement like cross cable. So note that use cross cable to connect two similar devices.

A straight cable will not work to connect two computers together.

Page 15: Ecw course

Crossover used to connect to PCs directly together, also used for connecting networking devices together like Switch to Switch etc.

Straight cables connect two DIFFERENT types of devices. Whereas crossover cables connect two of the SAME type

Now do this (if possible): connect cross cable between switch and PC and see what happens..!

Page 16: Ecw course

Hub Switch Router Workstation Hub Crossover Crossover Straight Straight Switch Crossover Crossover Straight Straight Router Straight Straight Crossover Crossover Workstation Straight Straight Crossover Crossover

Page 17: Ecw course

-----------------------------------------------------------------------------------------------

Communication between Switches and Workstations

When a workstation connects to a LAN, it transmits data independently of the other devices connected to the LAN media. The workstation simply transmits data frames from a NIC to the network medium.

If desired, the workstation can be attached directly to another workstation by using a crossover cable. Crossover cables connect the following devices:

Workstation to workstation Switch to switch Switch to hub Hub to hub Router to router Router to PC

Straight-through cables connect the following devices:

Switch to router Switch to workstation or server Hub to workstation or server

Many modern switches now automatically adjust the port pinout to support the particular cable attached, whether it is a crossover or straight-through cable.

Switches, which are Layer 2 devices, use intelligence to learn the MAC addresses of the devices that are attached to its ports. This data is entered into a switching table. After the table is complete, the switch can read the destination MAC address of an incoming data frame on a port and immediately forward it. Until a device transmits, the switch does not know its MAC address.

Switches provide significant scalability on a network. Switches are normally connected to each other by way of trunk links.

-----------------------------------------------------------------------------------------

Page 18: Ecw course

IPaddressclasses

Class 1st Octet Decimal Range

1st Octet High

Order Bits

Network/Host ID (N=Network,

H=Host)

Default Subnet Mask

Number of Networks

Hosts per Network (Usable

Addresses)

A 1 126* 0 N.H.H.H 255.0.0.0 126 (27 2) 16,777,214 (224 2)

B 128 191 10 N.N.H.H 255.255.0.0 16,382 (214

2) 65,534 (216 2)

C 192 223 110 N.N.N.H 255.255.255.0 2,097,150 (221 2)

254 (28 2)

D 224 239 1110 Reserved for Multicasting

E 240 254 1111 Experimental; used for research

Note: Class A addresses 127.0.0.0 to 127.255.255.255 cannot be used and is reserved for loopback and diagnostic functions.

PrivateIPAddressesClass Private Networks Subnet Mask Address Range

A 10.0.0.0 255.0.0.0 10.0.0.0 - 10.255.255.255

B 172.16.0.0 - 172.31.0.0 255.240.0.0 172.16.0.0 - 172.31.255.255

C 192.168.0.0 255.255.0.0 192.168.0.0 - 192.168.255.255

Page 19: Ecw course

Objective 3.1: Install, configure, and differentiate between common network devices

Network switches

Computer networking devices are units that mediate data in a computer network and are also called network equipment. Units which are the last receiver or generate data are called hosts or data terminal equipment.

Hub

Hubs connect computers together in a star topology network. Due to their design, they increase the chances for collisions. Hubs operate in the physical layer of the OSI model and have no intelligence. Hubs flood incoming packets to all ports all the time. For this reason, if a network is connected using hubs, the chances of a collision increases linearly with the number of computers (assuming equal bandwidth use). Hubs pose a security risk since all packets are flooded to all ports all the time. If a user has packet sniffing software, they can extract data from the network and potentially decode it and use it. Hubs make it easy to "spy" on users on the same LAN as you.

Repeater

A wireless repeater.

Page 20: Ecw course

A repeater is an electronic device that receives a signal and retransmits it at a higher level and/or higher power, or onto the other side of an obstruction, so that the signal can cover longer distances without degradation. Because repeaters work with the actual physical signal, and do not attempt to interpret the data being transmitted, they operate on the physical layer, the first layer of the OSI model. Repeaters are majorly employed in long distance transmission to reduce the effect of attenuation. It is important to note that repeaters do not amplify the original signal but simply regenerate it.

Modem

Modem (from modulator-demodulator) is a device that turns the digital 1s and 0s of a personal computer into sounds that can be transmitted over the telephone lines of Plain Old Telephone Systems (POTS), and once received on the other side, converts those sounds back into a form used by a USB, Ethernet, serial, or network connection. Modems are generally classified by the amount of data they can send in a given time, normally measured in bits per second, or "bps".

NIC(NetworkInterfaceCard)

A network interface card is a computer hardware component designed to allow computers to communicate over a computer network. It is both an OSI layer 1 (physical layer) and layer 2 (data link layer) device, as it provides physical access to a networking medium and provides a low-level addressing system through the use of MAC addresses. It allows users to connect to each other either by using cables or wirelessly. Most motherboards today come equipped with a network interface card in the form of a controller, with the hardware built into the board itself, eliminating the need for a standalone card.

Mediaconverters

Media converters are simple networking devices that make it possible to connect two dissimilar media types such as twisted pair with fiber optic cabling. They were introduced to the industry nearly two decades ago, and are important in interconnecting fiber optic cabling-based systems with existing copper-based, structured cabling systems. Media converters support many different data communication protocols including Ethernet, T1/E1, T3/E3, as well as multiple cabling types such as coaxial, twisted pair, multimode and single-mode fiber optics. When expanding the reach of a Local Area Network to span multiple locations, media converters are useful in connecting multiple LANs to form one large "campus area network" that spans over a limited geographic area. As local networks are primarily copper-based, media converters can extend the reach of the LAN over single-mode fiber up to 130 kilometers with 1550 nm optics.

Page 21: Ecw course

Basicswitch

Switches are often confused with bridges because they also operate at the data link layer of the OSI model. Similar to a hub, switches provide a central connection between two or more computers on a network, but with some intelligence. They provide traffic control for packets; rather than forwarding data to all the connected ports, a switch forwards data only to the port on which the destination system is connected. They use a database of MAC addresses to determine where computers are located and very efficiently send packets only where they need to go. The database is created dynamically as computers communicate on the network. The switch simply watches the incoming packets and memorizes the MAC address and port a packet arrives on. If a packet arrives with a destination computer that the switch does not have an address for in its MAC address table, it will flood the packet out all connected ports. A switch creates separate collision domains for each physical connection. A switch will only create separate broadcast domains if separate VLANs (Virtual Local Area Networks) are assigned to different ports on the switch. Otherwise, a broadcast received on one port will be flooded out all ports except the one it came in on.

Bridge

Bridges can be identified by the fact that they operate at the data link layer of the OSI model. Bridges have intelligence and can "bridge" two of their ports together at very high speed. They use a database of MAC addresses to determine where computers are located and very efficiently send frames only where they need to go. The database is created dynamically as computers communicate on the network. A bridge simply watches the incoming frame and memorizes the MAC address and port a frame arrives on. It uses this information to locate a computer if a packet comes in that must be forwarded to it. If a frame arrives at the bridge and the bridge does not know where to send it, the bridge will flood the frame just like a hub does. Bridging is often inaccurately called switching.

Page 22: Ecw course

Wirelessaccesspoint

A wireless access point (WAP or AP) is a device that allows wireless communication devices to connect to a wireless network using Wi-Fi, Bluetooth or related standards. The WAP usually connects to a wired network, and can relay data between the wireless devices (such as computers or printers) and wired devices on the network.

A typical corporate use involves attaching several WAPs to a wired network and then providing wireless access to the office Local Area Network. Within the range of the WAPs, the wireless end user has a full network connection with the benefit of mobility. In this instance, the WAP functions as a gateway for clients to access the wired network.

A Hot Spot is a common public application of WAPs, where wireless clients can connect to the Internet without regard for the particular networks to which they have attached for the moment. The concept has become common in large cities, where a combination of coffeehouses, libraries, as well as privately owned open access points, allow clients to stay more or less continuously connected to the Internet, while moving around. A collection of connected Hot Spots can be referred to as a lily-pad network.

Home networks generally have only one WAP to connect all the computers in a home. Most are wireless routers, meaning converged devices that include a WAP, router, and often an Ethernet switch in the same device. Many also converge a broadband modem. In places where most homes have their own WAP within range of the neighbors' WAP, it's possible for technically savvy people to turn off their encryption and set up a wireless community network, creating an intra-city communication network without the need of wired networks.

Basicrouter

Page 23: Ecw course

Routers operate at the network layer of the OSI model and efficiently route information between Local Area Networks. Since routers operate in the third layer, the network layer, they must understand layer 3 addressing... such as TCP/IP. A router will divide a broadcast domain by not forwarding broadcasts on one connected network to another connected network. Routers operate in two different planes: the control plane, in which the router learns the outgoing interface that is most appropriate for forwarding specific packets to specific destinations, and the forwarding plane, which is responsible for the actual process of sending a packet received on a logical interface to an outbound logical interface.

Basicfirewall

A firewall is a part of a computer system or network that is designed to block unauthorized access while permitting outward communication. It is also a device or set of devices configured to permit, deny, encrypt, decrypt, or proxy all computer traffic between different security domains based upon a set of rules and other criteria.

Firewalls can be implemented in both hardware and software, or a combination of both. Firewalls are frequently used to prevent unauthorized Internet users from accessing private networks connected to the Internet. All messages entering or leaving the Local Area Network pass through the firewall, which examines each message and blocks those that do not meet the specified security criteria. Without proper configuration, a firewall can often become worthless. Standard security practices dictate a "default-deny" firewall ruleset, in which the only network connections which are allowed are the ones that have been explicitly allowed.

BasicDHCP(DynamicHostConfigurationProtocol)server

When a DHCP-configured client (be it a computer or any other network-aware device) connects to a network, the DHCP client sends a broadcast query requesting necessary information from a DHCP server. The DHCP server manages a pool of IP addresses and information about client configuration parameters such as the default gateway, the domain name, the DNS (Domain Name System) servers, other servers such as time servers, and so forth. Upon receipt of a valid request the server will assign the computer an IP address, a lease (the length of time for which the allocation is valid), and other IP configuration parameters, such as the subnet mask and the default gateway. The query is typically initiated immediately after booting and must be completed before the client can initiate IP-based communication with other hosts.

Page 24: Ecw course

BasicNetworkCommandsTable of Contents

13.1 ping

13.2 traceroute

13.3 DNS Tools

13.4 finger

13.5 telnet

13.6 The Secure shell

13.7 email

13.8 Browsers

13.9 FTP Clients

13.10 Talking to Other People

A network consists of several computers connected together. The network can be as simple as a few computers connected in your home or office, or as complicated as a large university network or even the entire Internet. When your computer is part of a network, you have access to those systems either directly or through services like mail and the web.

There are a variety of networking programs that you can use. Some are handy for performing diagnostics to see if everything is working properly. Others (like mail readers and web browsers) are useful for getting your work done and staying in contact with other people.

1pingping(8) sends an ICMP ECHO_REQUEST packet to the specified host. If the host responds,

machine is alive. If there is no response, you know something is wrong. Here is an example conversation between two Linux users:

User A: Loki's down again. User B: Are you sure? User A: Yeah, I tried pinging it, but there's no response.

It's instances like these that make ping a very useful day-to-day command. It provides a very quick way to see if a machine is up and connected to the network. The basic syntax is:

Page 25: Ecw course

% ping www.slackware.com

There are, of course, several options that can be specified. Check the ping(1) man page for more information.

2tracerouteSlackware's traceroute(8) command is a very useful network diagnostic tool. traceroute displays each host that a packet travels through as it tries to reach its destination. You can see

om the Slackware web site you are with this command:

% traceroute www.slackware.com

Each host will be displayed, along with the response times at each host. Here is an example output:

% traceroute www.slackware.com traceroute to www.slackware.com (204.216.27.13), 30 hops max, 40 byte packets 1 zuul.tdn (192.168.1.1) 0.409 ms 1.032 ms 0.303 ms 2 207.171.227.254 (207.171.227.254) 18.218 ms 32.873 ms 32.433 ms 3 border-sf-2-0-4.sirius.com (205.134.230.254) 15.662 ms 15.731 ms 16.142 ms 4 pb-nap.crl.net (198.32.128.20) 20.741 ms 23.672 ms 21.378 ms 5 E0-CRL-SFO-03-E0X0.US.CRL.NET (165.113.55.3) 22.293 ms 21.532 ms 21.29 ms 6 T1-CDROM-00-EX.US.CRL.NET (165.113.118.2) 24.544 ms 42.955 ms 58.443 ms 7 www.slackware.com (204.216.27.13) 38.115 ms 53.033 ms 48.328 ms

DNSToolsDomain Name Service (DNS for short) is that magical protocol that allows your computer to turn meaningless domain names like www.slackware.com into meaningful IP address like 64.57.102.34. Computers can't route packets to www.slackware.com, but they can route packets to that domain name's IP address. This gives us a convenient way to remember machines. Without DNS we'd have to keep a mental database of just what IP address belongs to what computer, and that's assuming the IP address doesn't change. Clearly using names for computers is better, but how do we map names to IP addresses?

Page 26: Ecw course

13.3.1host

host(1) can do this for us. host is used to map names to IP addresses. It is a very quick and simple utility without a lot of functions.

% host www.slackware.com www.slackware.com is an alias for slackware.com. slackware.com has address 64.57.102.34

But let's say for some reason we want to map an IP address to a domain name; what then?

13.3.2nslookup

nslookup is a tried and true program that has weathered the ages. nslookup has been deprecated and may be removed from future releases. There is not even a man page for this program.

% nslookup 64.57.102.34 Note: nslookup is deprecated and may be removed from future releases. Consider using the `dig' or `host' programs instead. Run nslookup with the `-sil[ent]' option to prevent this message from appearing. Server: 192.168.1.254 Address: 192.168.1.254#53 Non-authoritative answer: www.slackware.com canonical name = slackware.com. Name: slackware.com Address: 64.57.102.34

13.3.3dig

The meanest dog in the pound, the domain information groper, dig(1) for short, is the go-to program for finding DNS information. dig can grab just about anything from a DNS server including reverse lookups, A, CNAME, MX, SP, and TXT records. dig has many command line options and if you're not familiar with it you should read through it's extensive man page.

% dig @192.168.1.254 www.slackware.com mx ; <<>> DiG 9.2.2 <<>> @192.168.1.254 www.slackware.com mx ;; global options: printcmd ;; Got answer: ;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 26362 ;; flags: qr rd ra; QUERY: 1, ANSWER: 2, AUTHORITY: 2, ADDITIONAL: 2 ;; QUESTION SECTION: ;www.slackware.com. IN MX ;; ANSWER SECTION: www.slackware.com. 76634 IN CNAME slackware.com. slackware.com. 86400 IN MX 1 mail.slackware.com. ;; AUTHORITY SECTION: slackware.com. 86400 IN NS ns1.cwo.com. slackware.com. 86400 IN NS ns2.cwo.com.

Page 27: Ecw course

;; ADDITIONAL SECTION: ns1.cwo.com. 163033 IN A 64.57.100.2 ns2.cwo.com. 163033 IN A 64.57.100.3 ;; Query time: 149 msec ;; SERVER: 192.168.1.254#53(192.168.1.254) ;; WHEN: Sat Nov 6 16:59:31 2004 ;; MSG SIZE rcvd: 159

This should give you an idea how dig works.

the type of lookup I am performing. The above query tells me that e-mail to www.slackware.com will instead be sent to mail.slackware.com for delivery.

4fingerfinger(1) will retrieve information about the specified user. You give finger a username or an email address and it will try to contact the necessary server and retrieve the username, office, telephone number, and other pieces of information. Here is an example:

% finger [email protected]

finger finger server.

The one included with Slackware returns the following information by default:

Username Room number Home phone number Work phone number Login status Email status Contents of the .plan file in the user's home directory Contents of the .project file in the user's home directory

The first four items can be set with the chfn command. It stores those values in the /etc/passwd file. To change the information in your .plan or .project file, just edit them with your favorite text editor. They must reside in your home directory and must be called .plan and .project.

Many users finger their own account from a remote machine to quickly see if they have new email. Or, you can see a user's plan or current project.

Page 28: Ecw course

5telnetSomeone once stated that telnet(1) was the coolest thing he had ever seen on computers. The ability to remotely log in and do stuff on another computer is what separates Unix and Unix-like operating systems from other operating systems.

telnet allows you to log in to a computer, just as if you were sitting at the terminal. Once your username and password are verified, you are given a shell prompt. From here, you can do anything requiring a text console. Compose email, read newsgroups, move files around, and so on. If you are running X and you telnet to another machine, you can run X programs on the remote computer and display them on yours.

To login to a remote machine, use this syntax:

% telnet <hostname>

If the host responds, you will receive a login prompt. Give it your username and password. That's it. You are now at a shell. To quit your telnet session, use either the exit command or the logout command.

telnet does not encrypt the information it sends. Everything is sent in plain text, even passwords. It is not advisable to use telnet over the Internet. Instead, consider the Secure Shell. It encrypts all traffic and is available for free.

13.5.1Theotheruseoftelnet

Now that we have convinced you not to use the telnet protocol anymore to log into a remote machine, we'll show you a couple of useful ways to use telnet.

You can also use the telnet command to connect to a host on a certain port.

% telnet <hostname> [port]

This can be quite handy when you quickly need to test a certain service, and you need full control over the commands, and you need to see what exactly is going on. You can interactively test or use an SMTP server, a POP3 server, an HTTP server, etc. this way.

In the next figure you'll see how you can telnet to a HTTP server on port 80, and get some basic information from it.

Figure 13-1. Telnetting to a webserver

% telnet store.slackware.com 80 Trying 69.50.233.153... Connected to store.slackware.com. Escape character is '^]'. HEAD / HTTP/1.0

Page 29: Ecw course

HTTP/1.1 200 OK Date: Mon, 25 Apr 2005 20:47:01 GMT Server: Apache/1.3.33 (Unix) mod_ssl/2.8.22 OpenSSL/0.9.7d Last-Modified: Fri, 18 Apr 2003 10:58:54 GMT ETag: "193424-c0-3e9fda6e" Accept-Ranges: bytes Content-Length: 192 Connection: close Content-Type: text/html Connection closed by foreign host. %

You can do the same for other plain-text protocols, as long as you know what port to connect to, and what the commands are.

6TheSecureshellToday, secure shell basks in the adoration that telnet once enjoyed. ssh(1) allows one to make a connection to a remote machine and execute programs as if one were physically present; however, ssh encrypts all the data travelling between the two computers so even if others intercept the conversation, they are unable to understand it. A typical secure shell connection follows.

% ssh carrier.lizella.net -l alan The authenticity of host 'carrier.lizella.net (192.168.1.253)' can't be established. RSA key fingerprint is 0b:e2:5d:43:4c:39:4f:8c:b9:85:db:b2:fa:25:e9:9d. Are you sure you want to continue connecting (yes/no)? yes Warning: Permanently added 'carrier.lizella.net' (RSA) to the list of known hosts. Password: password Last login: Sat Nov 6 16:32:19 2004 from 192.168.1.102 Linux 2.4.26-smp. alan@carrier:~$ ls -l MANIFEST -rw-r--r-- 1 alan users 23545276 2004-10-28 20:04 MANIFEST alan@carrier:~$ exit logout Connection to carrier.lizella.net closed.

There you see me making an ssh connection to carrier.lizella.net, and checking the permissions on the MANIFEST file.

7emailElectronic mail is one of the most popular things one can do on the Internet. In 1998, it was reported that more electronic mail was sent than regular mail. It is indeed common and useful.

Page 30: Ecw course

Under Slackware, we provide a standard mail server, and several mail clients. All of the clients discussed below are text-based. A lot of Windows users may be against this, but you will find that a text based client is very convenient, especially when checking mail remotely. Fear not, there are many graphical e-mail clients such as KDE's Kmail. If you wish to use one of those check its help menu.

13.7.1pine

pine(1) is not elm. Or so the saying goes. The University of Washington created their program for Internet news and email out of a need for an easy mail reader for their students. pine is one of the most popular email clients in use today and is available for nearly every flavor of Unix and even Windows.

Figure 13-2. The Pine main menu

You will see a menu of commands and a row of command keys at the bottom. pine is indeed a complex program, so we will not discuss every feature about it here.

To see what's in your inbox, type i. Your messages are listed with their date, author, and subject. Highlight the message you want and press enter to view it. Pressing r will start a reply to the message. Once you have written the response, type Ctrl+X to send it. You can press i to get back to the message listing.

If you want to delete a message, press d. It will mark the highlighted message for deletion. pine deletes the mail when you exit the program. pine also lets you store your mail in folders. You can get a listing of folders by pressing l. At the message listing, press s to save it to another folder. It will ask for the folder name to write the message to.

Page 31: Ecw course

pine offers many, many features; you should definitely have a look at the man page for more information. It will contain the latest information about the program.

13.7.2elm

elm(1) is another popular text-based email client. Though not quite as user friendly as pine, it's definitely been around a lot longer.

Figure 13-3. Elm main screen

By default, you are placed in your inbox. The messages are listed with the message number, date, sender, and subject. Use the arrow keys to highlight the message you want. Press Enter to read the message.

To compose a new message, type m at the main screen. The d key will flag a message for deletion. And the r key will reply to the current message you are reading. All of these keys are displayed at the bottom of the screen with a prompt.

The man page discusses elm in more detail, so you will probably want to consult that before using elm.

13.7.3mutt

mutt's original interface was based on elm with added features found in other popular mailclients, resulting in a hybrid mutt.

Page 32: Ecw course

Some of mutt's features include:

color support message threading MIME and PGP/MIME support pop3 and imap support support for multiple mailbox formats (mbox, MMDF, MH, maildir) highly customizable

Figure 13-4. Mutt main screen

if you're looking for a mail client that will let you be in total control over everything, then you will like mutt. all the default settings can be customized, keybindings can be changed. if you like to add a macro, you can.

you probably want to take a look at the muttrc manpage, which will tell you how to configure everything. or take a look at the included example muttrc file.

13.7.4nail

nail(1) is a command line driven mail client. It is very primitive and offers pretty much nothing in the way of user interfaces. However, mailx is handy for times when you need to quickly mail something, scripting a bulk mailer, testing your MTA installation or something similar. Note that Slackware creates symbolic links to nail at /usr/bin/mail and /usr/bin/mailx. Any of these three commands executes the same program. In fact, you will most likely see nail referred to as mail.

Page 33: Ecw course

The basic command line is:

% mailx <subject> <to-addr>

mailx reads the message body from standard input. So you can cat a file into this command to mail it, or you can just type text and hit Ctrl+D when finished with the message.

Here is an example of mailing a program source file to another person.

% cat randomfunc.c | mail -s "Here's that function" [email protected]

8Browsers

Or looking at websites using a web browser. This is probably by far the most popular use of the Internet for the average user.

options below.

13.8.1lynx

lynx(1) is a text-based web browser. It is a very quick way of looking up something on the Internet. Sometimes graphics just get in the way if you know exactly what you're after.

To start lynx, just type lynx at the prompt:

% lynx

Figure 13-5. Lynx default start page

Page 34: Ecw course

You may want to specify a site for lynx to open to:

% lynx http://www.slackware.com

lynx prints the command keys and what they do at the bottom of the screen. The up and down arrow keys move around the document, Enter selects the highlighted link, and the left arrow goes back to the previous page. Typing d will download the currently selected file. The g command brings up the Go prompt, where you can give lynx a URL to open.

There are many other commands in lynx. You can either consult the man page, or type h to get the help screen for more information.

13.8.2links

Just like lynx, links is a textmode web browser, where you do all the navigation using the keyboard. However, when you press the Esc key, it will activate a very convenient pulldown menu on the top of the screen. This makes it very easy to use, without having to learn all the keyboard shortcuts. People who do not use a text browser every day will appreciate this feature.

links seems to have better support for both frames and tables, when compared to lynx.

Figure 13-6. Links, with the file menu open

Page 35: Ecw course

13.8.3wget

wget(1) is a command line utility that will download files from a specified URL. While not an actual web-browser, wget is used primarily to grab whole or partial web sites for offline viewing, or for fast download of single files from HTTP or FTP servers instead. The basic syntax is:

% wget <url>

You can also pass options. For example, this will download the Slackware web site:

% wget --recursive http://www.slackware.com

wget will create a www.slackware.com directory and store the files in there, just as the site does.

wget can also download files from FTP sites; just specify an FTP URL instead of an HTTP one.

% wget ftp://ftp.gnu.org/gnu/wget/wget-1.8.2.tar.gz --12:18:16-- ftp://ftp.gnu.org/gnu/wget/wget-1.8.2.tar.gz => `wget-1.8.2.tar.gz' Resolving ftp.gnu.org... done. Connecting to ftp.gnu.org[199.232.41.7]:21... connected. Logging in as anonymous ... Logged in! ==> SYST ... done. ==> PWD ... done. ==> TYPE I ... done. ==> CWD /gnu/wget ... done. ==> PORT ... done. ==> RETR wget-1.8.2.tar.gz ... done.

Page 36: Ecw course

Length: 1,154,648 (unauthoritative) 100%[==================================>] 1,154,648 209.55K/s ETA 00:00 12:18:23 (209.55KB/s) - `wget-1.8.2.tar.gz' saved [1154648]

9FTPClientsFTP stands for the File Transfer Protocol. It allows you to send and receive files between two computers. There is the FTP server and the FTP client. We discuss the client in this section.

request and lets you login. You will download files from and upload files to the server. The client cannot accept FTP connections, it can only connect to servers.

13.9.1ftp

To connect to an FTP server, simply run the ftp(1) command and specify the host:

% ftp <hostname> [port]

If the host is running an FTP server, it will ask for a username and password. You can log in

For example, to get Slackware Linux via FTP, you must use anonymous FTP.

Once connected, you will be at the ftp> prompt. There are special commands for FTP, but they are similar to other standard commands. The following shows some of the basic commands and what they do:

Table 13-1. ftp commands

Command Purpose

ls List files

cd <dirname> Change directory

bin Set binary transfer mode

ascii Set ASCII transfer mode

get <filename> Download a file

Page 37: Ecw course

Command Purpose

put <filename> Upload a file

hash Toggle hash mark stats indicator

tick Toggle byte counter indicator

prom Toggle interactive mode for downloads

mget <mask> Download a file or group of files; wildcards are allowed

mput <mask> Upload a file or group of files; wildcards are allowed

quit Log off the FTP server

You can also use some of the following commands which are quite self-explanatory: chmod, delete, rename, rmdir. For a complete list of all commands and their meaning, just type help or ? and you'll see a complete listing on screen.

FTP is a fairly simple program to use, but lacks the user interface that many of us are used to nowadays. The man page discusses some of the command line options for ftp(1).

ftp> ls *.TXT 200 PORT command successful. 150 Opening ASCII mode data connection for /bin/ls. -rw-r--r-- 1 root 100 18606 Apr 6 2002 BOOTING.TXT -rw-r--r-- 1 root 100 10518 Jun 13 2002 COPYRIGHT.TXT -rw-r--r-- 1 root 100 602 Apr 6 2002 CRYPTO_NOTICE.TXT -rw-r--r-- 1 root 100 32431 Sep 29 02:56 FAQ.TXT -rw-r--r-- 1 root 100 499784 Mar 3 19:29 FILELIST.TXT -rw-r--r-- 1 root 100 241099 Mar 3 19:12 PACKAGES.TXT -rw-r--r-- 1 root 100 12339 Jun 19 2002 README81.TXT -rw-r--r-- 1 root 100 14826 Jun 17 2002 SPEAKUP_DOCS.TXT -rw-r--r-- 1 root 100 15434 Jun 17 2002 SPEAK_INSTALL.TXT -rw-r--r-- 1 root 100 2876 Jun 17 2002 UPGRADE.TXT 226 Transfer complete. ftp> tick Tick counter printing on (10240 bytes/tick increment). ftp> get README81.TXT local: README81.TXT remote: README81.TXT 200 PORT command successful. 150 Opening BINARY mode data connection for README81.TXT (12339 bytes). Bytes transferred: 12339 226 Transfer complete. 12339 bytes received in 0.208 secs (58 Kbytes/sec)

13.9.2ncftp

ncftp(1) (pronounced "Nik-F-T-P") is an alternative to the traditional ftp client that comes with Slackware. It is still a text-based program, but offers many advantages over ftp, including:

Page 38: Ecw course

Tab completion Bookmarks file More liberal wildcard uses Command history

By default, ncftp will try to log in anonymously to the server you specify. You can force ncftp -u use the same commands as in ftp, only you'll notice a nicer interface, one that works more like bash.

ncftp /pub/linux/slackware > cd slackware-current/ Please read the file README81.TXT it was last modified on Wed Jun 19 16:24:21 2002 - 258 days ago CWD command successful. ncftp ...ware/slackware-current > ls BOOTING.TXT FAQ.TXT bootdisks/ CHECKSUMS FILELIST.TXT extra/ CHECKSUMS.asc GPG-KEY isolinux/ CHECKSUMS.md5 PACKAGES.TXT kernels/ CHECKSUMS.md5.asc PRERELEASE_NOTES pasture/ COPYING README81.TXT rootdisks/ COPYRIGHT.TXT SPEEKUP_DOCS.TXT slackware/ CRYPTO_NOTICE.TXT SPEEK_INSTALL.TXT source/ CURRENT.WARNING Slackware-HOWTO ChangeLog.txt UPGRADE.TXT ncftp ...ware/slackware-current > get README81.TXT README81.TXT: 12.29 kB 307.07 kB/s

Page 39: Ecw course

Networking Basics

In the world of modern technology, the process of networking has become an essential tool for governments, businesses, and even schools to operate both efficiently and securely.

WhatisNetworking?

Networking is the practice of linking multiple computing devices together in order to share resources. These resources can be printers, CDs, files, or even electronic communications such as e-mails and instant messages. These networks can be created using several different methods, such as cables, telephone lines, satellites, radio waves, and infrared beams. Without the ability to network, businesses, government agencies, and schools would be unable to operate as efficiently as they do today. The ability for an office or school to connect dozens of computers to a single printer is a seemingly simple, yet extremely useful capability. Perhaps even more valuable is the ability to access the same data files from various computers throughout a building. This is incredibly useful for companies that may have files that require access by multiple employees daily. By utilizing networking, those same files could be made available to several employees on separate computers simultaneously, improving efficiency.

TheInsandOutsofNetworking

When it comes to networking, there are two essential pieces of equipment that enable numerous devices to be connected: routers and switches

Switches

Switches are used in order to connect many devices on the same network. These devices are generally within the same building, such as an office building or school and could consist of various computers, printers, and other gadgets. The switch acts as a controller, allowing the connected objects to share information with one another. This not only increases productivity and efficiency, but also saves money.

Routers

In addition to switches, networks generally employ routers as well. These essential tools connect different networks to each other through the internet in order to allow for data exchange between networks. Whereas the switch can be considered a controller, a router should be considered more of a dispatcher, packaging digital information and choosing the best route for it to travel. Routers can feature several other functions, including firewalls and virtual private networks (VPNs) that enhance the security of the data being sent over the internet.

NetworkTypes

There are countless types of networks available, especially as networking technologies continue to advance. Two of the most commonly employed networks are LAN and WAN.

Page 40: Ecw course

short distances, such as within a building, school, or home. LANs generally employ Ethernet cables as a means of connecting the various gadgets within the network.

distances than LANs. A WAN is established by using routers to connect various LANs and are generally not owned by a single person or organization. The internet is one massive WAN that spans the entire planet.

ncluding wireless local area networks (WLANs) that are LANs based on wireless network technology and metropolitan area networks (MANs) that cover larger areas than LANs but smaller areas than WANs. These MANs generally span a city and are owned and operated by a government or corporation.

NetworkTopology

Not to be confused with network type, network topology refers to the virtual layout of the devices within a network and can refer to five distinct categories:

devices on a network. Found in some offices and schools, ring topologies give each device two neighbors

for communication purposes. All data travels in a ring, and a failure of that ring can bring down the whole network.

objects on the network. This hub could be a router or a switch.

in order to vastly increase the number of computers able to connect to the network.

on the network has multiple paths it can take instead of one fixed route. The internet is a perfect example of this topology.

TheArtofComputerNetworking

Computer networking has become a central theme in nearly every aspect of life. From home use to business use, more and more devices are being produced that can access computer networks. Because of this fact, it is important to understand just what computer networking is.

Computer Network Definition

A computer network is a collection of computers and other devices that are able to communicate with each other and share data. These devices include computers, printers, tablets, phones, and many other electronics.

Computer Networking Essentials

Both traditional and modern forms of computer networking aim to provide users with the ability to share data amongst multiple gadgets, whether they be in the same building or across the globe. Traditional computer networking relied on Ethernet and fiber optic cables to

Page 41: Ecw course

connect various devices on a network. More modern technology has emerged that allows for wireless connections between electronics. These technologies include Wi-Fi and Bluetooth compatible devices. It is very helpful to understand the role that each of these technologies plays in computer networking.

simultaneously, such as satellites or cellular networks are considered wide area interconnects. They are generally expensive to build and run more slowly than others due to the large area and high volume of users.

support a very large amount of data and serve many clients who share common hardware.

include tools such as Bluetooth. These interconnects are highly optimized for low-cost and also low power usage. Bluetooth is used in many mobile devices, laptop computers, and speakers in order to enable the transfer of data. Popular information sent over Bluetooth includes music, phone calls, and contact information. The market for Bluetooth technology is growing at a rapid pace to include many other items such as remote controlled helicopters and cars, home security systems, and fitness gear. Because it is rather affordable for the connectivity it supplies, Bluetooth technology is finding its way into countless niches.

Page 42: Ecw course

AnoperatingSystem(OS) is an intermediary between users and computer hardware. It provides users an environment in which a user can execute programs conveniently and efficiently.

In technical terms, It is a software which manages hardware. An operating System controls the allocation of resources and services such as memory, processors, devices and information.

Definition

An operating system is a program that acts as an interface between the user and the computer hardware and controls the execution of all kinds of programs.

Following are some of important functions of an operating System.

Memory Management Processor Management Device Management File Management Security Control over system performance Job accounting Error detecting aids Coordination between other software and users

MemoryManagement

Memory management refers to management of Primary Memory or Main Memory. Main memory is a large array of words or bytes where each word or byte has its own address.

Page 43: Ecw course

Main memory provides a fast storage that can be access directly by the CPU. So for a program to be executed, it must in the main memory. Operating System does the following activities for memory management.

Keeps tracks of primary memory i.e. what part of it are in use by whom, what part are not in use.

In multiprogramming, OS decides which process will get memory when and how much.

Allocates the memory when the process requests it to do so. De-allocates the memory when the process no longer needs it or has been terminated.

ProcessorManagement

In multiprogramming environment, OS decides which process gets the processor when and how much time. This function is called process scheduling. Operating System does the following activities for processor management.

Keeps tracks of processor and status of process. Program responsible for this task is known as traffic controller.

Allocates the processor(CPU) to a process. De-allocates processor when processor is no longer required.

DeviceManagement

OS manages device communication via their respective drivers. Operating System does the following activities for device management.

Keeps tracks of all devices. Program responsible for this task is known as the I/O controller.

Decides which process gets the device when and for how much time. Allocates the device in the efficient way. De-allocates devices.

FileManagement

A file system is normally organized into directories for easy navigation and usage. These directories may contain files and other directions. Operating System does the following activities for file management.

Keeps track of information, location, uses, status etc. The collective facilities are often known as file system.

Decides who gets the resources. Allocates the resources. De-allocates the resources.

OtherImportantActivities

Following are some of the important activities that Operating System does.

Page 44: Ecw course

Security -- By means of password and similar other techniques, preventing unauthorized access to programs and data.

Control over system performance -- Recording delays between request for a service and response from the system.

Job accounting -- Keeping track of time and resources used by various jobs and users.

Error detecting aids -- Production of dumps, traces, error messages and other debugging and error detecting aids.

Coordination between other softwares and users -- Coordination and assignment of compilers, interpreters, assemblers and other software to the various users of the computer systems.

Page 45: Ecw course

What is an operating system?

An operating system is the most important software that runs on a computer. It manages the computer's memory, processes, and all of its software and hardware. It also allows you to communicate with the computer without knowing how to speak the computer's language. Without an operating system, a computer is useless.

Watch the video to learn about operating systems.

Theoperatingsystem'sjob

Your computer's operating system (OS) manages all of the software and hardware on the computer. Most of the time, there are many different computer programs running at the same time, and they all need to access your computer's central processing unit (CPU), memory, and storage. The operating system coordinates all of this to make sure each program gets what it needs.

Typesofoperatingsystems

Operating systems usually come preloaded on any computer you buy. Most people use the operating system that comes with their computer, but it's possible to upgrade or even change operating systems.

The three most common operating systems for personal computers are Microsoft Windows, Apple Mac OS X, and Linux.

Modern operating systems use a graphical user interface, or GUI (pronounced gooey). A GUI lets you use your mouse to click icons, buttons, and menus, and everything is clearly displayed on the screen using a combination of graphics and text.

Each operating system's GUI has a different look and feel, so if you switch to a different operating system it may seem unfamiliar at first. However, modern operating systems are designed to be easy to use, and most of the basic principles are the same.

Page 46: Ecw course

Before GUIs, computers had a command-line interface, which meant users had to type every single command to the computer and the computer would only display text.

Microsoft Windows

Microsoft created the Windows operating system in the mid-1980s. Over the years, there have been many different versions of Windows, but the most recent ones are Windows 8 (released in 2012), Windows 7 (2009), and Windows Vista (2007). Windows comes preloaded on most new PCs, which helps to make it the most popular operating system in the world.

If you're buying a new computer or are upgrading to a newer version of Windows, you can choose from several different editions of Windows, such as Home Premium, Professional, and Ultimate. You may need to do some research to decide which edition is right for you.

Page 47: Ecw course

Mac OS X

Mac OS is a line of operating systems created by Apple. It comes preloaded on all new Macintosh computers, or Macs. All of the recent versions are known as OS X (pronounced O-S Ten), and the specific versions include Yosemite (released in 2014), Mavericks (2013), Mountain Lion (2012), Lion (2011), and Snow Leopard (2009). Apple also offers a version called Mac OS X Server, which is designed to be run on servers.

According to StatCounter Global Stats, Mac OS X users account for 9.5% of the operating systems market as of September 2014 much lower than the percentage of Windows users (almost 90%). One reason for this is that Apple computers tend to be more expensive. However, many people prefer the look and feel of Mac OS X.

Page 48: Ecw course

Linux

Linux (pronounced LINN-ux) is a family of open-source operating systems, which means they can be modified and distributed by anyone around the world. This is different from proprietary software like Windows, which can only be modified by the company that owns it (Microsoft). The advantages of Linux are that it is free, and there are many different distributions or versions you can choose from. Each distribution has a different look and feel, and the most popular ones include Ubuntu, Mint, and Fedora.

Linux is named after Linus Torvalds, who created the Linux kernel in 1991. The kernel is the computer code that is the central part of an operating system.

According to StatCounter Global Stats, Linux users account for less than 2% of the operating systems market as of September 2014. However, most servers run Linux because it's relatively easy to customize.

Page 49: Ecw course

Operating systems for mobile devices

The operating systems we've been talking about were designed to run on desktop or laptop computers. Mobile devices such as phones, tablet computers, and MP3 players are different from desktop and laptop computers, so they run operating systems that are designed specifically for mobile devices. Examples of mobile operating systems include Apple iOS, Windows Phone, and Google Android. In the screenshot below, you can see Apple iOS running on an iPad.

Operating systems for mobile devices generally aren't as fully featured as those made for desktop and laptop computers, and they aren't able to run all of the same software. However, you can still do a lot of things with them, like watch movies, browse the Web, manage your calendar, and play games.

Page 50: Ecw course
Page 51: Ecw course

RaspberryPiBasics

Contentistakenfromhttps://www.howtoforge.com/tutorial/howto-install-raspbian-on-raspberry-pi/

Raspberry Pi Basics: installing Raspbian and getting it up and running

So, are you a person who got a Raspberry Pi (aka "Pi") and want to start building something with it but don't know how to go about it? If yes, then this tutorial is for you. Here in this howto, we go about installing the Raspbian OS and initiating a desktop environment.

Introduction

Raspberry Pi is a credit card sized micro processor available in different models with different processing speed starting from 700 MHz. Whether you have a model B or model B+, or the very old version, the installation process remains the same. People who have checked out the official Raspberry Pi website, might have seen them recommending the "NOOBS" or "NOOBS LITE" Operating System (aka "OS") for beginners. But using the Pi is very easy and from being a beginner, one will turn pro in no time. So, it's better to go with the more powerful and more efficient OS, the Raspbian. The main reason why Raspbian is extremely popular is that it has thousands of pre built libraries to perform many tasks and optimize the OS. This forms a huge advantage while building applications.

1DownloadingRaspbianandImagewriter

Download the latest version of Raspbian from here. You can download it directly or via the torrents.

You will be needing an image writer to write the downloaded OS into the SD card (micro SD card in case of Raspberry Pi B+ model). So download the "win32 disk imager" from here.

2Writingtheimage

Insert the SD card into the laptop/pc and run the image writer. Once open, browse and select the downloaded Raspbian image file. Select the correct device, that is the drive representing the SD card. If the drive (or device) selected is different from the SD card then the other selected drive will become corrupted. SO be careful.

After that, click on the "Write" button in the bottom. As an example, see the image below, where the SD card (or micro SD) drive is represented by the letter "G:\"

Page 52: Ecw course

Once the write is complete, eject the SD card and insert it into the Raspberry Pi and turn it on. It should start booting up.

3SettingupthePi

Please remember that after booting the Pi, there might be situations when the user credentials like the "username" and password will be asked. Raspberry Pi comes with a default user name and password and so always use it whenever it is being asked. The credentials are:

login: pi password: raspberry

When the Pi has been booted for the first time, a configuration screen called the "Setup Options" should appear and it will look like the image below.

If you have missed the "Setup Options" screen, its not a problem, you can always get it by typing the following command in the terminal.

sudo raspi-config

Page 53: Ecw course

Once you execute this command the "Setup Options" screen will come up as shown in the image above.

Now that the Setup Options window is up, we will have to set a few things. After completing each of the steps below, if it asks to reboot the Pi, please do so. After the reboot, if you don't get the "Setup Options" screen, then follow the command given above to get the screen/window.

Thefirstthingtodo:

select the first option in the list of the setup options window, that is select the "Expand Filesystem" option and hit the enter key. We do this to make use of all the space present on the SD card as a full partition. All this does is, expand the OS to fit the whole space on the SD card which can then be used as the storage memory for the Pi.

Thesecondthingtodo:

select the third option in the list of the setup options window, that is select the "Enable Boot To Desktop/Scratch" option and hit the enter key. It will take you to another window called the "choose boot option" window that looks like the image below.

In the "choose boot option window" , select the second option, that is, "Desktop Log in as user 'pi' at the graphical desktop" and hit the enter button. Once done you will be taken back to the "Setup Options" page, if not select the "OK" button at the bottom of this window and you will be taken back to the previous window. We do this because we wan to boot into the desktop environment which we are familiar with. If we don't do this step then the Raspberry Pi boots into a terminal each time with no GUI options.

Page 54: Ecw course

Once, both the steps are done, select the "finish" button at the bottom of the page and it should reboot automatically. If it doesn't, then use the following command in the terminal to reboot.

sudo reboot

4Updatingthefirmware

After the reboot from the previous step, if everything went right, then you will end up on the desktop which looks like the image below.

Once you are on the desktop, open a terminal and enter the following command to update the firmware of the Pi.

sudo rpi-update

Updating the firmware is necessary because certain models of the Pi might not have all the required dependencies to run smoothly or it may have some bug. The latest firmware might have the fix to those bugs, thus its very important to update it in the beginning itself.

5Conclusion

So, we have covered the steps to get the Pi up and running. This method works on all the different models of Raspberry Pi ( model A, B, B+ and also RPi 2) as Raspbain was made to be supported on all models. However, while installing other software or libraries , the procedure might change a bit while installing depending on the model of the Pi or the version of Raspbian itself. The concept of Raspberry is to keep trying till you get he result or build that you want. This might involve a lot of trial and error but spending the time will be worth it. The actual usage doesn't end here. This is just the beginning. It is up to you to go ahead to build something amazing out of it.

Page 55: Ecw course

6Links

Raspberry Pi Raspbia

Page 56: Ecw course

LINUXCOMMANDS

WhyBother?

Why do you need to learn the command line anyway? Well, let me tell you a story. A few years ago we had a problem where I used to work. There was a shared drive on one of our file servers that kept getting full. I won't mention that this legacy operating system did not support user quotas; that's another story. But the server kept getting full and it stopped people from working. One of our software engineers spent the better part of a day writing a C++ program that would look through all the user's directories and add up the space they were using and make a listing of the results. Since I was forced to use the legacy OS while I was on the job, I installed a Linux-like command line environment for it. When I heard about the problem, I realized I could do all the work this engineer had done with this single line:

du -s * | sort -nr > $HOME/user_space_report.txt

Graphical user interfaces (GUIs) are helpful for many tasks, but they are not good for all tasks. I have long felt that most computers today are not powered by electricity. They instead seem to be powered by the "pumping" motion of the mouse! Computers were supposed to free us from manual labor, but how many times have you performed some task you felt sure the computer should be able to do but you ended up doing the work yourself by tediously working the mouse? Pointing and clicking, pointing and clicking.

I once heard an author say that when you are a child you use a computer by looking at the pictures. When you grow up, you learn to read and write. Welcome to Computer Literacy 101. Now let's get to work.

Contents

1. What Is "The Shell"? 2. Navigation 3. Looking Around 4. A Guided Tour 5. Manipulating Files 6. Working With Commands 7. I/O Redirection 8. Expansion 9. Permissions 10. Job Control

Page 57: Ecw course

WhatIs"TheShell"?

Simply put, the shell is a program that takes commands from the keyboard and gives them to the operating system to perform. In the old days, it was the only user interface available on a Unix-like system such as Linux. Nowadays, we have graphical user interfaces (GUIs) in addition to command line interfaces (CLIs) such as the shell.

On most Linux systems a program called bash (which stands for Bourne Again SHell, an enhanced version of the original Unix shell program, sh, written by Steve Bourne) acts as the shell program. Besides bash, there are other shell programs that can be installed in a Linux system. These include: ksh, tcsh and zsh.

What'sA"Terminal?"

It's a program called a terminal emulator. This is a program that opens a window and lets you interact with the shell. There are a bunch of different terminal emulators you can use. Most Linux distributions supply several, such as: gnome-terminal, konsole, xterm, rxvt, kvt, nxterm, and eterm.

StartingATerminal

Your window manager probably has a way to launch a terminal from the menu. Look through the list of programs to see if anything looks like a terminal emulator. If you are a KDE user, the terminal program is called "konsole," in Gnome it's called "gnome-terminal." You can start up as many of these as you want and play with them. While there are a number of different terminal emulators, they all do the same thing. They give you access to a shell session. You will probably develop a preference for one, based on the different bells and whistles each one provides.

TestingTheKeyboard

OK, let's try some typing. Bring up a terminal window. You should see a shell prompt that contains your user name and the name of the machine followed by a dollar sign. Something like this:

[me@linuxbox me]$

Excellent! Now type some nonsense characters and press the enter key.

[me@linuxbox me]$ kdkjflajfks

If all went well, you should have gotten an error message complaining that it cannot understand you:

[me@linuxbox me]$ kdkjflajfks

bash: kdkjflajfks: command not found

Page 58: Ecw course

Wonderful! Now press the up-arrow key. Watch how our previous command "kdkjflajfks" returns. Yes, we have command history. Press the down-arrow and we get the blank line again.

Recall the "kdkjflajfks" command using the up-arrow key if needed. Now, try the left and right-arrow keys. You can position the text cursor anywhere in the command line. This allows you to easily correct mistakes.

You'renotloggedinasroot,areyou?

If the last character of your shell prompt is # rather than $, you are operating as the superuser. This means that you have administrative privileges. This can be potentially dangerous, since you are able to delete or overwrite any file on the system. Unless you absolutely need administrative privileges, do not operate as the superuser.

UsingTheMouse

Even though the shell is a command line interface, the mouse is still handy.

Besides using the mouse to scroll the contents of the terminal window, you can copy text with the mouse. Drag your mouse over some text (for example, "kdkjflajfks" right here on the browser window) while holding down the left button. The text should highlight. Release the left button and move your mouse pointer to the terminal window and press the middle mouse button (alternately, you can press both the left and right buttons at the same time if you are working on a touch pad). The text you highlighted in the browser window should be copied into the command line.

Afewwordsaboutfocus...

When you installed your Linux system and its window manager (most likely Gnome or KDE), it was configured to behave in some ways like that legacy operating system.

In particular, it probably has its focus policy set to "click to focus." This means that in order for a window to gain focus (become active) you have to click in the window. This is contrary to traditional X Window behavior. You should consider setting the focus policy to "focus follows mouse". You may find it strange at first that windows don't raise to the front when they get focus (you have to click on the window to do that), but you will enjoy being able to work on more than one window at once without having the active window obscuring the the other. Try it and give it a fair trial; I think you will like it. You can find this setting in the configuration tools for your window manager.

Navigation

In this lesson, I will introduce your first three commands: pwd (print working directory), cd (change directory), and ls (list files and directories).

Page 59: Ecw course

If you have not worked with a command line interface before, you will need to pay close attention to this lesson, since the concepts will take some getting used to.

FileSystemOrganization

Like that legacy operating system, the files on a Linux system are arranged in what is called a hierarchical directory structure. This means that they are organized in a tree-like pattern of directories (called folders in other systems), which may contain files and other directories. The first directory in the file system is called the root directory. The root directory contains files and subdirectories, which contain more files and subdirectories and so on and so on.

Most graphical environments today include a file manager program to view and manipulate the contents of the file system. Often you will see the file system represented like this:

One important difference between the legacy operating system and Unix-like operating systems such as Linux is that Linux does not employ the concept of drive letters. While drive letters split the file system into a series of different trees (one for each drive), Linux always has a single tree. Different storage devices may contain different branches of the tree, but there is always a single tree.

pwd

Since a command line interface cannot provide graphic pictures of the file system structure, it must have a different way of representing it. Think of the file system tree as a maze, and you are standing in it. At any given moment, you are located in a single directory. Inside that directory, you can see its files and the pathway to its parent directory and the pathways to the subdirectories of the directory in which you are standing.

The directory you are standing in is called the working directory. To find the name of the working directory, use the pwd command.

[me@linuxbox me]$ pwd /home/me

Page 60: Ecw course

When you first log on to a Linux system, the working directory is set to your home directory. This is where you put your files. On most systems, your home directory will be called /home/your_user_name, but it can be anything according to the whims of the system administrator.

To list the files in the working directory, use the ls command.

[me@linuxbox me]$ ls

Desktop Xrootenv.0 linuxcmd GNUstep bin nedit.rpm GUILG00.GZ hitni123.jpg nsmail

I will come back to ls in the next lesson. There are a lot of fun things you can do with it, but I have to talk about pathnames and directories a bit first.

cd

To change your working directory (where you are standing in the maze) you use the cd command. To do this, type cd followed by the pathname of the desired working directory. A pathname is the route you take along the branches of the tree to get to the directory you want. Pathnames can be specified in one of two different ways; absolute pathnames or relative pathnames. Let's look with absolute pathnames first.

An absolute pathname begins with the root directory and follows the tree branch by branch until the path to the desired directory or file is completed. For example, there is a directory on your system in which most programs are installed. The pathname of the directory is /usr/bin. This means from the root directory (represented by the leading slash in the pathname) there is a directory called "usr" which contains a directory called "bin".

Let's try this out:

[me@linuxbox me]$ cd /usr/bin [me@linuxbox bin]$ pwd /usr/bin [me@linuxbox bin]$ ls

[ lwp-request 2to3 lwp-rget 2to3-2.6 lxterm a2p lz aalib-config lzcat aconnect lzma acpi_fakekey lzmadec acpi_listen lzmainfo add-apt-repository m17n-db addpart magnifier and many more...

Page 61: Ecw course

Now we can see that we have changed the current working directory to /usr/bin and that it is full of files. Notice how your prompt has changed? As a convenience, it is usually set up to display the name of the working directory.

Where an absolute pathname starts from the root directory and leads to its destination, a relative pathname starts from the working directory. To do this, it uses a couple of special notations to represent relative positions in the file system tree. These special notations are "." (dot) and ".." (dot dot).

The "." notation refers to the working directory itself and the ".." notation refers to the working directory's parent directory. Here is how it works. Let's change the working directory to /usr/bin again:

[me@linuxbox me]$ cd /usr/bin [me@linuxbox bin]$ pwd /usr/bin

O.K., now let's say that we wanted to change the working directory to the parent of /usr/bin which is /usr. We could do that two different ways. First, with an absolute pathname:

[me@linuxbox bin]$ cd /usr [me@linuxbox usr]$ pwd /usr

Or, with a relative pathname:

[me@linuxbox bin]$ cd .. [me@linuxbox usr]$ pwd /usr

Two different methods with identical results. Which one should you use? The one that requires the least typing!

Likewise, we can change the working directory from /usr to /usr/bin in two different ways. First using an absolute pathname:

[me@linuxbox usr]$ cd /usr/bin [me@linuxbox bin]$ pwd /usr/bin

Or, with a relative pathname:

[me@linuxbox usr]$ cd ./bin [me@linuxbox bin]$ pwd /usr/bin

Now, there is something important that I must point out here. In almost all cases, you can omit the "./". It is implied. Typing:

[me@linuxbox usr]$ cd bin

Page 62: Ecw course

would do the same thing. In general, if you do not specify a pathname to something, the working directory will be assumed. There is one important exception to this, but we won't get to that for a while.

AFewShortcuts

If you type cd followed by nothing, cd will change the working directory to your home directory.

A related shortcut is to type cd ~user_name. In this case, cd will change the working directory to the home directory of the specified user.

Typing cd - changes the working directory to the previous one.

Importantfactsaboutfilenames

1. File names that begin with a period character are hidden. This only means that ls will not list them unless you say ls -a. When your account was created, several hidden files were placed in your home directory to configure things for your account. Later on we will take a closer look at some of these files to see how you can customize your environment. In addition, some applications will place their configuration and settings files in your home directory as hidden files.

2. File names in Linux, like Unix, are case sensitive. The file names "File1" and "file1" refer to different files.

3. Linux has no concept of a "file extension" like legacy operating systems. You may name files any way you like. However, while Linux itself does not care about file extensions, many application programs do.

4. Though Linux supports long file names which may contain embedded spaces and punctuation characters, limit the punctuation characters to period, dash, and underscore. Most importantly, do not embed spaces in file names. If you want to represent spaces between words in a file name, use underscore characters. You will thank yourself later.

LookingAround

Now that you know how to move from working directory to working directory, we're going to take a tour of your Linux system and, along the way, learn some things about what makes it tick. But before we begin, I have to teach you some tools that will come in handy during our adventure. These are:

Page 63: Ecw course

ls (list files and directories) less (view text files) file (classify a file's contents)

ls

The ls command is used to list the contents of a directory. It is probably the most commonly used Linux command. It can be used in a number of different ways. Here are some examples:

Examples of the ls command

Command Result

ls List the files in the working directory

ls /bin List the files in the /bin directory (or any other directory you care to specify)

ls -l List the files in the working directory in long format

ls -l /etc /bin List the files in the /bin directory and the /etc directory in long format

ls -la .. List all files (even ones with names beginning with a period character, which are normally hidden) in the parent of the working directory in long format

These examples also point out an important concept about commands. Most commands operate like this:

command -options arguments

where command is the name of the command, -options is one or more adjustments to the command's behavior, and arguments is one or more "things" upon which the command operates.

In the case of ls, we see that ls is the name of the command, and that it can have one or more options, such as -a and -l, and it can operate on one or more files or directories.

A Closer Look At Long Format

If you use the -l option with ls, you will get a file listing that contains a wealth of information about the files being listed. Here's an example:

Page 64: Ecw course

-rw------- 1 bshotts bshotts 576 Apr 17 1998 weather.txt drwxr-xr-x 6 bshotts bshotts 1024 Oct 9 1999 web_page -rw-rw-r-- 1 bshotts bshotts 276480 Feb 11 20:41 web_site.tar -rw------- 1 bshotts bshotts 5743 Dec 16 1998 xmas_file.txt ---------- ------- ------- -------- ------------ ------------- | | | | | | | | | | | File Name | | | | | | | | | +--- Modification Time | | | | | | | +------------- Size (in bytes) | | | | | +----------------------- Group | | | +-------------------------------- Owner | +---------------------------------------------- File Permissions

File Name

The name of the file or directory.

Modification Time

The last time the file was modified. If the last modification occurred more than six months in the past, the date and year are displayed. Otherwise, the time of day is shown.

Size

The size of the file in bytes.

Group

The name of the group that has file permissions in addition to the file's owner.

Owner

The name of the user who owns the file.

File Permissions

A representation of the file's access permissions. The first character is the type of file. A "-" indicates a regular (ordinary) file. A "d" indicates a directory. The second set of three characters represent the read, write, and execution rights of the file's owner. The next three represent the rights of the file's group, and the final three represent the rights granted to everybody else. I'll discuss this in more detail in a later lesson.

less

less is a program that lets you view text files. This is very handy since many of the files used to control and configure Linux are human readable.

Page 65: Ecw course

Whatis"text"?

There are many ways to represent information on a computer. All methods involve defining a relationship between the information and some numbers that will be used to represent it. Computers, after all, only understand numbers and all data is converted to numeric representation.

Some of these representation systems are very complex (such as compressed multimedia files), while others are rather simple. One of the earliest and simplest is called ASCII text. ASCII (pronounced "As-Key") is short for American Standard Code for Information Interchange. This is a simple encoding scheme that was first used on Teletype machines to map keyboard characters to numbers.

Text is a simple one-to-one mapping of characters to numbers. It is very compact. Fifty characters of text translates to fifty bytes of data. Throughout a Linux system, many files are stored in text format and there are many Linux tools that work with text files. Even the legacy operating systems recognize the importance of this format. The well-known NOTEPAD.EXE program is an editor for plain ASCII text files.

The less program is invoked by simply typing:

less text_file

This will display the file.

Controlling less

Once started, less will display the text file one page at a time. You may use the Page Up and Page Down keys to move through the text file. To exit less, type "q". Here are some commands that less will accept:

Keyboard commands for the less program

Command Action

Page Up or b Scroll back one page

Page Down or space

Scroll forward one page

G Go to the end of the text file

1G Go to the beginning of the text file

/characters Search forward in the text file for an occurrence of the specified characters

Page 66: Ecw course

n Repeat the previous search

h Display a complete list less commands and options

q Quit

file

As you wander around your Linux system, it is helpful to determine what kind of data a file contains before you try to view it. This is where the file command comes in. file will examine a file and tell you what kind of file it is.

To use the file program, just type:

file name_of_file

The file program can recognize most types of files, such as:

Various kinds of files

File Type Description Viewable as text?

ASCII text The name says it all yes

Bourne-Again shell script text

A bash script yes

ELF 32-bit LSB core file

A core dump file (a program will create this when it crashes)

no

ELF 32-bit LSB executable

An executable binary program no

ELF 32-bit LSB shared object

A shared library no

GNU tar archive A tape archive file. A common way of storing groups of files.

no, use tar tvf to view listing.

gzip compressed data An archive compressed with gzip no

HTML document text A web page yes

JPEG image data A compressed JPEG image no

PostScript document A PostScript file yes

Page 67: Ecw course

text

RPM A Red Hat Package Manager archive no, use rpm -q to examine contents.

Zip archive data An archive compressed with zip no

While it may seem that most files cannot be viewed as text, you will be surprised how many can. This is especially true of the important configuration files. You will also notice during our adventure that many features of the operating system are controlled by shell scripts. In Linux, there are no secrets!

AGuidedTour

It's time to take our tour. The table below lists some interesting places to explore. This is by no means a complete list, but it should prove to be an interesting adventure. For each of the directories listed below, do the following:

cd into each directory. Use ls to list the contents of the directory. If you see an interesting file, use the file command to determine its contents. For text files, use less to view them.

Interesting directories and their contents

Directory Description

/ The root directory where the file system begins. In most cases the root directory only contains subdirectories.

/boot This is where the Linux kernel and boot loader files are kept. The kernel is a file called vmlinuz.

/etc The /etc directory contains the configuration files for the system. All of the files in /etc should be text files. Points of interest:

Page 68: Ecw course

/etc/passwd

The passwd file contains the essential information for each user. It is here that users are defined.

/etc/fstab

The fstab file contains a table of devices that get mounted when your system boots. This file defines your disk drives.

/etc/hosts

This file lists the network host names and IP addresses that are intrinsically known to the system.

/etc/init.d

This directory contains the scripts that start various system services typically at boot time.

/bin, /usr/bin These two directories contain most of the programs for the system. The /bin directory has the essential programs that the system requires to operate, while /usr/bin contains applications for the system's users.

/sbin, /usr/sbin The sbin directories contain programs for system administration, mostly for use by the superuser.

/usr The /usr directory contains a variety of things that support user applications. Some highlights:

/usr/share/X11

Support files for the X Window system

/usr/share/dict

Dictionaries for the spelling checker. Bet you didn't know that Linux had a spelling checker. See look and aspell.

/usr/share/doc

Various documentation files in a variety of formats.

/usr/share/man

The man pages are kept here.

/usr/src

Source code files. If you installed the kernel source code package,

Page 69: Ecw course

you will find the entire Linux kernel source code here.

/usr/local /usr/local and its subdirectories are used for the installation of software and other files for use on the local machine. What this really means is that software that is not part of the official distribution (which usually goes in /usr/bin) goes here. When you find interesting programs to install on your system, they should be installed in one of the /usr/local directories. Most often, the directory of choice is /usr/local/bin.

/var The /var directory contains files that change as the system is running. This includes:

/var/log

Directory that contains log files. These are updated as the system runs. You should view the files in this directory from time to time, to monitor the health of your system.

/var/spool

This directory is used to hold files that are queued for some process, such as mail messages and print jobs. When a user's mail first arrives on the local system (assuming you have local mail), the messages are first stored in /var/spool/mail

/lib The shared libraries (similar to DLLs in that other operating system) are kept here.

/home /home is where users keep their personal work. In general, this is the only place users are allowed to write files. This keeps things nice and clean :-)

/root This is the superuser's home directory.

/tmp /tmp is a directory in which programs can write their temporary files.

/dev The /dev directory is a special directory, since it does not really contain files in the usual sense. Rather, it contains devices that are available to the system. In Linux (like Unix), devices are treated like files. You can read and write devices as though they were files. For example /dev/fd0 is the first floppy disk drive, /dev/sda (/dev/hda on older systems) is the first hard

Page 70: Ecw course

drive. All the devices that the kernel understands are represented here.

/proc The /proc directory is also special. This directory does not contain files. In fact, this directory does not really exist at all. It is entirely virtual. The /proc directory contains little peep holes into the kernel itself. There are a group of numbered entries in this directory that correspond to all the processes running on the system. In addition, there are a number of named entries that permit access to the current configuration of the system. Many of these entries can be viewed. Try viewing /proc/cpuinfo. This entry will tell you what the kernel thinks of your CPU.

/media,/mnt Finally, we come to /media, a normal directory which is used in a special way. The /media directory is used for mount points. As we learned in the second lesson, the different physical storage devices (like hard disk drives) are attached to the file system tree in various places. This process of attaching a device to the tree is called mounting. For a device to be available, it must first be mounted. When your system boots, it reads a list of mounting instructions in the file /etc/fstab, which describes which device is mounted at which mount point in the directory tree. This takes care of the hard drives, but you may also have devices that are considered temporary, such as CD-ROMs, thumb drives, and floppy disks. Since these are removable, they do not stay mounted all the time. The /media directory is used by the automatic device mounting mechanisms found in modern desktop oriented Linux distributions. On systems that require manual mounting of removable devices, the /mnt directory provides a convenient place for mounting these temporary devices. You will often see the directories /mnt/floppy and /mnt/cdrom. To see what devices and mount points are used, type mount.

Aweirdkindoffile...

During your tour, you probably noticed a strange kind of directory entry, particularly in the /boot and /lib directories. When listed with ls -l, you would have seen something like this:

lrwxrwxrwx 25 Jul 3 16:42 System.map -> /boot/System.map-2.0.36-3 -rw-r--r-- 105911 Oct 13 1998 System.map-2.0.36-0.7 -rw-r--r-- 105935 Dec 29 1998 System.map-2.0.36-3 -rw-r--r-- 181986 Dec 11 1999 initrd-2.0.36-0.7.img

Page 71: Ecw course

-rw-r--r-- 182001 Dec 11 1999 initrd-2.0.36.img lrwxrwxrwx 26 Jul 3 16:42 module-info -> /boot/module-info-2.0.36-3 -rw-r--r-- 11773 Oct 13 1998 module-info-2.0.36-0.7 -rw-r--r-- 11773 Dec 29 1998 module-info-2.0.36-3 lrwxrwxrwx 16 Dec 11 1999 vmlinuz -> vmlinuz-2.0.36-3 -rw-r--r-- 454325 Oct 13 1998 vmlinuz-2.0.36-0.7 -rw-r--r-- 454434 Dec 29 1998 vmlinuz-2.0.36-3

Notice the files, System.map, module-info and vmlinuz. See the strange notation after the file names?

These three files are called symbolic links. Symbolic links are a special type of file that points to another file. With symbolic links, it is possible for a single file to have multiple names. Here's how it works: Whenever the system is given a file name that is a symbolic link, it transparently maps it to the file it is pointing to.

Just what is this good for? This is a very handy feature. Let's consider the directory listing above (which is the /boot directory of an old Red Hat 5.2 system). This system has had multiple versions of the Linux kernel installed. We can see this from the files vmlinuz-2.0.36-0.7 and vmlinuz-2.0.36-3. These file names suggest that both version 2.0.36-0.7 and 2.0.36-3 are installed. Because the file names contain the version it is easy to see the differences in the directory listing. However, this would be confusing to programs that rely on a fixed name for the kernel file. These programs might expect the kernel to simply be called "vmlinuz". Here is where the beauty of the symbolic link comes in. By creating a symbolic link called vmlinuz that points to vmlinuz-2.0.36-3, we have solved the problem.

To create symbolic links, use the ln command.

ManipulatingFiles

This lesson will introduce you to the following commands:

cp - copy files and directories mv - move or rename files and directories rm - remove files and directories mkdir - create directories

These four commands are among the most frequently used Linux commands. They are the basic commands for manipulating both files and directories.

Now, to be frank, some of the tasks performed by these commands are more easily done with a graphical file manager. With a file manager, you can drag and drop a file from one

Page 72: Ecw course

directory to another, cut and paste files, delete files, etc. So why use these old command line programs?

The answer is power and flexibility. While it is easy to perform simple file manipulations with a graphical file manager, complicated tasks can be easier with the command line programs. For example, how would you copy all the HTML files from one directory to another, but only copy files that did not exist in the destination directory or were newer than the versions in the destination directory? Pretty hard with with a file manager. Pretty easy with the command line:

[me@linuxbox me]$ cp -u *.html destination

Wildcards

Before I begin with our commands, I want to talk about a shell feature that makes these commands so powerful. Since the shell uses filenames so much, it provides special characters to help you rapidly specify groups of filenames. These special characters are called wildcards. Wildcards allow you to select filenames based on patterns of characters. The table below lists the wildcards and what they select:

Summary of wildcards and their meanings

Wildcard Meaning

* Matches any characters

? Matches any single character

[characters]

Matches any character that is a member of the set characters. The set of characters may also be expressed as a POSIX character class such as one of the following:

POSIX Character Classes

[:alnum:] Alphanumeric characters

[:alpha:] Alphabetic characters

[:digit:] Numerals

[:upper:] Uppercase alphabetic characters

[:lower:] Lowercase alphabetic characters

[!characters] Matches any character that is not a member of the set characters

Page 73: Ecw course

Using wildcards, it is possible to construct very sophisticated selection criteria for filenames. Here are some examples of patterns and what they match:

Examples of wildcard matching

Pattern Matches

* All filenames

g* All filenames that begin with the character "g"

b*.txt All filenames that begin with the character "b" and end with the characters ".txt"

Data??? Any filename that begins with the characters "Data" followed by exactly 3 more characters

[abc]* Any filename that begins with "a" or "b" or "c" followed by any other characters

[[:upper:]]* Any filename that begins with an uppercase letter. This is an example of a character class.

BACKUP.[[:digit:]][[:digit:]] Another example of character classes. This pattern matches any filename that begins with the characters "BACKUP." followed by exactly two numerals.

*[![:lower:]] Any filename that does not end with a lowercase letter.

You can use wildcards with any command that accepts filename arguments.

cp

The cp program copies files and directories. In its simplest form, it copies a single file:

[me@linuxbox me]$ cp file1 file2

It can also be used to copy multiple files (and/or directories) to a different directory:

[me@linuxbox me]$ cp file... directory

A note on notation: ... signifies that an item can be repeated one or more times.

Other useful examples of cp and its options include:

Page 74: Ecw course

Examples of the cp command

Command Results

cp file1 file2

Copies the contents of file1 into file2. If file2 does not exist, it is created; otherwise, file2 is silently overwritten with the contents of file1.

cp -i file1 file2

Like above however, since the "-i" (interactive) option is specified, if file2 exists, the user is prompted before it is overwritten with the contents of file1.

cp file1 dir1 Copy the contents of file1 (into a file named file1) inside of directory dir1.

cp -R dir1 dir2

Copy the contents of the directory dir1. If directory dir2 does not exist, it is created. Otherwise, it creates a directory named dir1 within directory dir2.

mv

The mv command moves or renames files and directories depending on how it is used. It will either move one or more files to a different directory, or it will rename a file or directory. To rename a file, it is used like this:

[me@linuxbox me]$ mv filename1 filename2

To move files (and/or directories) to a different directory:

[me@linuxbox me]$ mv file... directory

Examples of mv and its options include:

Examples of the mv command

Command Results

mv file1 file2 If file2 does not exist, then file1 is renamed file2. If file2 exists, its contents are silently replaced with the contents of file1.

mv -i file1 file2

Like above however, since the "-i" (interactive) option is specified, if file2 exists, the user is prompted before it is overwritten with the contents of file1.

mv file1 file2 file3 dir1

The files file1, file2, file3 are moved to directory dir1. If dir1 does not exist, mv will exit with an error.

Page 75: Ecw course

mv dir1 dir2 If dir2 does not exist, then dir1 is renamed dir2. If dir2 exists, the directory dir1 is moved within directory dir2.

rm

The rm command removes (deletes) files and directories.

[me@linuxbox me]$ rm file...

It can also be used to delete directories:

[me@linuxbox me]$ rm -r directory...

Examples of rm and its options include:

Examples of the rm command

Command Results

rm file1 file2 Delete file1 and file2.

rm -i file1 file2

Like above however, since the "-i" (interactive) option is specified, the user is prompted before each file is deleted.

rm -r dir1 dir2 Directories dir1 and dir2 are deleted along with all of their contents.

Becarefulwithrm!

Linux does not have an undelete command. Once you delete something with rm, it's gone. You can inflict terrific damage on your system with rm if you are not careful, particularly with wildcards.

Before you use rm with wildcards, try this helpful trick: construct your command using ls instead. By doing this, you can see the effect of your wildcards before you delete files. After you have tested your command with ls, recall the command with the up-arrow key and then substitute rm for ls in the command.

mkdir

The mkdir command is used to create directories. To use it, you simply type:

[me@linuxbox me]$ mkdir directory...

Page 76: Ecw course

UsingCommandsWithWildcards

Since the commands we have covered here accept multiple file and directories names as arguments, you can use wildcards to specify them. Here are a few examples:

Command examples using wildcards

Command Results

cp *.txt text_files

Copy all files in the current working directory with names ending with the characters ".txt" to an existing directory named text_files.

mv my_dir ../*.bak my_new_dir

Move the subdirectory my_dir and all the files ending in ".bak" in the current working directory's parent directory to an existing directory named my_new_dir.

rm *~ Delete all files in the current working directory that end with the character "~". Some applications create backup files using this naming scheme. Using this command will clean them out of a directory.

WorkingWithCommands

Up until now you have seen a number of commands and their mysterious options and arguments. In this lesson, we will try to remove some of that mystery. This lesson will introduce the following commands.

type - Display information about command type which - Locate a command help - Display reference page for shell builtin man - Display an on-line command reference

WhatAre"Commands?"

Commands can be one of 4 different kinds:

1. An executable program like all those files we saw in /usr/bin. Within this category, programs can be compiled binaries such as programs written in C and C++, or programs written in scripting languages such as the shell, Perl, Python, Ruby, etc.

2. A command built into the shell itself. bash provides a number of commands internally called shell builtins. The cd command, for example, is a shell builtin.

Page 77: Ecw course

3. A shell function. These are miniature shell scripts incorporated into the environment. We will cover configuring the environment and writing shell functions in later lessons, but for now, just be aware that they exist.

4. An alias. Commands that you can define yourselves, built from other commands. This will be covered in a later lesson.

IdentifyingCommands

It is often useful to know exactly which of the four kinds of commands is being used and Linux provides a couple of ways to find out.

type

The type command is a shell builtin that displays the kind of command the shell will execute, given a particular command name. It works like this:

type command

examples:

[me@linuxbox me]$ type type type is a shell builtin

[me@linuxbox me]$ type ls ls is aliased to `ls --color=tty'

[me@linuxbox me]$ type cp cp is /bin/cp

Here we see the results for three different commands. Notice that the one for ls (taken from a --

output from ls is displayed in color!

which

Sometimes there is more than one version of an executable program installed on a system. While this is not very common on desktop systems, it's not unusual on large servers. To determine the exact location of a given executable, the which command is used:

[me@linuxbox me]$ which ls /bin/ls

which only works for executable programs, not builtins nor aliases that are substitutes for actual executable programs.

GettingCommandDocumentation

With this knowledge of what a command is, we can now search for the documentation available for each kind of command.

Page 78: Ecw course

help

bash has a built-followed by the name of the shell builtin. Optionally, you may add the -m option to change the format of the output. For example:

[me@linuxbox me]$ help -m cd

NAME cd - Change the shell working directory. SYNOPSIS cd [-L|-P] [dir] DESCRIPTION Change the shell working directory. Change the current directory to DIR. The default DIR is the value of the HOME shell variable. The variable CDPATH defines the search path for the directory containing DIR. Alternative directory names in CDPATH are separated by a colon (:). A null directory name is the same as the current directory. If DIR begins with a slash (/), then CDPATH is not used. If the directory is not found, and the shell option `cdable_vars' is set, the word is assumed to be a variable name. If that variable has a value, its value is used for DIR. Options: -L force symbolic links to be followed -P use the physical directory structure without following symbolic links The default is to follow symbolic links, as if `-L' were specified. Exit Status: Returns 0 if the directory is changed; non-zero otherwise. SEE ALSO bash(1) IMPLEMENTATION GNU bash, version 4.1.5(1)-release (i486-pc-linux-gnu) Copyright (C) 2009 Free Software Foundation, Inc.

A note on notation: When square brackets appear in the description of a command's syntax, they indicate optional items. A vertical bar character indicates mutually exclusive items. In the case of the cd command above:

cd [-L|-P] [dir]

Page 79: Ecw course

This notation says that the command cd - -

--help

-- cription of the command's supported syntax and options. For example:

[me@linuxbox me]$ mkdir --help

Usage: mkdir [OPTION] DIRECTORY... Create the DIRECTORY(ies), if they do not already exist. -Z, --context=CONTEXT (SELinux) set security context to CONTEXT Mandatory arguments to long options are mandatory for short options too. -m, --mode=MODE set file mode (as in chmod), not a=rwx umask -p, --parents no error if existing, make parent directories as needed -v, --verbose print a message for each created directory --help display this help and exit --version output version information and exit

--error message that will reveal similar usage information.

man

Most executable programs intended for command line use provide a formal piece of documentation called a manual or man page. A special paging program called man is used to view them. It is used like this:

man program

but generally contain a title, a synopsis of the command's syntax, a description of the command's purpose, and a listing and description of each of the command's options. Man pages, however, do not usually include examples, and are intended as a reference, not a tutorial. As an example, let's try viewing the man pagefor the ls command:

[me@linuxbox me]$ man ls

On most Linux systems, man uses less to display the manual page, so all of the familiar less commands work while displaying the page.

README And Other Documentation Files

Many software packages installed on your system have documentation files residing in the /usr/share/doc directory. Most of these are stored in plain text format and can be viewed with less. Some of the files are in HTML format and can be viewed with your web browser. You

Page 80: Ecw course

compressed with the gzip compression program. The gzip package includes a special version of less called zless that will display the contents of gzip-compressed text files.

I/ORedirection

In this lesson, we will explore a powerful feature used by many command line programs called input/output redirection. As we have seen, many commands such as ls print their output on the display. This does not have to be the case, however. By using some special notations we can redirect the output of many commands to files, devices, and even to the input of other commands.

StandardOutput

Most command line programs that display their results do so by sending their results to a facility called standard output. By default, standard output directs its contents to the display. To redirect standard output to a file, the ">" character is used like this:

[me@linuxbox me]$ ls > file_list.txt

In this example, the ls command is executed and the results are written in a file named file_list.txt. Since the output of ls was redirected to the file, no results appear on the display.

Each time the command above is repeated, file_list.txt is overwritten from the beginning with the output of the command ls. If you want the new results to be appended to the file instead, use ">>" like this:

[me@linuxbox me]$ ls >> file_list.txt

When the results are appended, the new results are added to the end of the file, thus making the file longer each time the command is repeated. If the file does not exist when you attempt to append the redirected output, the file will be created.

StandardInput

Many commands can accept input from a facility called standard input. By default, standard input gets its contents from the keyboard, but like standard output, it can be redirected. To redirect standard input from a file instead of the keyboard, the "<" character is used like this:

[me@linuxbox me]$ sort < file_list.txt

In the example above, we used the sort command to process the contents of file_list.txt. The results are output on the display since the standard output was not redirected. We could redirect standard output to another file like this:

[me@linuxbox me]$ sort < file_list.txt > sorted_file_list.txt

Page 81: Ecw course

As you can see, a command can have both its input and output redirected. Be aware that the order of the redirection does not matter. The only requirement is that the redirection operators (the "<" and ">") must appear after the other options and arguments in the command.

Pipelines

The most useful and powerful thing you can do with I/O redirection is to connect multiple commands together with what are called pipelines. With pipelines, the standard output of one command is fed into the standard input of another. Here is my absolute favorite:

[me@linuxbox me]$ ls -l | less

In this example, the output of the ls command is fed into less. By using this "| less" trick, you can make any command have scrolling output. I use this technique all the time.

By connecting commands together, you can acomplish amazing feats. Here are some examples you'll want to try:

Examples of commands used together with pipelines

Command What it does

ls -lt | head Displays the 10 newest files in the current directory.

du | sort -nr Displays a list of directories and how much space they consume, sorted from the largest to the smallest.

find . -type f -print | wc -l Displays the total number of files in the current working directory and all of its subdirectories.

Filters

One kind of program frequently used in pipelines is called filters. Filters take standard input and perform an operation upon it and send the results to standard output. In this way, they can be combined to process information in powerful ways. Here are some of the common programs that can act as filters:

Common filter commands

Program What it does

sort Sorts standard input then outputs the sorted result on standard output.

uniq

Given a sorted stream of data from standard input, it removes duplicate lines of data (i.e., it makes sure that every line is unique).

Page 82: Ecw course

grep

Examines each line of data it receives from standard input and outputs every line that contains a specified pattern of characters.

fmt Reads text from standard input, then outputs formatted text on standard output.

pr

Takes text input from standard input and splits the data into pages with page breaks, headers and footers in preparation for printing.

head Outputs the first few lines of its input. Useful for getting the header of a file.

tail

Outputs the last few lines of its input. Useful for things like getting the most recent entries from a log file.

tr

Translates characters. Can be used to perform tasks such as upper/lowercase conversions or changing line termination characters from one type to another (for example, converting DOS text files into Unix style text files).

sed Stream editor. Can perform more sophisticated text translations than tr.

awk

An entire programming language designed for constructing filters. Extremely powerful.

Performingtaskswithpipelines

1. Printing from the command line. Linux provides a program called lpr that accepts standard input and sends it to the printer. It is often used with pipes and filters. Here are a couple of examples:

2. 3. cat poorly_formatted_report.txt | fmt | pr | lpr 4. 5. cat unsorted_list_with_dupes.txt | sort | uniq | pr | lpr 6.

In the first example, we use cat to read the file and output it to standard output, which is piped into the standard input of fmt. fmt formats the text into neat paragraphs and outputs it to standard output, which is piped into the standard input of pr. pr splits the text neatly into pages and outputs it to standard output, which is piped into the standard input of lpr. lpr takes its standard input and sends it to the printer.

The second example starts with an unsorted list of data with duplicate entries. First, cat sends the list into sort which sorts it and feeds it into uniq which removes any duplicates. Next pr and lpr are used to paginate and print the list.

7. Viewing the contents of tar files Often you will see software distributed as a gzipped tar file. This is a traditional Unix style tape archive file (created with tar) that has been compressed with gzip. You can recognize these files by their traditional file extensions, ".tar.gz" or ".tgz". You can use the following command to view the directory of such a file on a Linux system:

8. tar tzvf name_of_file.tar.gz | less

Page 83: Ecw course

Expansion

Each time you type a command line and press the enter key, bash performs several processes upon the text before it carries out your command. We have seen a couple of cases of how a

process that makes this happen is called expansion. With expansion, you type something and it is expanded into something else before the shell acts upon it. To demonstrate what we mean by this, let's take a look at the echo command. echo is a shell builtin that performs a very simple task. It prints out its text arguments on standard output:

[me@linuxbox me]$ echo this is a test this is a test

That's pretty straightforward. Any argument passed to echo gets displayed. Let's try another example:

[me@linuxbox me]$ echo * Desktop Documents ls-output.txt Music Pictures Public Templates Videos

So what just happened? Why didn't echo

in our original discussion was how the shell does that. The simple answer is that the shell e files in the current

working directory) before the echo command is executed. When the enter key is pressed, the shell automatically expands any qualifying characters on the command line before the command is carried out, so the echo command never saw the Knowing this, we can see that echo behaved as expected.

PathnameExpansion

The mechanism by which wildcards work is called pathname expansion. If we try some of the techniques that we employed in our earlier lessons, we will see that they are really expansions. Given a home directory that looks like this:

[me@linuxbox me]$ ls

Desktop ls-output.txt Documents Music Pictures Public Templates Videos

we could carry out the following expansions:

[me@linuxbox me]$ echo D* Desktop Documents

and:

Page 84: Ecw course

[me@linuxbox me]$ echo *s Documents Pictures Templates Videos

or even:

[me@linuxbox me]$ echo [[:upper:]]* Desktop Documents Music Pictures Public Templates Videos

and looking beyond our home directory:

[me@linuxbox me]$ echo /usr/*/share /usr/kerberos/share /usr/local/share

TildeExpansion

As you may recall from our introduction to the cd special meaning. When used at the beginning of a word, it expands into the name of the home directory of the named user, or if no user is named, the home directory of the current user:

[me@linuxbox me]$ echo ~ /home/me

[me@linuxbox me]$ echo ~foo /home/foo

ArithmeticExpansion

The shell allows arithmetic to be performed by expansion. This allow us to use the shell prompt as a calculator:

[me@linuxbox me]$ echo $((2 + 2)) 4

Arithmetic expansion uses the form:

$((expression))

where expression is an arithmetic expression consisting of values and arithmetic operators.

Arithmetic expansion only supports integers (whole numbers, no decimals), but can perform quite a number of different operations.

Spaces are not significant in arithmetic expressions and expressions may be nested. For example, to multiply five squared by three:

[me@linuxbox me]$ echo $(($((5**2)) * 3)) 75

Page 85: Ecw course

Single parentheses may be used to group multiple subexpressions. With this technique, we can rewrite the example above and get the same result using a single expansion instead of two:

[me@linuxbox me]$ echo $(((5**2) * 3)) 75

Here is an example using the division and remainder operators. Notice the effect of integer division:

[me@linuxbox me]$ echo Five divided by two equals $((5/2)) Five divided by two equals 2 [me@linuxbox me]$ echo with $((5%2)) left over. with 1 left over.

BraceExpansion

Perhaps the strangest expansion is called brace expansion. With it, you can create multiple text strings from a pattern containing braces. Here's an example:

[me@linuxbox me]$ echo Front-{A,B,C}-Back Front-A-Back Front-B-Back Front-C-Back

Patterns to be brace expanded may contain a leading portion called a preamble and a trailing portion called a postscript. The brace expression itself may contain either a comma-separated list of strings, or a range of integers or single characters. The pattern may not contain embedded whitespace. Here is an example using a range of integers:

[me@linuxbox me]$ echo Number_{1..5} Number_1 Number_2 Number_3 Number_4 Number_5

A range of letters in reverse order:

[me@linuxbox me]$ echo {Z..A} Z Y X W V U T S R Q P O N M L K J I H G F E D C B A

Brace expansions may be nested:

[me@linuxbox me]$ echo a{A{1,2},B{3,4}}b aA1b aA2b aB3b aB4b

So what is this good for? The most common application is to make lists of files or directories to be created. For example, if you were a photographer and had a large collection of images you wanted to organize into years and months, the first thing you might do is create a series

- way, the directory names will sort in chronological order. You could type out a complete list of directories, but that's a lot of work and it's error-prone too. Instead, you could do this:

[me@linuxbox me]$ mkdir Photos [me@linuxbox me]$ cd Photos [me@linuxbox Photos]$ mkdir {2007..2009}-0{1..9} {2007..2009}-{10..12} [me@linuxbox Photos]$ ls

Page 86: Ecw course

2007-01 2007-07 2008-01 2008-07 2009-01 2009-07 2007-02 2007-08 2008-02 2008-08 2009-02 2009-08 2007-03 2007-09 2008-03 2008-09 2009-03 2009-09 2007-04 2007-10 2008-04 2008-10 2009-04 2009-10 2007-05 2007-11 2008-05 2008-11 2009-05 2009-11 2007-06 2007-12 2008-06 2008-12 2009-06 2009-12

Pretty slick!

ParameterExpansion

We're only going to touch briefly on parameter expansion in this lesson, but we'll be covering it more later. It's a feature that is more useful in shell scripts than directly on the command line. Many of its capabilities have to do with the system's ability to store small chunks of data and to give each chunk a name. Many such chunks, more properly called variablescontains your user name. To invoke parameter expansion and reveal the contents of USER you would do this:

[me@linuxbox me]$ echo $USER me

To see a list of available variables, try this:

[me@linuxbox me]$ printenv | less

You may have noticed that with other types of expansion, if you mistype a pattern, the expansion will not take place and the echo command will simply display the mistyped pattern. With parameter expansion, if you misspell the name of a variable, the expansion will still take place, but will result in an empty string:

[me@linuxbox me]$ echo $SUER [me@linuxbox ~]$

CommandSubstitution

Command substitution allows us to use the output of a command as an expansion:

[me@linuxbox me]$ echo $(ls) Desktop Documents ls-output.txt Music Pictures Public Templates Videos

One of my favorites goes something like this:

[me@linuxbox me]$ ls -l $(which cp) -rwxr-xr-x 1 root root 71516 2007-12-05 08:58 /bin/cp

Here we passed the results of which cp as an argument to the ls command, thereby getting the listing of of the cp program without having to know its full pathname. We are not limited to just simple commands. Entire pipelines can be used (only partial output shown):

[me@linuxbox me]$ file $(ls /usr/bin/* | grep bin/zip)

Page 87: Ecw course

/usr/bin/bunzip2: /usr/bin/zip: ELF 32-bit LSB executable, Intel 80386, version 1 (SYSV), dynamically linked (uses shared libs), for GNU/Linux 2.6.15, stripped /usr/bin/zipcloak: ELF 32-bit LSB executable, Intel 80386, version 1 (SYSV), dynamically linked (uses shared libs), for GNU/Linux 2.6.15, stripped /usr/bin/zipgrep: POSIX shell script text executable /usr/bin/zipinfo: ELF 32-bit LSB executable, Intel 80386, version 1 (SYSV), dynamically linked (uses shared libs), for GNU/Linux 2.6.15, stripped /usr/bin/zipnote: ELF 32-bit LSB executable, Intel 80386, version 1 (SYSV), dynamically linked (uses shared libs), for GNU/Linux 2.6.15, stripped /usr/bin/zipsplit: ELF 32-bit LSB executable, Intel 80386, version 1 (SYSV), dynamically linked (uses shared libs), for GNU/Linux 2.6.15, stripped

In this example, the results of the pipeline became the argument list of the file command. There is an alternate syntax for command substitution in older shell programs which is also supported in bash. It uses back-quotes instead of the dollar sign and parentheses:

[me@linuxbox me]$ ls -l `which cp` -rwxr-xr-x 1 root root 71516 2007-12-05 08:58 /bin/cp

Quoting

Now that we've seen how many ways the shell can perform expansions, it's time to learn how we can control it. Take for example:

[me@linuxbox me]$ echo this is a test this is a test

or:

[me@linuxbox me]$ [me@linuxbox ~]$ echo The total is $100.00 The total is 00.00

In the first example, word-splitting by the shell removed extra whitespace from the echo command's list of arguments. In the second example, parameter expansion substituted an

ll provides a mechanism called quoting to selectively suppress unwanted expansions.

DoubleQuotes

The first type of quoting we will look at is double quotes. If you place text inside double quotes, all the special characters used by the shell lose their special meaning and are treated

\ - quote). This means that word-splitting, pathname expansion, tilde expansion, and brace expansion are suppressed, but parameter expansion, arithmetic expansion, and command substitution are still carried out. Using double quotes, we can cope with filenames containing embedded spaces. Say you were the unfortunate victim of a file called two words.txt. If you tried to use

Page 88: Ecw course

this on the command line, word-splitting would cause this to be treated as two separate arguments rather than the desired single argument:

[me@linuxbox me]$ ls -l two words.txt

ls: cannot access two: No such file or directory ls: cannot access words.txt: No such file or directory

By using double quotes, you can stop the word-splitting and get the desired result; further, you can even repair the damage:

[me@linuxbox me]$ ls -l "two words.txt" -rw-rw-r-- 1 me me 18 2008-02-20 13:03 two words.txt [me@linuxbox me]$ mv "two words.txt" two_words.txt

There! Now we don't have to keep typing those pesky double quotes. Remember, parameter expansion, arithmetic expansion, and command substitution still take place within double quotes:

[me@linuxbox me]$ echo "$USER $((2+2)) $(cal)"

me 4 February 2008 Su Mo Tu We Th Fr Sa 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29

We should take a moment to look at the effect of double quotes on command substitution. First let's look a little deeper at how word splitting works. In our earlier example, we saw how word-splitting appears to remove extra spaces in our text:

[me@linuxbox me]$ echo this is a test this is a test

By default, word-splitting looks for the presence of spaces, tabs, and newlines (linefeed characters) and treats them as delimiters between words. This means that unquoted spaces, tabs, and newlines are not considered to be part of the text. They only serve as separators. Since they separate the words into different arguments, our example command line contains a command followed by four distinct arguments. If we add double quotes:

[me@linuxbox me]$ echo "this is a test" this is a test

word-splitting is suppressed and the embedded spaces are not treated as delimiters, rather they become part of the argument. Once the double quotes are added, our command line contains a command followed by a single argument. The fact that newlines are considered delimiters by the word-splitting mechanism causes an interesting, albeit subtle, effect on command substitution. Consider the following:

[me@linuxbox me]$ echo $(cal) February 2008 Su Mo Tu We Th Fr Sa 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16

Page 89: Ecw course

17 18 19 20 21 22 23 24 25 26 27 28 29 [me@linuxbox me]$ echo "$(cal)"

February 2008 Su Mo Tu We Th Fr Sa 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29

In the first instance, the unquoted command substitution resulted in a command line containing thirty-eight arguments. In the second, a command line with one argument that includes the embedded spaces and newlines.

SingleQuotes

If you need to suppress all expansions, you use single quotes. Here is a comparison of unquoted, double quotes, and single quotes:

[me@linuxbox me]$ echo text ~/*.txt {a,b} $(echo foo) $((2+2)) $USER text /home/me/ls-output.txt a b foo 4 me [me@linuxbox me]$ echo "text ~/*.txt {a,b} $(echo foo) $((2+2)) $USER" text ~/*.txt {a,b} foo 4 me [me@linuxbox me]$ echo 'text ~/*.txt {a,b} $(echo foo) $((2+2)) $USER' text ~/*.txt {a,b} $(echo foo) $((2+2)) $USER

As you can see, with each succeeding level of quoting, more and more of the expansions are suppressed.

EscapingCharacters

Sometimes you only want to quote a single character. To do this, you can precede a character with a backslash, which in this context is called the escape character. Often this is done inside double quotes to selectively prevent an expansion:

[me@linuxbox me]$ echo "The balance for user $USER is: \$5.00" The balance for user me is: $5.00

It is also common to use escaping to eliminate the special meaning of a character in a filename. For example, it is possible to use characters in filenames that normally have special meaning to the shell. These would character in a filename you can to this:

[me@linuxbox me]$ mv bad\&filename good_filename

\\quotes, the backslash loses its special meaning and is treated as an ordinary character.

Page 90: Ecw course

MoreBackslashTricks

If you look at the man pages for any program written by the GNU project, you will notice that in addition to command line options consisting of a dash and a single letter, there are also long option names that begin with two dashes. For example, the following are equivalent:

ls -r ls --reverse

Why do they support both? The short form is for lazy typists on the command line and the long form is mostly for scripts though some options may only be long form. I sometimes use obscure options, and I find the long form useful if I have to review a script again months after I wrote it. Seeing the long form helps me understand what the option does, saving me a trip to the man page. A little more typing now, a lot less work later. Laziness is maintained.

As you might suspect, using the long form options can make a single command line very long. To combat this problem, you can use a backslash to get the shell to ignore a newline character like this:

ls -l \ --reverse \ --human-readable \ --full-time

Using the backslash in this way allows us to embed newlines in our command. Note that for this trick to work, the newline must be typed immediately after the backslash. If you put a space after the backslash, the space will be ignored, not the newline. Backslashes are also used to insert special characters into our text. These are called backslash escape characters. Here are the common ones:

Escape Character Name Possible Uses

\n newline Adding blank lines to text

\t tab Inserting horizontal tabs to text

\a alert Makes your terminal beep

\\ backslash Inserts a backslash

\f formfeed Sending this to your printer ejects the page

The use of the backslash escape characters is very common. This idea first appeared in the C programming language. Today, the shell, C++, perl, python, awk, tcl, and many other programming languages use this concept. Using the echo command with the -e option will allow us to demonstrate:

[me@linuxbox me]$ echo -e "Inserting several blank lines\n\n\n" Inserting several blank lines

Page 91: Ecw course

[me@linuxbox me]$ echo -e "Words\tseparated\tby\thorizontal\ttabs."

Words separated by horizontal tabs [me@linuxbox me]$ echo -e "\aMy computer went \"beep\"." My computer went "beep". [me@linuxbox me]$ echo -e "DEL C:\\WIN2K\\LEGACY_OS.EXE" DEL C:\WIN2K\LEGACY_OS.EXE

Permissions

The Unix-like operating systems, such as Linux differ from other computing systems in that they are not only multitasking but also multi-user.

What exactly does this mean? It means that more than one user can be operating the computer at the same time. While your computer only has one keyboard and monitor, it can still be used by more than one user. For example, if your computer is attached to a network, or the Internet, remote users can log in via ssh (secure shell) and operate the computer. In fact, remote users can execute graphical applications and have the output displayed on a remote computer. The X Window system supports this.

The multi-user capability of Unix-like systems is a feature that is deeply ingrained into the design of the operating system. If you remember the environment in which Unix was created, this makes perfect sense. Years ago before computers were "personal," they were large, expensive, and centralized. A typical university computer system consisted of a large mainframe computer located in some building on campus and terminals were located throughout the campus, each connected to the large central computer. The computer would support many users at the same time.

In order to make this practical, a method had to be devised to protect the users from each other. After all, you could not allow the actions of one user to crash the computer, nor could you allow one user to interfere with the files belonging to another user.

This lesson will cover the following commands:

chmod - modify file access rights su - temporarily become the superuser sudo - temporarily become the superuser chown - change file ownership chgrp - change a file's group ownership

Page 92: Ecw course

FilePermissions

On a Linux system, each file and directory is assigned access rights for the owner of the file, the members of a group of related users, and everybody else. Rights can be assigned to read a file, to write a file, and to execute a file (i.e., run the file as a program).

To see the permission settings for a file, we can use the ls command. As an example, we will look at the bash program which is located in the /bin directory:

[me@linuxbox me]$ ls -l /bin/bash

-rwxr-xr-x 1 root root 316848 Feb 27 2000 /bin/bash

Here we can see:

The file "/bin/bash" is owned by user "root" The superuser has the right to read, write, and execute this file The file is owned by the group "root" Members of the group "root" can also read and execute this file Everybody else can read and execute this file

In the diagram below, we see how the first portion of the listing is interpreted. It consists of a character indicating the file type, followed by three sets of three characters that convey the reading, writing and execution permission for the owner, group, and everybody else.

Page 93: Ecw course

chmod

The chmod command is used to change the permissions of a file or directory. To use it, you specify the desired permission settings and the file or files that you wish to modify. There are two ways to specify the permissions. In this lesson we will focus on one of these, called the octal notation method.

It is easy to think of the permission settings as a series of bits (which is how the computer thinks about them). Here's how it works:

rwx rwx rwx = 111 111 111 rw- rw- rw- = 110 110 110 rwx --- --- = 111 000 000 and so on... rwx = 111 in binary = 7 rw- = 110 in binary = 6 r-x = 101 in binary = 5 r-- = 100 in binary = 4

Now, if you represent each of the three sets of permissions (owner, group, and other) as a single digit, you have a pretty convenient way of expressing the possible permissions settings. For example, if we wanted to set some_file to have read and write permission for the owner, but wanted to keep the file private from others, we would:

[me@linuxbox me]$ chmod 600 some_file

Here is a table of numbers that covers all the common settings. The ones beginning with "7" are used with programs (since they enable execution) and the rest are for other kinds of files.

Value Meaning

777 (rwxrwxrwx) No restrictions on permissions. Anybody may do anything. Generally not a desirable setting.

755 (rwxr-xr-x) The file's owner may read, write, and execute the file. All others may read and execute the file. This setting is common for programs that are used by all users.

700 (rwx------) The file's owner may read, write, and execute the file. Nobody else has any rights. This setting is useful for programs that only the owner may use and must be kept private from others.

666 (rw-rw-rw-) All users may read and write the file.

644 (rw-r--r--) The owner may read and write a file, while all others may only read the file. A common setting for data files that everybody may read, but only the owner may change.

Page 94: Ecw course

600 (rw-------) The owner may read and write a file. All others have no rights. A common setting for data files that the owner wants to keep private.

DirectoryPermissions

The chmod command can also be used to control the access permissions for directories. Again, we can use the octal notation to set permissions, but the meaning of the r, w, and x attributes is different:

r - Allows the contents of the directory to be listed if the x attribute is also set. w - Allows files within the directory to be created, deleted, or renamed if the x attribute is

also set. x - Allows a directory to be entered (i.e. cd dir).

Here are some useful settings for directories:

Value Meaning

777 (rwxrwxrwx) No restrictions on permissions. Anybody may list files, create new files in the directory and delete files in the directory. Generally not a good setting.

755 (rwxr-xr-x) The directory owner has full access. All others may list the directory, but cannot create files nor delete them. This setting is common for directories that you wish to share with other users.

700 (rwx------) The directory owner has full access. Nobody else has any rights. This setting is useful for directories that only the owner may use and must be kept private from others.

BecomingTheSuperuserForAShortWhile

It is often necessary to become the superuser to perform important system administration tasks, but as you have been warned, you should not stay logged in as the superuser. In most distributions, there is a program that can give you temporary access to the superuser's privileges. This program is called su (short for substitute user) and can be used in those cases when you need to be the superuser for a small number of tasks. To become the superuser, simply type the su command. You will be prompted for the superuser's password:

[me@linuxbox me]$ su Password: [root@linuxbox me]#

After executing the su command, you have a new shell session as the superuser. To exit the superuser session, type exit and you will return to your previous session.

In some distributions, most notably Ubuntu, an alternate method is used. Rather than using su, these systems employ the sudo command instead. With sudo, one or more users are granted superuser privileges on an as needed basis. To execute a command as the superuser,

Page 95: Ecw course

the desired command is simply preceeded with the sudo command. After the command is entered, the user is prompted for the user's password rather than the superuser's:

[me@linuxbox me]$ sudo some_command Password: [me@linuxbox me]$

ChangingFileOwnership

You can change the owner of a file by using the chown command. Here's an example: Suppose I wanted to change the owner of some_file from "me" to "you". I could:

[me@linuxbox me]$ su Password: [root@linuxbox me]# chown you some_file [root@linuxbox me]# exit [me@linuxbox me]$

Notice that in order to change the owner of a file, you must be the superuser. To do this, our example employed the su command, then we executed chown, and finally we typed exit to return to our previous session.

chown works the same way on directories as it does on files.

ChangingGroupOwnership

The group ownership of a file or directory may be changed with chgrp. This command is used like this:

[me@linuxbox me]$ chgrp new_group some_file

In the example above, we changed the group ownership of some_file from its previous group to "new_group". You must be the owner of the file or directory to perform a chgrp.

JobControl

In the previous lesson, we looked at some of the implications of Linux being a multi-user operating system. In this lesson, we will examine the multitasking nature of Linux, and how this is manipulated with the command line interface.

As with any multitasking operating system, Linux executes multiple, simultaneous processes. Well, they appear simultaneous, anyway. Actually, a single processor computer can only execute one process at a time but the Linux kernel manages to give each process its turn at the processor and each appears to be running at the same time.

There are several commands that can be used to control processes. They are:

Page 96: Ecw course

ps - list the processes running on the system kill - send a signal to one or more processes (usually to "kill" a process) jobs - an alternate way of listing your own processes bg - put a process in the background fg - put a process in the forground

APracticalExample

While it may seem that this subject is rather obscure, it can be very practical for the average user who mostly works with the graphical user interface. You might not know this, but most (if not all) of the graphical programs can be launched from the command line. Here's an example: there is a small program supplied with the X Window system called xload which displays a graph representing system load. You can excute this program by typing the following:

[me@linuxbox me]$ xload

Notice that the small xload window appears and begins to display the system load graph. Notice also that your prompt did not reappear after the program launched. The shell is waiting for the program to finish before control returns to you. If you close the xload window, the xload program terminates and the prompt returns.

PuttingAProgramInTheBackground

Now, in order to make life a little easier, we are going to launch the xload program again, but this time we will put it in the background so that the prompt will return. To do this, we execute xload like this:

[me@linuxbox me]$ xload & [1] 1223

[me@linuxbox me]$

In this case, the prompt returned because the process was put in the background.

Now imagine that you forgot to use the "&" symbol to put the program into the background. There is still hope. You can type Ctrl-z and the process will be suspended. The process still exists, but is idle. To resume the process in the background, type the bg command (short for background). Here is an example:

[me@linuxbox me]$ xload [2]+ Stopped xload

[me@linuxbox me]$ bg [2]+ xload &

Page 97: Ecw course

ListingYourProcesses

Now that we have a process in the background, it would be helpful to display a list of the processes we have launched. To do this, we can use either the jobs command or the more powerful ps command.

[me@linuxbox me]$ jobs [1]+ Running xload &

[me@linuxbox me]$ ps PID TTY TIME CMD 1211 pts/4 00:00:00 bash 1246 pts/4 00:00:00 xload 1247 pts/4 00:00:00 ps

[me@linuxbox me]$

KillingAProcess

Suppose that you have a program that becomes unresponsive; how do you get rid of it? You use the kill command, of course. Let's try this out on xload. First, you need to identify the process you want to kill. You can use either jobs or ps, to do this. If you use jobs you will get back a job number. With ps, you are given a process id (PID). We will do it both ways:

[me@linuxbox me]$ xload & [1] 1292

[me@linuxbox me]$ jobs [1]+ Running xload &

[me@linuxbox me]$ kill %1

[me@linuxbox me]$ xload & [2] 1293 [1] Terminated xload

[me@linuxbox me]$ ps PID TTY TIME CMD 1280 pts/5 00:00:00 bash 1293 pts/5 00:00:00 xload 1294 pts/5 00:00:00 ps

[me@linuxbox me]$ kill 1293 [2]+ Terminated xload

[me@linuxbox me]$

ALittleMoreAboutkill

While the kill command is used to "kill" processes, its real purpose is to send signals to processes. Most of the time the signal is intended to tell the process to go away, but there is more to it than that. Programs (if they are properly written) listen for signals from the operating system and respond to them, most often to allow some graceful method of

Page 98: Ecw course

terminating. For example, a text editor might listen for any signal that indicates that the user is logging off, or that the computer is shutting down. When it receives this signal, it saves the work in progress before it exits. The kill command can send a variety of signals to processes. Typing:

kill -l

will give you a list of the signals it supports. Most are rather obscure, but several are useful to know:

Signal # Name Description

1 SIGHUP Hang up signal. Programs can listen for this signal and act upon it. This signal is sent to processes running in a terminal when you close the terminal.

2 SIGINT Interrupt signal. This signal is given to processes to interrupt them. Programs can process this signal and act upon it. You can also issue this signal directly by typing Ctrl-c in the terminal window where the program is running.

15 SIGTERM Termination signal. This signal is given to processes to terminate them. Again, programs can process this signal and act upon it. This is the default signal sent by the kill command if no signal is specified.

9 SIGKILL Kill signal. This signal causes the immediate termination of the process by the Linux kernel. Programs cannot listen for this signal.

Now let's suppose that you have a program that is hopelessly hung and you want to get rid of it. Here's what you do:

1. Use the ps command to get the process id (PID) of the process you want to terminate. 2. Issue a kill command for that PID. 3. If the process refuses to terminate (i.e., it is ignoring the signal), send increasingly harsh

signals until it does terminate.

[me@linuxbox me]$ ps x | grep bad_program PID TTY STAT TIME COMMAND 2931 pts/5 SN 0:00 bad_program

[me@linuxbox me]$ kill -SIGTERM 2931

[me@linuxbox me]$ kill -SIGKILL 2931

In the example above I used the ps command with the x option to list all of my processes (even those not launched from the current terminal). In addition, I piped the output of the ps command into grep to list only list the program I was interested in. Next, I used kill to issue a SIGTERM signal to the troublesome program. In actual practice, it is more common to do it in the following way since the default signal sent by kill is SIGTERM and kill can also use the signal number instead of the signal name:

Page 99: Ecw course

[me@linuxbox me]$ kill 2931

Then, if the process does not terminate, force it with the SIGKILL signal:

[me@linuxbox me]$ kill -9 2931

That'sIt!

This concludes the "Learning the shell" series of lessons. In the next series, "Writing shell scripts," we will look at how to automate tasks with the shell.