Download as pdf
Download as pdf
You are on page 1of 38
Chapter 04 INTRODUCTION TO LINUX 4.1 INTRODUCTION TO LINUX OPERATING SYSTEM Linux is a UNIX-base operating system. Its original creator was a Finnish student name Linus Torvalds, although being ‘open source’ it has change a great deal since its original conception. It belongs to nobody, and is free to download and use. Any changes to it are open for all to adopt, and as a result it has developed into a very powerful OS that is rapidly gaining in popularity worldwide, particularly among those seeking an alternative to Windows. In 1991, hardware was expanding rapidly, and DOS was the king of operating systems. Software development was slower, and Macs, while better, were also much pricier than PCs. UNIX was growing, but at that time in its history the source code was jealously guarded and expensive to use. Linus Torvalds was a Helsinki university student who liked playing around with software and computers, and in 1991 he announced the creation of a new core operating system that he had named Linux. It is now one of the most used systems for the PC, and is particularly suitable for businesses with small IT budgets. Linux is free to use and install, and is more reliable than almost all other systems, running for many months and even years without a reboot being necessary. Open Source §; 2 nefits of Linux d Bi vantages an 4.1.4 At «enificant benefits of open source software such e sigh no owner, it can be debugged Withoy wner or software proprietor. Businesses therefore ry wish with the OS without having lex license agreements. One of th Linux is that because it has resource toa license 0 have the flexibility to do as the: worry about conforming to comp! The major advantage of Linux is its cost: ‘c end i8 fee, while many software applications also come _ a General public License. It can also be used simultaneously by large umber of users without slowing down or freezing and it is very fast. It is an excellent networking platform and performs at optimum efficiency even with little available hard disk space. Linux also runs on a wide range of hardware types, including PCs, Macs, mainframes, supercomputers, some cell phones and industrial robots. Some prefer to dual-boot Linux and Windows while others prefer Linux and Mac OS. System76 machines come pre- installed with Linux in the form of Ubuntu, a Debian distribution of Linux. This is the most popular distribution of Linux for laptops. Linux Vs Windows The main benefits and advantages of Linux over other operating systems, particularly Microsoft Windows, are: % — Itis free to use and distribute, * — Support is free through online help sites, blogs and forums. Pe fe ; Itis very reliable more so than most other operating systems with very few crashes, * Ah uge amount of free open source software has been developed for it. * It is very Tesistant to malware viruses, * Introduction to Linux 43 %* — Since the source code is visible, ‘backdoors’ are easily spotted, so Linux offers greater security for sensitive applications. %* — Linux offers a high degree of flexibility of configuration, and significant customization is possible without modifying the source code. The Linux operating system is widely use by both home and business users, and its usage is increasing daily. It is considered that Linux will eventually overtake Microsoft Windows as the most popular operating system, which could also open the door further for more free software such as Open Office, The Gimp, Paint, Thunderbird, Firefox and Scribus. It is easy to install and run alongside your existing operating system, so give it a try, because it is also easy to remove if you don’t like it~ which is unlikely. 4.2 LINUX ESSENTIAL COMMANDS 4.2.1 Commands For Beginners $>clear This is the command to clear screen. This command is also useful when you have to type long commands, which can confuse the users to see different details over the screen. Sls Shows list of files and directories. This has many options to see different types of files and it also supports wild cards. %* — Show all files in current directory Is * — Show all files in a directory /mydir/some/path Is /mydir/some/path * Display details of all file in the list Open Source Softwar, ee Is-l including the files nai 1 (including IME Stary E hidden files a8 We x Display all with a do ) Is-a ith my, x Display all file that have names starting W! y. Is my* $>ed Used to change directory + Goto the home directory of logged in user cd * Gotoa specific directory named /mydir/some/path cd /mydire/ some/path sep Copy a file or directory from one location to another. * Copy a file name file] with name file2 cp file] file2 %* — Copy the directory name dirl to dir2 cp -rdirl dir2 $>mkdir Create one or more directories * Create a directory named mydirecory mkdir mydirectory * Create 3 directories name dir], dir2 and dir3 mkdir dirl dir2 dir3 $>man Used to read more detail: is about how to use any command Introduction to Linux 4.5 sie smile a You can always use this command to explore more options supported by a command. %* Show help for Is command man Is * Show help for grep command man grep $>mv - Rename command * © Used for renaming a file or directory. * Rename file! to file2 * — myfile! file2 4.2.2 System Information $>date The command to see current date or set system date/time Display current date $>date * — Set current system date to “June 20, 1985, 5:27 PM” date 0620172785 %* ~The command for checking available disc space. * — It helps in offering you the status of file system disk space over your Linux based system. af-h S>du Display disk space use by each file in the file system * — Display disk usage by each file in Documents directory du -h Documents 4.6 ; whole Documents di % Display dis! : mesouy dom Documents usage by th g>top Display the te and cpu utilization. * Display all top ™u a Display all top running top -U fromdev op running processes on the system with etna processes top processes from user fromdey ning $>ps Show the status of running processes * Display all running process status for current user | ps * Display the list of all running processes on system with th status. _ ps -al $>uname Find infc i i information about version and details of operating system uname -@ 4.2.3 File Operations S>gzip This command wi will compress in gzi oes a file in gzip format. $>gunzip Uncompress th ‘ he gzip fil gunzip filel.gz oe S>tail Display las t few lines content updates on log file contents of a file, Very useful to watch Introduction to Linux 4.7 *& = = Watch running content of a logfile name logfile! tail -f logfile1 %* — Display last 100 lines of a file name myfile tail -100 myfile $>sep * = Copy a file to or from a remote host %* ~~ Copy the file “myfile.txt” from a remote host to the local host * scp your_username@remote-server:foobar.txt /path/to/local/ directory %* — Copy a local file myfile.txt to remote server * ~~ scp myfile.txt your_username@remote-server:/path/to/copy/ %* Copy the directory “mydir” from the local host to a remote host’s directory “myremotedir” * scp -r mydir your_username@remote-server:/path/to/remote/ directory/myremotedir $>sftp This can be used for doing file transfer using secure ftp protocol. To open a sftp command prompt on a sftp server try this sfip your_username@remote-server $>cat Used to display the content of the file on console without opening it in a editor. cat myfile $>more Used to display the content of a file on console with option to navigate in case the content is too large to fit in screen, more myfile 48 S$>find Find a file or directory on the system using this command i cure! ‘ory and its subdi j * Find a file myfile.txt in current directory directories find . -name “myfile.txt” *® Find all files in Documents directory that are larger that 25MR In size find . -size +25M -exec du -h {} \; %* Find all .doc files on the system that have been modified in the last 5 days. find . name “*.doc” ~mtime -5 * Find all .txt files on the system that were modified in last js minutes find . —name “* txt” —mmin -15 | Find all files that contain a string “I am inside file”, find . -name “*” -exec grep -i -H “I am inside file” Os $>grep This command is used to search specified location containing a string. * all the lines in all files ina Search for a specific string “myname” in a file myfile.txt grep “myname” myfile.txt Search for a specific string “ myname” with ignoring the cas¢ ina file myfile.txt grep -i “myname” myfile.txt %* Search for a Specific strin, b 8 “myname” in a all files in current directory grep “myname” * Search for full word “myword” in a file myfile.txt j Introduction to Linux 49 grep -w “myword” myfile.txt % Search a string “myname” in all files in all subdirectories recursively grep -r “myname” * $>rm Remove a file or directory using this command. %* Remove a file name myfile.txt rm myfile.txt %* Remove a directory mydir rm -r mydir %* Remove a file myfile.txt forcefully rm -f myfile.txt $>chmod The command for manipulating the file permissions. For better security, the permissions for file in Linux OS are categorized into different groups, users and other sections. You have the option of controlling the permissions by assigning the users under the given divisions via the command of ‘chmod’. These permissions would help the users to write, read and execute the respective files. With the command of ‘chmod +x’ you could end up making the script executable over your Linux system. %* Provide execute permission on a file myfile.txt to all users chmod +x myfile.txt %* Provide read permission on a file myfile.txt to all users chmod +r myfile.txt %* Provide full permissions (read/write/execute) on a file myfile. txt to yourself but everyone else has only read and execute chmod 755 myfile.txt Open Source Soy 4.10 % Provide full pe txt to everyone : chmod 777 myfile-tx ite/execute) ON a fijp mh sini read/ wil! missions ( $>chown Change . of the file to successfully run thi Id be either root or theo i file. You shou! ng ownership of a is command. the ownership of a file myfile.txt to another_user Who Change the up part of another_grot oy chown another_user:another_group myfile. i i mydirl recursive}, , Change the ownership of a directory my sively , another_user who is part of another_group chown -R another_user:another_group mydirl 4.3 LINUX FILE SYSTEM CONCEPT AND STANDARD FILES The Linux file system is a hierarchically structured tree wher every location has its distinct meaning. The file system structure j Standardized through the file system hierarchy standard of whic you'll find this chapter to be a description off. Lately however, mog and more distributions are making a small change towards their fik system layout (but all Consistent) so the standard is i When a setting deviates from t chapter. Of course, a file System is always stored on media (be it a hal Ory fragment); how these media relate to Sorts of files Most files ate just files, calles data, for example text file, output from a Program an 4d regular files; they contain nom! table files or Programs, input for | S, €xecut id so on, Introduction to Linux 4.1 While it i: Is -1 total 80 -tw-rw-t- | jaime jaime 31744 Feb 21 17:56 intro Linux.doc -tw-tw-t-- 1 jaime jaime 41472 Feb 21 17:56 Linux.doc drwxrwxr-x 2 jaime jaime 4096 Feb 25 11:50 course This table gives an overview of the characters determining the file type: Table 4.1. File types in a long list Symbol Meaning e Regular file [Directory _| Link Special file Socket |Named pipe _| Block device ny Structure The file system is a tree which coincidentally is called ¢ J as being above all other, is ident the highest place you can go to. Ben: directories: ~$cd/ ~$ ls -F bin’ home/ opt/ srv/_ var! boot/ lib/ proc/ sys/ dev/ media/ root/ tmp/ etc/ mnt/— sbin/ — usr/ The Is -F commands shows the content of the root location by appends an additional character to special files. For instance, it append a “7” to directories, an “@’ to symbolic links and a “*” to execute files. A popular way of representing the file system is through a tree. 4s example would be for the top level: ih +- bin/ +- boot/ +- dev/ +- ete/ +- home/ +- lib/ +- media/ +- mnt/ +- opt/ ++ proc/ +- root/ +- sbin/ +. sry/ + sys/ ++ tmp/ -shaped structure. The root of the he file system root but is always dens fied by the slash charact eath it are almost always Introduction to Lit 4.13 +. usr/ * var/ The more you descend, the larger the tree becomes and it will soon be too difficult to put it on a single view. Still, the tree format isa good way of representing the file system because it shows you exactly how the file system looks like. +- bin/ tens +- home/ | +- thomas/ +- Documents/ +- Movies/ +- Music/ +- Pictures/ <-- You are here | | = Backgrounds/ | | ‘= opentasks.txt | +-jane/ | “= jack/ +- lib/ +. | | | | | *- var/ To know Backgrounds directory you would type “ed Backgrounds”. To ascend back (to /home/thomas) you would type “cd ..” (.. being short for “parent directory”). 4.3.1 Mounting File Systems The root of a file system is stored somewhere. Most of the time, it is stored on a partition of a disk. In many cases you would want to combine multiple partitions for a single file system. Combining one partition with the file system is called mounting a file system. Your file system is always seen as a tree structure, but parts of a tree (a branch) can be located on a different partition, disk or even other medium (network storage, DVD, USB stick. Mounting oe the root of a file system stored on avi stored on another. This 4 hat all the users’ files ae stor aS Woy ne - ‘i everything beneath it, is on one pi Pt /hy mean that /, an i second one. \d everything beneath that, which is on a s cS _____—_ Suppose that you hi ‘Ome = yo | | Portion A +- boot/ \/ — i | +- bin +-usr/ | Fig 4.1. Two partitions used for the file system Structure The mount command by itself, without any arguments, shows you a list of mounted file systems: $ mount /dev/sda8 on / type ext3 (rw,noatime) Proc on /proc dpe proc (rw) sysfs on bys Ype sysfs (wnosuid, nodey,noexec,relatime) udev on/dev Ypedevimpfs (ry nosuid relatime,size= |} 0240k, mode=755) devpts on /devipts type — devpls (wnosuid, noexec,relatime.gid=5, mode=620) /dev/sda7 on /home Ype ext3 (rw, noatime) none on /dev/shm Spe tmpfy (rw) /dev/sdal on /mnt/data Pee ienoay ») : ,Noatime, j usb on ‘Prochous/ysh sh (rwnoexec, Nosuid devmod i *0664,deveid=gs 5) Introduction to Linux 4.15 The concept of mounting allows programs to be agnostic about where your data is structured. From an application (or user) point of view, the file system is one tree. Under the hood, the file system structure can be on a single partition, but also on a dozen partitions, network storage, removable media and more. 4.3.2 File Systems Linux however doesn’t require its partitions to have one possible file system (like “only NTFS is supported”): as long as it understands it and the file system supports things like ownership and permissions, you are free to choose whatever file system you want. In fact, during most distribution installations, you are asked which file system to choose. The following is a small list of popular file systems around, each with a brief explanation on its advantages and disadvantages... * The ex? file system is Linux’ old, yet still used file system. It stands for extended 2 file system and is quite simple. It has been in use almost since the birth of Linux and is quite resilient against file system fragmentation - although this is true for almost all Linux file systems. It is however slowly being replaced by journaled file systems. * The ext3 file system is an improvement on the ex/2 file system, adding, amongst other things, the concept of journaling. % The ext4 file system is an improvement on the ex/3 file system, adding, amongst other things, support for very large file systems/ files, extents (contiguous physical blocks), pre-allocation and delayed allocation and more. The ex?4 file system is backwards compatible with ext3 as long as you do not use extents. Ext4 is frequently seen as the default file system of choice amongst administrators and distributions. %* The reiserfs file system is written from scratch. It provides journaling as well, but its main focus is on speed. The file system provides quick access to locations with hundreds of files inside (ext2 and ext3 are much slower in these situations) Open Source Softy Footpri all fil me o the dis a ie for every file, rire a several files). Although uite Populg able to share ae ‘tie file system has been seeing a lack ; throu: A : popular years (harmful bugs Stayed in shppore roug! and is not frequently advised by distribution, quite some mae reiser4, is still quite premature and ig tie cae Teal of the main developer Hans Reise a ae developed that actively any more. * — The birfs file system is a promising file system. It addresses concerns regarding huge storage backend volumes, mult. device spanning, snapshotting and more. eatnouel its primary target was enterprise usage, it also offers interesting features to home users such as online grow/shrink (both on file system as well as underlying storage level), object-level redundaney transparent compression and cloning. and keep file systems fr a few years bi * The xf file system is an enterprise-ready, high performance journaling file system. It offers very high parallel throughput and is therefore a common choice amongst enterprises, * The zfs file system (ZFSonLinux system offering block-| snapshotting, volumes, ) is a multi-featured file evel checksumming, compression, copy-on-write, teduplication, extremely large » Smack and accepted modules in the offi 417 Introduction to Linux ee Design LSM was designed to provide the specific needs of everything needed to successfully implement a mandatory access control module, while imposing the fewest possible changes to the Linux kernel. LSM avoids the approach of system call interposition as used in Systrace because it does not scale to multiprocessor kernels and is subject to TOCTTOU (race) attacks. Instead, LSM inserts “hooks” (upcalls to. the module) at every point in the kernel where a user-level system call is about to result in access to an important internal kernel object such as inodes and task control blocks. The project is narrowly scoped to solve the problem of access control to avoid imposing a large and complex change patch on the mainstream kernel. It is not intended as a general “hook” or “upcall” mechanism, nor does it support Operating system-level virtualization. LSM’s access control goal is very closely related to the problem of system auditing, but is subtly different. Auditing requires that every attempt at access be recorded. LSM cannot deliver that, because it would require a great many more hooks, so as to detect cases where the kernel “short circuits” failing system calls and returns an error code before getting near significant objects. 4.4.1 Linux Security Modules The Linux Security Modules (LSM) API implements hooks at all security-critical points within the kernel. A user of the framework (an “LSM”) can register with the API and receive callbacks from these hooks. All security-.elevant information is safely passed to the LSM, avoiding race conditions, and the LSM may deny the operation. This is similar to the Netfilter hook-based API, although applied to the general kernel. The LSM API allows different security models to be plugged into the kernel typically access control frameworks. To ensure compatibility with existing applications, the LSM hooks are placed so that the Unix DAC checks are performed first, and only if they succeed, is LSM code invoked. } | | 5 ted into the mainline |; 4.18 en incorpor@ The following kernel: LSMs have bet ) is an implementatigg , (AC) designed to ,,.. . datory Access Control (M eneral purpos — aay ar security requirements, from 8 ye a wide range ©} t and military systems which manage class through to government ers from DAC in that the secu, information. MA ity diffe am sick 2 ‘ saw d users do not administer policy policy is administere centrally, an ; . their own resources. This we contain attacks which exploit userng software bugs and misconfiguration. In SELinux, all objects on the system, such as files and process are assigned security labels. All security-relevant interactions betwee; entities on the system are hooked by LSM and passed to the SELiny, module, which consults its security policy to determine whether tte operation should continue. The SELinux security policy is loaded from userland, and may be modified to meet a range of different security goals. Many previous MAC schemes had fixed policies, which limite! their application to general purpose computing. SELinux sis Security Enhanced Linux (S' SELinux is implemented as a standard feature in Fedora-basi distributions, and widely deployed, Smack The Smack LSM was desi security, in response to the rel; implemented as a label-bas Smack is part of the Tizen s generally in the embedded ned to provide a simple form of MAC ative complexity of SELinux. It's al ed scheme with a customizable polit! curity architecture and has seen adopt! Space, AppArmor AppArmor is a MAY iC designed to be simple to nn a ©onfining applications, and ¥® rofiles usi li . ABE. Policy j ae Profiles using familiar Unix-styte abs ce : soa as soni 'S Such as pathnames. ifferent to SELinux and curity policy is applied to pathnames. AppA\ avior of an fundame i labeling of objects, also features a learning mode, where the security beh application is observed and converted automatically into a security mor profile. AppArmor is shipped with Ubuntu and OpenSUSE, and is also widely deployed. TOMOYO The TOMOYO module is another MAC scheme which implements path-based security rather than object labeling. It’s also aimed at simplicity, by utilizing a learning mode similar to AppArmor’s where the behavior of the system is observed for the purpose of generating security policy. What's different about TOMOY 0 is that what’s recorded are trees of process invocation, described “domains”. For example, when the as series of tasks are invoked which lead to a system boots, from init, logged in user running a shell, and ultimately executing a command, say ping. This particular chain of tasks is recorded as a valid domain for the execution of that application, and other invocations which have not been recorded are denied. TOMOYO is intended for end users rather than system administrators, although it has not yet seen any appreciable adoption. Yama The Yama LSM is not an access control scheme like those described above. It’s where miscellaneous DAC security enhancements are collected, typically from external projects such as grsecurity. Currently, enhanced restrictions on ptrace are implemented in Yama, and the module may be stacked with other LSMs in a similar manner to the capabilities module. Open. Source Software — di bsystem. cive audit subsystem, 1 smel features @ com rehensive : The Linux kernel features a comp! fm requirements, government certifical : be useful. LSMs and other security t API. The userland components which was designed to meet actually turns out to ts utilize the kernel Audi are extensible and highly configurable. Audit logs are useful for analyzing syste! help detect attempts at compromising the system. but also component m behavior, and may Seccomp eccomp) is mechanism which restricts duce the attack access to system call: The idea is to reauce surface of the kernel by preventing applications from entering system calls they don’t need. The system call API is a wide gateway to the kernel, and as with all code, there have and are likely to be bugs present somewhere. Given the privileged nature of the kernel, bugs in system calls are potential avenues of attack. Ifan application only needs to use a limited number of system calls, then restricting it to only being able to invoke those calls reduces the overall risk of a successful attack. also known as “mode 1”, provided s: read, write, exit, and sigreturn. Secure computing mode (si is by processes. The original seccomp code, access to only four system call These are the minimum required for a useful application, and this was intended to be used to run untrusted code on otherwise idle systems. ‘A recent update to the code allows for arbitrary specification of which system calls are permitted for a process, and integration with audit logging. This “mode 2” seccomy p was developed fc of the Google Chrome OS. 7 Integrity Management : inane : aay management subsystem may be used 3 in eet of files on the system. The Integrity —anaaaeeionn na (MA) component performs runtime them with a list of a — ek . The list itself may be verified vi Introduction to Linux 4.21 ea ras an aggregate hash stored in the TPM. Measurements performed by IMA ae be logged via the audit subsystem, and also used for remote attestation, where an external system verifies their correctness. IMA may also be used for local integrity enforcement via the Appraisal extension. Valid measured hashes of files are stored as extended attributes with the files, and subsequently checked on access. These extended attributes (as well as other security-related extended attributes), are protected against offline attack by the Extended Verification Module (EVM) component, idealRy in conjunction with the TPM. Ifa file has been modified, IMA may be configured via policy to deny access to the file. The Digital Signature extension allows IMA to verify the authenticity of files in addition to integrity by checking RSA-signed measurement hashes. A simpler approach to integrity management is the dm-verity module. This is a device mapper target which manages file integrity at the block level. It’s intended to be used as part of a verified boot process, where an appropriately authorized caller brings a device online, say, a trusted partition containing kernel modules to be loaded later. The integrity of those modules will be transparently verified block by block as they are read from disk. Hardening and Platform Security Hardening techniques have been applied at various levels, including in the build chain and in software, to help reduce the risk of system compromise. Address Space Layout Randomization (ASLR) places various memory areas of a userland executable in random locations, which helps prevent certain classes of attacks. This was adapted from the external PaX/grsecurity projects, along with several other software- based hardening features. The Linux kernel also supports hardware security features where available, such as NX, VT-d, the TPM, TXT, and SMAP, along with cryptographic processing as previously mentioned. 4.22 Open Source Software 4.5 VIEDITOR This “vi* content is intended for those who wish to master and advance their skills beyond the basic features of the basic editor. It covers buffers, “vi” command line instructions interfacing with UNIX commands, and ctags. The vim editor is an enhanced version of vi. The improvements are clearly noticed in the handling of tags. learning it well is that one The advantage of learning vi and d it does not consume an will find vi on all Unix based systems an inordinate amount of system resources. vi works great over slow network ppp modem connections and on systems of limited resources, One can completely utilize vi without departing a single finger from the keyboard. (No hand to mouse and return to keyboard latency). A Beginner’s Guide to Editing Text Files With Vi RRO Vii pene a ee see tor editor included with most Linux systems. ia = led ome Vi provide a list of keyboard shortcuts on the . It’s a modal text editor, i an sate , and it has both an insert and command 4.5.1 Getting Started 11s a terminal application, so you'll have to start it from a jm terminal wind i ae ee 7 , ‘path/to/file command to open an existing 5 ath/to/file command alsi i Iso works if the file doesn’t Introduction to Linux 4.23 exist yet; Vi will c i y ill create a new file and write it to the specified location when you save. 4.5.2 Command Mode This is what you’ll see when you open a file in vi. It looks like you can just start typing, but you can’t, Vi is a modal text editor, and it opens in command mode. CERWIN RENAL While in command mode, you can move the cursor around with the arrow keys. Press the x key to delete the character under the cursor. There are a variety of other delete commands for example, typing dd (press the d key twice) deletes an entire line of text. Open Source Software ut and paste text in command mode, i ou want to copy or right side of the text y' ' : Py to select text, and then press y to our cursor at the desired 4 You can select, copy: Position the cursor at the left ! and press the v key. Move your curso! copy the selected text or X to cut it. nee hk pec a location and press the p key to paste the text y poe : Beene aig meena 9 cabrio an 4.5.3 Insert Mode A side from command mode, the other mode you need to know about is insert mode, which allows you to insert text in Vi. Entering insert mode is easy once you know it exists just press the i key once after you’ve positioned the cursor in command mode. Start typing and Vi will insert the characters you type into the file rather than trying to interpret them as commands. Once you’re done in insert mode, press the escape key to return to command mode. =e °F = | | Introduction to Linux 4.25 ieee You can save and quit vi from command mode. First, ensure you're in command mode by pressing the escape key .Type :wq and press enter to write the file to disk and quit vi. You can also split this - command up for example, type :w and press enter to write the file to disk without quitting or type :q to quit vi without saving the file. Vi won't let you quit if you've modified the file since you last saved, but you can type :q! and press enter to ignore this warning. ee ie kc ures 4.26 > feat j “vi ssuing the command: Vifile-to-eg, 4.5.4 Basic Pe 45 sadiein ¥0Y One edit three modes, command mode, inser Mo ‘The vi editor has ine mode. command lin oon Sueoce of leery ne je. 1. Command mo ee sensitive. The ESC key can s command vi. Comman' command. ode: Text is inserted. The ESC key ends insen 2, Insert m Saad mode. One can enter insert mode wig and — ya (insert after), “A” (insert at end of line), “0” (ope, “4” (insert), “a’ , a current line) or “O” (Open line above current line) co 3. Command line mode: One enters this mode by typing“ y puts the command line entry at the foot of the screen. Partial list of interactive commands: Cursor Movement Commands: Keystrokes Action hij/k/ Move cursor left/down/up/ri ight spacebar | Move Cursor right one space + Move cursor down/up in first column ctrl-d Scroll down one half of a screen, notrl-d | Set scroll to “n” lines. New default set for half scree in Scroll up one half of a Screen ctrl-u “oy Set scroll to lines. New default set for half sorte ctrl-f Scroll forward one Screen | netl-f | Scroy forward “n” screey n ctrl-b Scroll b; nea ‘ack one Screen Scroll back ae Screen Introduction to Linux 4,27 ctrl-y Scroll forward one line netrl-y Scroll forward “n” lines ctrl-e Scroll back one line netrl-e Scroll back “n” lines M (shift-m) | Move cursor to middle of page H (shift-h) | Move cursor to top of page L(shift-l) | Move cursor to bottom of page Ww Move cursor a word at a time (white space delimited) w Move cursor a word ata time (first non-alphanumeric) Sw Move cursor ahead 5 words B Move cursor back a word at a time (white space delimited) Move cursor back a word at a time (first non- 5b alphanumeric) Move cursor back 5 words E Move cursor to end of word (white space delimited) Move cursor to end of word (first non-alphanumeric) Se Move cursor ahead to the end of the Sth word 0 (zero) Move cursor to beginning of line :30 Move cursor to line thirty $ Move cursor to end of line ) Move cursor to beginning of next sentence (delimeted by“, “2” or “!”) iG Move cursor to beginning of current sentence } Move cursor to beginning of next paragraph (delimeted by blank line or nroff macros: .IP, .LP, .PP, .QP, .P, .LI and .bp) Also see “set paragraphs” to define a paragraph. Move cursor to beginning of current paragraph Open Source Software | Move cursor to beginning of next section (delimeted : by nroff macros: .NH, ‘SH, HH, HERG). AlgO 988 act sections” to define a section. - (l Move cursor to beginning of current section G Move cursor to end of file % Move cursor to the matching bracket. = Move cursor to previously modified line. m Mark the line on which the cursor resides. Marking requires an identifier. . Mark the line as identified by the letter “a by marking with keystroke “ma” ‘a Move cursor to line mark “a” generated by marking with keystroke “ma’ ‘A Move cursor to line mark “A” (global between buffers) generated by marking with keystroke “mA” I: Move cursor to next lower case mark. C Move cursor to previous lower case mark. Place cursor on {}[]( and type “%”. Use the matchit or xmledit plug-in to extend this capability to XML/ XHTML tags. Editing Commands: Keystrokes Action i Insert at cursor, Puts you in insert mode. Must use ese key to terminate insert mode. Insi ert before the cursor. Puts you in insert mode. M : ust use esc key to terminate insert mode Appen — cursor, Puts you in insert mode. Must €y to terminate insert mode. Introduction to Linux 4.29 A Append at end of line. Puts you in insert mode. Must use esc key to terminate insert mode. ° Open a new line below the current cursor position. Also puts you in insert mode. Must use esc key to terminate insert mode. oO Open a new line above the current line. Also puts you in insert mode. Must use esc key to terminate insert mode. ESC Terminate insert mode. Terminates most other modes as well. u Undo last change U Undo all changes to entire line dd Delete line (stored in local buffer) 3dd Delete 3 lines (stored in local buffer). D Delete contents of line after cursor c Delete contents of line after cursor and insert new text. Press esc key to end insertion. dw Delete word daw Delete 4 words Delete to end of sentence 4d) Delete all characters from cursor to end of line d$ Delete current and previous line Delete from cursor to first occurance of the letter “x” ¢ Delete from the current line to the line marked with dfx the identifier “x” dx Delete from the line of mark “a” to the line marked “p”, A ae Delete all characters from the cursor to the next d/cat occurance of (but not including) “cat” cw Change word c) Change sentence c$ Change from cursor to end of line Open Source Software 4.30 x Delete c! ter at cursor Xx Delete character before cursor al Y or yy | Yank (copy) current line into “unnamed” storage | buffer. - p Paste unnamed storage buffer after current line. | P Paste unnamed storage buffer before current line. i Replace character | R Overwrite characters from cursor onward | s Substitute one character under cursor continue to insert Ss Substitute entire line and begin to insert at beginning | of line J Join current and following line into one line | = Change case of individual character ctrl-a Increment number under the cursor. ctrl-x Decrement number under the cursor. repeat last command action. 4.5.5 Control Characters Note that to enter control characters while in insert mode, prefix the the control character with “ctrl-v” and then type the control character (ex. Carriage control: ctrl-M, Form feed: ctrl-L, Backspace: ctrl-H, Delete: ctrl-P, ...). Each control character must first be preceeded by ctrl-v while in insert mode. Delete/Restore Buffers Each time you delete or yank a line, it is stored in a local buffer and can be recalled and pasted, See “ vi line buffers” examples below. Introduction to Linux Search Commands Keystrokes /search_string {CR} Action Search for search strins Ysearch_string{CR} Search backwards (up in file) for search_ String | INS Seat eh string\> {CR} Search for search_word Ex: /\ Search for variable “s” but ignore declaration “string” or words containing S”. This will find “string s;”, “s = fn(x);”, = fn(s);”, ete Find next occurrence of search _word Find previous occurrence of search_word Move cursor to first occurance of letter “x” after the cursor but in the same line Move cursor to “n”th occurance of letter “x” in line Go to next occurance in line Move cursor backwards to next occurance of letter “x” in line Move cursor backwards to “nth occurance of letter “x” in line Go to previous occurance in line nx | Tx nTx Move cursor to one char before the next occurance of letter “x” in line Move cursor to one char before the “n”th occurance of letter “x” in line. Go to one char before the next occurance in line Move cursor backwards to one char before the next occurance of letter “x” | Move cursor backwards to one char before the “nth occurance of letter “x” | Go to one char before previous occurance in line re 4.32 Open Source Software Where search strings can have the following patterns: Pattern : Description | a A period matches any single character is Finds the beginning of a line [A Finds the beginning of a line where the first] character is the letter ‘A’ 7 $ Matches the end of a line | [abe] Matches a string which contains any of the letters (a, b or c) between the brackets | \ Turn off the special meaning of a character.) | Example “\.” does not match the period to any, character but to the period character specifically \d Match any single digit (0 to 9) ? A search expression followed by a ‘*’ matches | zero or more of the search expression. For example | | “A*” will match A, AA and AAA | at, Same as ‘*’ above except that it matches one or more of the search expression. v Same as ‘*’ and “+” except that it matches zero or| | one occurances string] |string2_| Match any either string | or string 2 ab Matches a string beginning with the letter ‘a’ followed by any character, again followed by the] letter ‘c’ S$ Matches an entire line containing only a single) character a(b*|c*)d Matches a string beginning with the letter ‘a’ followed by zero or more of the letter ‘b’, followed by zero or more of the letter ‘c’ and then followed by the letter ‘a? Linux.*Linux Finds a line containin, “Linux” 'g two instances of the string “[az}+.* Finds a line containing a word Comprised of all lower case letters with a single blank on either side of the word Terminate session: Introduction to Linux 433 % Use command: ZZ Save changes to current file and quit. % Use command line: Save (write) changes to current file and quit. 3% Use command line: “:w” Save (write) changes to current file without quitting. % Use command line: “:w!” Save (write) changes to current file overriding the file permissions if the user has the privileges to change the file permissions. For example this will save a file with read only privileges if the user is the owner or has the ability to modify the privileges to allow a write. This will not permanently modify the file privileges. Note that there is no space between the two characters. A space will infer that the output is pe streamed to a Unix command following the % Use command line: “:w filename” Save (write) changes to a new file of name “filename” without quitting. %* Use command line: “:q!” Ignore changes and quit. No changes from last write will be saved. % Use command line: “:qa” Quit all files opened. New session Use command: “:e filename” Start new edit session on specified file name without closing current vi / vim editor process. 4.6 CREATING A NEW PARTITION IN LINUX Linux systems, you can use the fdisk utility to create a operations. In most new partition and to do other disk management To be able to execute the commands necessary to create a new partition on Linux, you must have the root privileges. Asa tool with a text interface, fdisk requires typing the commands on the fdisk command line. The following fdisk commands may be helpful: Open Source Software 4.34 Options Description ] m Displays the available commands. 1p Displays the list of existing partitions on your hda drive. | Unpartitioned space is not listed. | n Creates a new partition. | q Exits fdisk without saving your changes. | 1 Lists partition types. w Writes changes to the partition table. To create a new partition on Linux 1. Start a terminal. 2. Start fdisk using the following command: /sbin/fdisk /dev/hda where /dev/hda stands for the hard drive that you want to partition. 3. In fdisk, to create a new partition, type the following command: n %* When prompted to specify the Partition type, type p to create a primary partition or e to create an extended one. There may be up to four primary partitions. If you want to create more than four partitions, make the last partition extended, and it will be a container for other logical partitions. %* When prompted for the Number, in most cases, type 3 because a typical Linux virtual machine has two partitions by default. %* When prompted for the Start cylinder, type a starting cylinder number or press Return to use the first cylinder available. %* When prompted for the Last cylinder, press Return to allocate all the available space or specify the size of a new partition in cylinders if you do not want to use all the available space. By default, fdisk creates a partition with a System ID of 83. If you’re unsure of the partition’s System ID, use the command to check it. Introduction to Linux w command to write the changes to the partition table. 5, Restart the virtual machine by entering the reboot command. 6. When restarted, create a file system on the new partition. We recommend that you use the same file system as on the other partitions. In most cases it will be either the Ext3 or ReiserFS file system. For example, to create the Ext3 file system, enter the following. command: /sbin/mkfs -t ext3 /dev/hda3 7. Create a directory that will be a mount point for the new partition. For example, to name it data, enter: mkdir /data 8. Mount the new partition to the directory you have just created by using the following command: mount /dev/hda3 /data 9. Make changes in your static file system information by editing the /etc/fstab file in any of the available text editors. For example, add the following string to this file: /dev/hda3 /data ext3 defaults 00 In this string /dev/hda3 is the partition you have just created, /data is a mount point for the new partition, Ext3 is the file type of the new Partition, For the exact meaning of other items in this string, consult the Linux documentation for the mount and fstab commands. 10. Save the /etc/fstab file. Open Source Software 4.36 QUESTIONS AND ANSWERS PART-A (2 MARKS) 1. What is Linux?. Linux is a UNIX-base operating system. Its original creator wag a Finnish student name Linus Torvalds, although being ‘open source’ it has change a great deal since its original conception. It belongs to nobody, and is free to download and use. 2. List out the advantages of Linux. The major advantage of Linux is its cost: the core OS is free, while many software applications also come with a GNU General public License. It can also be used simultaneously by large numbers of users without slowing down or freezing and it is very fast. It is an excellent networking platform and performs at optimum efficiency even with little available hard disk space. 3. Write a uses of following commands: i) clear ii) mkdir iii) date iv) tail S>clear This is the command to clear screen. This command is also useful when you have to type long commands, which can confuse the users to see different details over the screen, S>mkdir Create one or more directories %* Create a directory named mydirecory mkdir mydirectory * Create 3 directories name dirl, dir2 and dir3 mkdir dirt dir2 dir3 $>date * Set Current system date to “June 20, 1985, 5:27 PM date 0620172785 Introduction to Linux 4.37 ee ee ee S>tail Display last few lines contents ofa file. Very useful to watch latest content updates on log file, Watch running content of a logfile name logfile! tail -f logfilel 4, Define Linux File System. The Linux file system is a hierarchically structured tree where every location has its distinct meaning. 5. Define Mounting a file System. The root of a file system is stored somewhere. Most of the time, it is stored on a partition of a disk. In many cases you would want to combine multiple partitions for a single file system. Combining one partition with the file system is called mounting a file system. 6. Define Linux Security Model[LSM]. Linux Security Modules (LSM) is a framework that allows the Linux kernel to support a variety of computer security models while avoiding favoritism toward any single security implementation. 7. What is Vi editor? This “vi” content is intended for those who wish to master and advance their skills beyond the basic features of the basic editor. It covers buffers, “vi” command line instructions, interfacing with UNIX commands, and ctags. The vim editor is an enhanced version of vi. 8. What are the three types of mode in Vi editor? The vi editor has three modes, command modé, insert mode and command line mode. i. Command mode ii. Insert mode iii. Command line mode 4.38 Open Source Softwar, 9. List out the any four cursor movement commands, hij/kll Move cursor left/down/up/right spacebar Move cursor right one space /+ Move cursor down/up in first column ctrl-d Scroll down one half of a screen nctrl-d Set scroll to “n” lines. New default set for half screen, etrl-u Scroll up one half of a screen netrl-u Set scroll to “n” lines. New default set for half screen, REVIEW QUESTIONS PART - B (5 MARKS) . Explain the Linux essential commands?. . Explain the advantages of Linux? . Short note on Mounting file System. . Explain the different modes of Vi editor? ws, . Explain the Linux security model? PART -C (10 MARKS) 1. Briefly explain the Linux Essential Commands. . Explain the File system Concept. . Explain the Linux Security Model. . Explain the Vi Editor and its different modes. in f& Gs 1) . Explain the Creating a New Partition in Linux.

You might also like