Wednesday, September 30, 2009

Using 'scp' to copy files securely (a.k.a. command-line Secure FTP)

 

Using 'scp' to copy files securely (a.k.a. command-line Secure FTP)

If you are in a UNIX environment and need a quick and secure way to copy files I suggest using scp from the command-line. SSH and OpenSSH provide the scp application, which allows you to connect and transfer files on servers running an encrypted FTP service. (ssh daemon)

If you are looking for an X windows GUI application, you may want to try out http://gftp.seul.org/.

Scp is already installed on the UW Dante and Homer servers and if you know the right directories it will even work with Windows secure FTP servers.

Here is how scp works :( Note the use of periods; they are essential!!)

1) To copy a file from hostB to hostA, while logged in to hostB:

bash$ scp filename username@hostA.com:.

(copies file to user's home dir on hostA machine, because of the period after the colon)

2) To copy a folder from hostB to hostA, while logged in to hostB first cd to the directory on HostB which contains the folder you want to copy:

bash$ scp -r folder username@hostA.com:.(creates new folder if the folder does not exist, again in user's home directory)

3) To copy a file from hostA to hostB, while logged in to hostB:

bash$ scp username@hostA.com:filename .

(copies into current directory on hostB)

bash$ scp -r username@hostA.com:folder .

(copies whole folder into current directory on hostB)

4) To copy a file or folder within a folder from hostA to hostB, while logged in to hostB:

bash$ scp username@hostA.com:/folder/dir/filename .

(copies into current directory on hostB)

bash$ scp -r username@hostA.com:/folder/dir .

(copies whole folder into current directory on hostB)

5) Instead of using the '.' to designate files to be copied to a home directory or the current working directory you can give scp an actual path (assuming you have write permissions):

bash$ scp -r folder username@hostA:/home/httpd/

bash$ scp username@hostA.com:/folder/dir/filename /home/tmp/

Tuesday, September 29, 2009

Creating And Mounting Iso File System Using makeisofs utility

Creating And Mounting Iso File System Using makeisofs utility

One file containing all the directory and files of CD-ROM.

First insert the cd in cd-rom for which you want to make the ISO image file.

# which mkisofs

# fdisk –l

# mkdir iso

# cd iso

# mkisofs –o mega.iso –J –v –R /media/cdrom

-o - Output File

-J – Joilet (The file is also redable by other applications in windows).

For more details of switches see the man pages of mkisofs

# man mkisofs

Mounting ISO file

# cat /proc/filesystems

Display list of filesystems supported by Linux or Kernel.

# mkdir mount

# mount –t iso9660 –o loop mega.iso /root/iso/mount

# cd /root/iso/mount

# ls

Monday, September 28, 2009

Load and Unload Kernel Modules

Load and Unload Kernel Modules

Linux allows the Kernel to be configured at run time, to enable or disable different services as you see fit. This way you don't have to compile a monolithic kernel, and can save some memory usage. Some modules you'll only need for a short time, others you'll need all the time. You can configure your Linux machine to load kernel modules on startup so you don't have to remember to do that when (if) you reboot.

Module Commands

There are a few commands that allow you to maniuplate the kernel. Each is quickly described below, for more information say `man [command]`.

  • depmod - handle dependency descriptions for loadable kernel modules.
  • insmod - install loadable kernel module.
  • lsmod - list loaded modules.
  • modinfo - display information about a kernel module.
  • modprobe - high level handling of loadable modules.
  • rmmod - unload loadable modules.

The usage of the commands is demonstrated below, it is left as an excerise to the reader to fully understand the commands.

Using Module Commands

Below the different kernel module commands are demonstrated

# Show the module dependencies.
depmod -n

# Install some module
insmod --autoclean [modnam]

# This lists all currently loaded modules, lsmod takes no useful parameters
lsmod

# Display information about module eepro100
modinfo --author --description --parameters eepro100

# Removing a module (don't use the example)
rmmod --all --stacks ip_tables


Module Configuration Files



The kernel modules can use two different methods of automatic loading. The first method (modules.conf) is my preferred method, but you can do as you please.




  • modules.conf - This method load the modules before the rest of the services, I think before your computer chooses which runlevel to use


  • rc.local - Using this method loads the modules after all other services are started



Using 'modules.conf' will require you to say `man 5 modules.conf`. Using 'rc.local' requires you to place the necessary commands (see above) in the right order.



Sample modules.conf



# modules.conf - configuration file for loading kernel modules
# Create a module alias parport_lowlevel to parport_pc
alias parport_lowlevel parport_pc
# Alias eth0 to my eepro100 (Intel Pro 100)
alias eth0 eepro100
# Execute /sbin/modprobe ip_conntrack_ftp after loading ip_tables
post-install ip_tables /sbin/modprobe ip_conntrack_ftp
# Execute /sbin/modprobe ip_nat_ftp after loading ip_tables
post-install ip_tables /sbin/modprobe ip_nat_ftp


Sample rc.local



#!/bin/sh
#
# This script will be executed *after* all the other init scripts.
# You can put your own initialization stuff in here if you don't
# want to do the full Sys V style init stuff.

/sbin/insmod ip_tables
/sbin/modprobe ip_conntrack_ftp
/sbin/modprobe ip_nat_ftp


Conclusion



You should see/know that modules are necessary. They can be loaded via 'modules.conf' or 'rc.local', but 'modules.conf' load them first and 'rc.local' loads them last. Using the various module commands you can add, remove, list or get information about modules.



source: http://edoceo.com/liber

Sunday, September 27, 2009

what is the difference between RHEL4 & RHEL5?

what is the difference between RHEL4 & RHEL5?

RHEL4 :No yum server,Selinux,secure,no cd key

RHEL5: yum server, advanced selinux ,more secure,virtualization

RHEL4 : Stable Kernel, Can'nt create YUM repository,

Selinux with 36,000 lines of code, Quite secure,no cd

key,no Xen.

RHEL5: Not stable kernel, Can create yum server, advanced

selinux without line of codes these are converted into

modules ,more secure,virtualization with Xen, As comapre to

RHEL 4 Many bugs in RHEL5 for e.g. Reducing LVM.,

IPV6 implementation.. etc

difference between RHEL 4 and RHEL 5

1)In RHEL 4 SELinux Block only 13 services, But on RHEL 5

SElinux Block 80 services

2) RHEL 4 have ext2 filesystem, but RHEL 5 we have ext3

filesystem That support Journal

3)RHEL 4 have no virtualization Feature, but in RHEL 5 we

have virtualization with Hypervisor-V

4)In RHEL 4 we have no Yum, But in RHEL 5 we have Yum available

differnece between rhel 4 and rhel 5

rhel4 rhel5

no yum server yum server

selinux Advanced selinux

secure more secure

no cdkey cd key

--- virtualization

mim 256 mb ram 512 ram

--- better support for

Red Hat Directory

XEN, YUM and improved SELinux

all the features updated with better options

Better GUI support then RHEL4

YUM over RPM package management

IPTables and SELinux for more secure environment

Red Hat author dishes on RHEL 5

By Jack Loftus, News Writer

23 Apr 2007 | SearchEnterpriseLinux.com

Enterprise Linux headlines

Digg This! StumbleUpon Toolbar StumbleUpon Bookmark with Delicious Del.icio.us Add to Google

Tammy Fox has worn many hats in the past for Red Hat Inc., including technical writer, lead of the documents team and founding editor of Red Hat Magazine. She has also been a professional Linux writer for the past seven years. In other words, she knows Red Hat Linux.

Five things to know about RHEL 5:

1. Installation codes are necessary for installation and can unlock access to specific functionality such as virtualization and clustering.

2. Virtual machines can be created with the virtualization option, which is based on Xen.

3. Kdump can be enabled to capture dump files during system crashes.

4. YUM has replaced up2date, both the command and graphical application.

5. SELinux is enabled by default.

- Tammy Fox, author, Red Hat Enterprise Linux 5 Unleashed

Fox's latest work, Red Hat Enterprise Linux 5 Administration Unleashed, arrived this month intended as a tome of knowledge for intermediate to advanced Linux system administrators. Before it was published, Fox sat down with SearchEnterpriseLinux.com to provide some insight on the latest version of the Linux community's leading commercial distribution, Red Hat Enterprise Linux 5 (RHEL 5).

What general best practices or tips can you share to make an upgrade to RHEL 5 a smooth one?

Tammy Fox: Performing an upgrade with the installation program basically updates any existing RPM packages on your system. If the new version of the package includes changes that make your existing configuration invalid, some packages will try to migrate your existing data, but it is not required.

The best practice is to have your data on a dedicated storage system that does not get reformatted during a fresh installation. Depending on the size of your organization, this can be a SAN, a data cluster, or just a set of dedicated hard drives in the system. Back up any existing data and configuration files, and perform a fresh installation. Restore your configuration files one by one, testing each program. Be sure to pay close attention to whether or not the software version has changed from your previous version of RHEL to RHEL 5. Finally, reconnect your data storage solution and perform any additional tests necessary.

Of course, all of these steps should be performed on a test system before the plan is implemented on a production system.

What are some key differences between what administrators see in RHEL 4 deployments, and RHEL 5 ones?

Fox: The most immediate change they will notice is the introduction of installation codes. During installation, an installation code must be entered. These codes are generated by Red Hat. Depending on what services you purchased, they unlock different RHEL 5 components such as virtualization and high availability. RHEL 5 also uses new RPM GPG keys. If upgrading, you will need to install the new keys before updating packages.

The next big noticeable change is the move to YUM for software management and maintenance. In previous versions of RHEL, the up2date command could be used to download and install software updates from Red Hat Network. It has been replaced with the YUM command, and all the up2date graphical program has been replaced with a graphical program that use YUM as well. If you schedule package updates and installation with the RHN Web site, you will not notice a difference.

Administrators must also consider whether to use the virtualization feature in RHEL5. (Editor's Note: Due to trademark issues, Red Hat currently refers to Xen-based hypervisor technology as virtualization.) If your hardware is supported and you have systems with enough resources to share between the host system and the virtual machines, virtualization can help reduce the number of physical machines that need to be maintained. If you are a hosting service or allow your customers shell access to their Web site, virtualization can be beneficial.

Administrators should read the release notes for a complete list of caveats and known issues with RHEL 5. For example, dual-booting with Windows Vista requires additional steps for GRUB to boot Windows Vista.

Friday, September 25, 2009

sticky bit

sticky bit — used primarily on directories, this bit dictates that a file created in the directory can be removed only by the user who created the file. it is indicated by the character t in place of the x in the everyone category. in Red Hat Linux the sticky bit is set by default on the /tmp/ directory for exactly this reason.

source :http://www.redhat.com/docs/manuals/linux/RHL-8.0-Manual/admin-primer/ch-acctsgrps.html

Wednesday, September 23, 2009

special permissions within Red Hat Linux.

special permissions within Red Hat Linux.

  • setuid — used only for applications, this permission indicates that the application runs as the owner of the file and not as the user executing the application. It is indicated by the character s in place of the x in the owner category. If the owner of the file does not have execution permissions, the S is capitalized.
  • setgid — used primarily for applications, this permission indicates that the application runs as the group owning the file and not as the group executing the application. If applied to a directory, all files a user creates within the directory are owned by the group who owns the directory, rather than by the user's private group (see the chapter titled Users and Groups in Official Red Hat Linux Reference Guide for more about user private groups). It is indicated by the character s in place of the x in the group category. If the group owner of the file or directory does not have execution permissions, the S is capitalized.

  • sticky bit — used primarily on directories, this bit dictates that a file created in the directory can be removed only by the user who created the file. it is indicated by the character t in place of the x in the everyone category. in Red Hat Linux the sticky bit is set by default on the /tmp/ directory for exactly this reason.

Monday, September 21, 2009

Important linux commands used in real time scenarios..

This is a linux command line reference for common operations.

Examples marked with • are valid/safe to paste without modification into a terminal, so

you may want to keep a terminal window open while reading this so you can cut & paste.

All these commands have been tested both on Fedora and Ubuntu.

Command

Description

apropos whatis

Show commands pertinent to string. See also threadsafe

man -t man | ps2pdf - > man.pdf

make a pdf of a manual page

which command

Show full path name of command

time command

See how long a command takes

time cat

Start stopwatch. Ctrl-d to stop. See also sw

nice info

Run a low priority command (The "info" reader in this case)

renice 19 -p $$

Make shell (script) low priority. Use for non interactive tasks

dir navigation

cd -

Go to previous directory

cd

Go to $HOME directory

(cd dir && command)

Go to dir, execute command and return to current dir

pushd .

Put current dir on stack so you can popd back to it

file searching

alias l='ls -l --color=auto'

quick dir listing

ls -lrt

List files by date. See also newest and find_mm_yyyy

ls /usr/bin | pr -T9 -W$COLUMNS

Print in 9 columns to width of terminal

find -name '*.[ch]' | xargs grep -E 'expr'

Search 'expr' in this dir and below. See also findrepo

find -type f -print0 | xargs -r0 grep -F 'example'

Search all regular files for 'example' in this dir and below

find -maxdepth 1 -type f | xargs grep -F 'example'

Search all regular files for 'example' in this dir

find -maxdepth 1 -type d | while read dir; do echo $dir; echo cmd2; done

Process each item with multiple commands (in while loop)

find -type f ! -perm -444

Find files not readable by all (useful for web site)

find -type d ! -perm -111

Find dirs not accessible by all (useful for web site)

locate -r 'file[^/]*\.txt'

Search cached index for names. This re is like glob *file*.txt

look reference

Quickly search (sorted) dictionary for prefix

grep --color reference /usr/share/dict/words

Highlight occurances of regular expression in dictionary

archives and compression

gpg -c file

Encrypt file

gpg file.gpg

Decrypt file

tar -c dir/ | bzip2 > dir.tar.bz2

Make compressed archive of dir/

bzip2 -dc dir.tar.bz2 | tar -x

Extract archive (use gzip instead of bzip2 for tar.gz files)

tar -c dir/ | gzip | gpg -c | ssh user@remote 'dd of=dir.tar.gz.gpg'

Make encrypted archive of dir/ on remote machine

find dir/ -name '*.txt' | tar -c --files-from=- | bzip2 > dir_txt.tar.bz2

Make archive of subset of dir/ and below

find dir/ -name '*.txt' | xargs cp -a --target-directory=dir_txt/ --parents

Make copy of subset of dir/ and below

( tar -c /dir/to/copy ) | ( cd /where/to/ && tar -x -p )

Copy (with permissions) copy/ dir to /where/to/ dir

( cd /dir/to/copy && tar -c . ) | ( cd /where/to/ && tar -x -p )

Copy (with permissions) contents of copy/ dir to /where/to/

( tar -c /dir/to/copy ) | ssh -C user@remote 'cd /where/to/ && tar -x -p'

Copy (with permissions) copy/ dir to remote:/where/to/ dir

dd bs=1M if=/dev/sda | gzip | ssh user@remote 'dd of=sda.gz'

Backup harddisk to remote machine

rsync (Network efficient file copier: Use the --dry-run option for testing)

rsync -P rsync://rsync.server.com/path/to/file file

Only get diffs. Do multiple times for troublesome downloads

rsync --bwlimit=1000 fromfile tofile

Locally copy with rate limit. It's like nice for I/O

rsync -az -e ssh --delete ~/public_html/ remote.com:'~/public_html'

Mirror web site (using compression and encryption)

rsync -auz -e ssh remote:/dir/ . && rsync -auz -e ssh . remote:/dir/

Synchronize current directory with remote one

ssh (Secure SHell)

ssh $USER@$HOST command

Run command on $HOST as $USER (default command=shell)

ssh -f -Y $USER@$HOSTNAME xeyes

Run GUI command on $HOSTNAME as $USER

scp -p -r $USER@$HOST: file dir/

Copy with permissions to $USER's home directory on $HOST

ssh -g -L 8080:localhost:80 root@$HOST

Forward connections to $HOSTNAME:8080 out to $HOST:80

ssh -R 1434:imap:143 root@$HOST

Forward connections from $HOST:1434 in to imap:143

wget (multi purpose download tool)

(cd dir/ && wget -nd -pHEKk http://www.pixelbeat.org/cmdline.html)

Store local browsable version of a page to the current dir

wget -c http://www.example.com/large.file

Continue downloading a partially downloaded file

wget -r -nd -np -l1 -A '*.jpg' http://www.example.com/dir/

Download a set of files to the current directory

wget ftp://remote/file[1-9].iso/

FTP supports globbing directly

wget -q -O- http://www.pixelbeat.org/timeline.html | grep 'a href' | head

Process output directly

echo 'wget url' | at 01:00

Download url at 1AM to current dir

wget --limit-rate=20k url

Do a low priority download (limit to 20KB/s in this case)

wget -nv --spider --force-html -i bookmarks.html

Check links in a file

wget --mirror http://www.example.com/

Efficiently update a local copy of a site (handy from cron)

networking (Note ifconfig, route, mii-tool, nslookup commands are obsolete)

ethtool eth0

Show status of ethernet interface eth0

ethtool --change eth0 autoneg off speed 100 duplex full

Manually set ethernet interface speed

iwconfig eth1

Show status of wireless interface eth1

iwconfig eth1 rate 1Mb/s fixed

Manually set wireless interface speed

iwlist scan

List wireless networks in range

ip link show

List network interfaces

ip link set dev eth0 name wan

Rename interface eth0 to wan

ip link set dev eth0 up

Bring interface eth0 up (or down)

ip addr show

List addresses for interfaces

ip addr add 1.2.3.4/24 brd + dev eth0

Add (or del) ip and mask (255.255.255.0)

ip route show

List routing table

ip route add default via 1.2.3.254

Set default gateway to 1.2.3.254

tc qdisc add dev lo root handle 1:0 netem delay 20msec

Add 20ms latency to loopback device (for testing)

tc qdisc del dev lo root

Remove latency added above

host pixelbeat.org

Lookup DNS ip address for name or vice versa

hostname -i

Lookup local ip address (equivalent to host `hostname`)

whois pixelbeat.org

Lookup whois info for hostname or ip address

netstat -tupl

List internet services on a system

netstat -tup

List active connections to/from system

windows networking (Note samba is the package that provides all this windows specific networking support)

smbtree

Find windows machines. See also findsmb

nmblookup -A 1.2.3.4

Find the windows (netbios) name associated with ip address

smbclient -L windows_box

List shares on windows machine or samba server

mount -t smbfs -o fmask=666,guest //windows_box/share /mnt/share

Mount a windows share

echo 'message' | smbclient -M windows_box

Send popup to windows machine (off by default in XP sp2)

text manipulation (Note sed uses stdin and stdout. Newer versions support inplace editing with the -i option)

sed 's/string1/string2/g'

Replace string1 with string2

sed 's/\(.*\)1/\12/g'

Modify anystring1 to anystring2

sed '/ *#/d; /^ *$/d'

Remove comments and blank lines

sed ':a; /\\$/N; s/\\\n//; ta'

Concatenate lines with trailing \

sed 's/[ \t]*$//'

Remove trailing spaces from lines

sed 's/\([`"$\]\)/\\\1/g'

Escape shell metacharacters active within double quotes

seq 10 | sed "s/^/ /; s/ *\(.\{7,\}\)/\1/"

Right align numbers

sed -n '1000p;1000q'

Print 1000th line

sed -n '10,20p;20q'

Print lines 10 to 20

sed -n 's/.*<\/title>.*/\1/ip;T;q'

Extract title from HTML web page

sed -i 42d ~/.ssh/known_hosts

Delete a particular line

sort -t. -k1,1n -k2,2n -k3,3n -k4,4n

Sort IPV4 ip addresses

echo 'Test' | tr '[:lower:]' '[:upper:]'

Case conversion

tr -dc '[:print:]' < /dev/urandom

Filter non printable characters

history | wc -l

Count lines

set operations (Note you can export LANG=C for speed. Also these assume no duplicate lines within a file)

sort file1 file2 | uniq

Union of unsorted files

sort file1 file2 | uniq -d

Intersection of unsorted files

sort file1 file1 file2 | uniq -u

Difference of unsorted files

sort file1 file2 | uniq -u

Symmetric Difference of unsorted files

join -t'\0' -a1 -a2 file1 file2

Union of sorted files

join -t'\0' file1 file2

Intersection of sorted files

join -t'\0' -v2 file1 file2

Difference of sorted files

join -t'\0' -v1 -v2 file1 file2

Symmetric Difference of sorted files

math

echo '(1 + sqrt(5))/2' | bc -l

Quick math (Calculate φ). See also bc

echo 'pad=20; min=64; (100*10^6)/((pad+min)*8)' | bc

More complex (int) e.g. This shows max FastE packet rate

echo 'pad=20; min=64; print (100E6)/((pad+min)*8)' | python

Python handles scientific notation

echo 'pad=20; plot [64:1518] (100*10**6)/((pad+x)*8)' | gnuplot -persist

Plot FastE packet rate vs packet size

echo 'obase=16; ibase=10; 64206' | bc

Base conversion (decimal to hexadecimal)

echo $((0x2dec))

Base conversion (hex to dec) ((shell arithmetic expansion))

units -t '100m/9.58s' 'miles/hour'

Unit conversion (metric to imperial)

units -t '500GB' 'GiB'

Unit conversion (SI to IEC prefixes)

units -t '1 googol'

Definition lookup

seq 100 | (tr '\n' +; echo 0) | bc

Add a column of numbers. See also add and funcpy

calendar

cal -3

Display a calendar

cal 9 1752

Display a calendar for a particular month year

date -d fri

What date is it this friday. See also day

[ $(date -d "tomorrow" +%d) = "01" ] || exit

exit a script unless it's the last day of the month

date --date='25 Dec' +%A

What day does xmas fall on, this year

date --date='@2147483647'

Convert seconds since the epoch (1970-01-01 UTC) to date

TZ=':America/Los_Angeles' date

What time is it on West coast of US (use tzselect to find TZ)

echo "mail -s 'get the train' P@draigBrady.com < /dev/null" | at 17:45

Email reminder

echo "DISPLAY=$DISPLAY xmessage cooker" | at "NOW + 30 minutes"

Popup reminder

locales

printf "%'d\n" 1234

Print number with thousands grouping appropriate to locale

BLOCK_SIZE=\'1 ls -l

get ls to do thousands grouping appropriate to locale

echo "I live in `locale territory`"

Extract info from locale database

LANG=en_IE.utf8 locale int_prefix

Lookup locale info for specific country. See also ccodes

locale | cut -d= -f1 | xargs locale -kc | less

List fields available in locale database

recode (Obsoletes iconv, dos2unix, unix2dos)

recode -l | less

Show available conversions (aliases on each line)

recode windows-1252.. file_to_change.txt

Windows "ansi" to local charset (auto does CRLF conversion)

recode utf-8/CRLF.. file_to_change.txt

Windows utf8 to local charset

recode iso-8859-15..utf8 file_to_change.txt

Latin9 (western europe) to utf8

recode ../b64 <> file.b64

Base64 encode

recode /qp.. <> file.qp

Quoted printable decode

recode ..HTML <> file.html

Text to HTML

recode -lf windows-1252 | grep euro

Lookup table of characters

echo -n 0x80 | recode latin-9/x1..dump

Show what a code represents in latin-9 charmap

echo -n 0x20AC | recode ucs-2/x2..latin-9/x

Show latin-9 encoding

echo -n 0x20AC | recode ucs-2/x2..utf-8/x

Show utf-8 encoding

CDs

gzip < /dev/cdrom > cdrom.iso.gz

Save copy of data cdrom

mkisofs -V LABEL -r dir | gzip > cdrom.iso.gz

Create cdrom image from contents of dir

mount -o loop cdrom.iso /mnt/dir

Mount the cdrom image at /mnt/dir (read only)

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

Clear a CDRW

gzip -dc cdrom.iso.gz | cdrecord -v dev=/dev/cdrom -

Burn cdrom image (use dev=ATAPI -scanbus to confirm dev)

cdparanoia -B

Rip audio tracks from CD to wav files in current dir

cdrecord -v dev=/dev/cdrom -audio *.wav

Make audio CD from all wavs in current dir (see also cdrdao)

oggenc --tracknum='track' track.cdda.wav -o 'track.ogg'

Make ogg file from wav file

disk space (See also FSlint)

ls -lSr

Show files by size, biggest last

du -s * | sort -k1,1rn | head

Show top disk users in current dir. See also dutop

df -h

Show free space on mounted filesystems

df -i

Show free inodes on mounted filesystems

fdisk -l

Show disks partitions sizes and types (run as root)

rpm -q -a --qf '%10{SIZE}\t%{NAME}\n' | sort -k1,1n

List all packages by installed size (Bytes) on rpm distros

dpkg-query -W -f='${Installed-Size;10}\t${Package}\n' | sort -k1,1n

List all packages by installed size (KBytes) on deb distros

dd bs=1 seek=2TB if=/dev/null of=ext3.test

Create a large test file (taking no space). See also truncate

> file

truncate data of file or create an empty file

monitoring/debugging

tail -f /var/log/messages

Monitor messages in a log file

strace -c ls >/dev/null

Summarise/profile system calls made by command

strace -f -e open ls >/dev/null

List system calls made by command

ltrace -f -e getenv ls >/dev/null

List library calls made by command

lsof -p $$

List paths that process id has open

lsof ~

List processes that have specified path open

tcpdump not port 22

Show network traffic except ssh. See also tcpdump_not_me

ps -e -o pid,args --forest

List processes in a hierarchy

ps -e -o pcpu,cpu,nice,state,cputime,args --sort pcpu | sed '/^ 0.0 /d'

List processes by % cpu usage

ps -e -orss=,args= | sort -b -k1,1n | pr -TW$COLUMNS

List processes by mem usage. See also ps_mem.py

ps -C firefox-bin -L -o pid,tid,pcpu,state

List all threads for a particular process

ps -p 1,2

List info for particular process IDs

last reboot

Show system reboot history

free -m

Show amount of (remaining) RAM (-m displays in MB)

watch -n.1 'cat /proc/interrupts'

Watch changeable data continuously

system information (see also sysinfo) ('#' means root access is required)

uname -a

Show kernel version and system architecture

head -n1 /etc/issue

Show name and version of distribution

cat /proc/partitions

Show all partitions registered on the system

grep MemTotal /proc/meminfo

Show RAM total seen by the system

grep "model name" /proc/cpuinfo

Show CPU(s) info

lspci -tv

Show PCI info

lsusb -tv

Show USB info

mount | column -t

List mounted filesystems on the system (and align output)

grep -F capacity: /proc/acpi/battery/BAT0/info

Show state of cells in laptop battery

#

dmidecode -q | less

Display SMBIOS/DMI information

#

smartctl -A /dev/sda | grep Power_On_Hours

How long has this disk (system) been powered on in total

#

hdparm -i /dev/sda

Show info about disk sda

#

hdparm -tT /dev/sda

Do a read speed test on disk sda

#

badblocks -s /dev/sda

Test for unreadable blocks on disk sda

interactive (see also linux keyboard shortcuts)

readline

Line editor used by bash, python, bc, gnuplot, ...

screen

Virtual terminals with detach capability, ...

mc

Powerful file manager that can browse rpm, tar, ftp, ssh, ...

gnuplot

Interactive/scriptable graphing

links

Web browser

xdg-open http://www.pixelbeat.org/

open a file or url with the registered desktop application

miscellaneous

alias hd='od -Ax -tx1z -v'

Handy hexdump. (usage e.g.: • hd /proc/self/cmdline | less)

alias realpath='readlink -f'

Canonicalize path. (usage e.g.: • realpath ~/../$USER)

set | grep $USER

Search current environment

touch -c -t 0304050607 file

Set file timestamp (YYMMDDhhmm)

python -m SimpleHTTPServer

Serve current directory tree at http://$HOSTNAME:8000/

source :http://www.pixelbeat.org/cmdline.html

Sunday, September 20, 2009

Passwords and Permisssions

Ordinary users have two ways of protecting the data in their accounts:

1. choose a secure password

2. set permissions

Changing your password:

  1. One of the easiest method of breaking into a system is to crack a weak password. To create a secure password:
    • The password should be at least 6 characters long.
    • You should not use names or phrases that are easily obtained; do NOT use your name; do NOT use your dog's name; do NOT use your spouse's name; do NOT use your licence plate; do NOT use your birthdate ...
    • Include both CAPITAL and lowercase letters.
    • Include special characters ( ! @ # $ % ... )
    • Include digits
  2. One way to create a secure password is suggested in the passwd man page.
    • choose 2 small words ( eg: why not )
    • mix in some capitalization ( eg: whY Not )
    • join them with a special character ( eg: whY%Not )
  3. The command to change your password is: passwd

Setting permissions:

Access to files and directories is controlled by a permissions at both the file and directory levels.

  • permissions can be any combination of read, write, execute for the owner, group and world.
  • for a file:
    • without read permission, a user cannot view the contents of a file
    • without write permission, a user cannot modify the contents of the file
    • without execute permission, a user cannot execute the file.
  • for a directory:
    • without read permission, a user cannot get a directory listing
    • without write permission, a user cannot create new files
    • without execute permission, a user cannot cd to the directory, list the directory contents or save a file in the directory.
  • chmod - change permissions.
    • Read, write and execute permissions are set for three groups: the owner, the group and everyone else.
    • chmod 543 myfile would set access rights as follows:
      owner: 5 = 101 binary = read, not write, execute
      group: 4 = 100 binary = read, not write, not execute
      others: 3 = 011 binary = not read, write, execute
  • chmod - version 2
    • permissions can also be set using a text representation
      u - user or owner
      g - group
      o - others
      r - read permission
      w - write permission
      x - execute permission
    • chmod u+w file1
      adds write permission for the user
    • chmod +w file1
      adds write permission for the user, group and others
    • chmod go-x file1
      deletes execute permission for the group and others
    • chmod u=r file1
      changes the permissions for the user to be just read permission (group and other permissions are not changed)

Exercises:


  1. Try to change your password to cat. What error message did you get?
  2. Try to change your password to blackcat. What error message did you get?
  3. Think up a password and change your password.
  4. Try to the password for another user. For example, enter the command:
    passwd floopy
    What error message did you get?
  5. Can you view the contents of the directory /sbin?
  6. What are the permissions for the directory /sbin?
  7. Change the permissions on "readme" in your own home so that you have read/write access, the group has read access and others have no access.
  8. Change permissions on your home directory so that you have read/write/execute permissions, the group has read/execute permissions, and everyone else has no access.
  9. Make sure that you are in your own home directory. Create a subdirectory called ddd and copy readme to ddd/fff (a file called fff in the ddd subdirectory).
    • what are the permissions on ddd and fff? ____________________
    • change the permissions on fff to only rwx for the owner.
  10. Try the following exercise to see some of the operations that you can and cannot do when you have only read permission on a directory.
    • change the permissions on ddd only r for the owner (no permissions for the group and the world)
    • can you get a directory listing for ddd? _____
    • can you cd to ddd? _____
    • can you view the contents of fff with the command: cat ddd/fff ? ______
    • can you delete fff with the command: rm ddd/fff ?______
  11. Try the following to see what you can do when you have read and execute permission for a directory.
    • change the permissions on ddd only rx for the owner (no permissions for the group and the world)
    • can you get a directory listing for ddd? _____
    • can you cd to ddd? _____
    • can you view the contents of fff with the command: cat ddd/fff ? ______
    • can you delete fff with the command: rm ddd/fff ? ______
  12. Try the following to see what you can do when you have write and execute permissions for a directory.
    • change the permissions on ddd only wx for the owner (no permissions for the group and the world)
    • can you get a directory listing for ddd? _____
    • can you cd to ddd? _____
    • can you view the contents of fff with the command: cat ddd/fff ? ______
    • can you delete fff with the command: rm ddd/fff ? ______
    • can you execute the command: cd ; cp readme ddd/fff _____
  13. Try the following to see what you can do when you have only execute permissions for a directory.
    • change the permissions on ddd only x for the owner (no permissions for the group and the world)
    • can you get a directory listing for ddd? _____
    • can you cd to ddd? _____
    • can you view the contents of fff with the command: cat ddd/fff ? ______
    • can you delete with the command: rm ddd/fff
    • can you execute the command: cd ; cp readme ddd/fff _____

Questions and Answers:


  1. The directory entries for the /etc directory and the file /etc/passwd are:
    -rwxr-xr-x 18 root root 1024 May 20 11:58 /etc
    -rw-r--r-- 1 root root 658 May 20 11:58 /etc/passwd

    Can you modify this file (assuming you are not root)?
    Answer: No.
  2. Can you copy /etc/passwd to your own home directory assuming that you have write and execute permissions for your own home directory?
    Answer: Yes. Everyone has read permission for this file and can make a copy.
  3. If you are not floopy, can you copy /etc/passwd (permissions rw-r--r--) to the directory /home/floopy? The permissions on /home/floopy are rwxr-xr-x.
    Answer: No. /home/floopy is owned by floopy and the permissions are rwxr-xr-x meaning that everyone can read the contents of the directory but only floopy can store files in this directory.
  4. File1 has permissions: r--r--r--
    You enter the command: chmod ug+w file1
    What are the new permissions?
    Answer: rw-rw-r--
  5. What command will change the permissions on dir1 so that only the owner has read/execute access?
    Answer: chmod 500 dir1
  6. Can you cd to dir1 given the permissions are drw-------?
    Answer: No. Without execute access, you cannot cd to a directory or access any of the files in the directory.
  7. What command will change the permissions on dir1 so that you have write/execute permissions only?
    Answer: chmod 300 dir1
  8. Can you copy readme (permissions r--r--r--) to dir1 (permissions d-wx------ ) if you own dir1?
    Answer: Yes
  9. Can you get a directory listing for dir1 permissions (d-wx-wx-wx)?
    Answer: No. If you do not have read permission for a directory, then essentially you have blind access; you can write files in the dir1 but you cannot get a directory listing.

Source:http://floppix.ccai.com/protect.html

Saturday, September 19, 2009

A thread and A task

A thread is a point of control flow in a task. A task

exists to provide resources for the threads it contains. This split is made to provide

for parallelism and resource sharing.

A thread

* is a point of control flow in a task.

* has access to all of the elements of the containing task.

* executes (potentially) in parallel with other threads, even threads within the same task.

* has minimal state information for low overhead.

A task

* is a collection of system resources. These resources, with the exception of the address space, are referenced by ports. These resources may be shared with other tasks if rights to the ports are so distributed.

* provides a large, potentially sparse address space, referenced by virtual address.Portions of this space may be shared through inheritance or external memory management.

* contains some number of threads.

Thursday, September 17, 2009

Overview of the linux kernel

Overview of the linux kernel

Abstract

This article discusses the basic kernel features of the linux kernel.It starts from the history of the linux kernel to basic operataing designs required for a kernel and how linux implements it in a nutshell.Then it concludes by promising future articles on different layers of the linux kernel and also an articles on Linux kernel 2.6 features,Future of Linux which will be contributed by different members of the lkg_india group.

Audience

I myself being a kernel newbie,has intended to write the article in such a fashion that it will be understood by anyone who has used the computer.It can also be read by experienced kernel developers so as to refresh their thoughts and also suggest/crticise the mistakes in the article.This article is dedicated for free for the benefit and education of all. That a person seeking knowledge should have the opportunity to find it.Thanks to every other document written with the same vein which has made this article possible.

Intoduction

To start off immediately what does kernel mean?Well thats what this blog is for,for us to understand what the kernel is.Hopefully future articles in the blog will make us understand the kernel completely and clearly.Well here is the literal meaning of the word "kernel" straight from dict.org

"The central, substantial or essential part of anything;the gist; the core;"

This is how the Online dictionary of computing defines the word kernel

"The essential part of Unix or other operating systems, responsible for resource allocation,low-level hardware interfaces, security etc"

Operating System

Any computer system includes a basic set of programs called the operating system. The most important program in the set is called the kernel.The other programs are less crucial utilities; they can provide a wide variety of interactive experiences for the user as well as doing all the jobs the user bought the computer for but the essential shape and capabilities of the system are determined by the kernel.

Is kernel the entire operating system?

No,as discussed above.The kernel is the core component of the operating system.The operating system contains the Kernel plus other systen utilities which use the kernel to provide higher level house keeping tasks.Technically speaking,Linux is only the kernel,as it does not provide system utilities like file system utilities,compilers,editors,the graphical user interface which are provided by any other operating system.So linux users typically rely on commercial ditributions like Suse,Red Hat etc., to have the entire operating system.Having known the what a Operating system and what the kernel is,let us know something about the history of the Linux kernel.

Linux,the revolutionay open source kernel

Linux was intially developed by Linus in Aug 1991.As a source of inspiration listed below is his mail on the famous comp.os.newsgroup

"----- Message from "Linus Benedict Torvalds"

on Mon, 26 Aug 1991 02:27:08 +0530 -----

Subject: What would you like to see most in minix?

Hello everybody out there using minix-

I'm doing a (free) operating system (just a hobby, won't be big

and professional like gnu) for 386(486) AT clones. This has

been brewing since april, and is starting to get ready. I'd like

any feedback on things people like/dislike in minix; as my OS

resembles it somewhat (same physical layout of the file-sytem

due to practical reasons)among other things.

I've currently ported bash (1.08) an gcc (1.40), and things seem to work.

This implies that i'll get something practical within a few months, and I'd

like to know what features most people want. Any suggestions are welcome,

but I won't promise I'll implement them :-)

Linus Torvalds torvalds@kruuna.helsinki.fi"

As seen from the mail there was an effort by the FSF(Free Software Foundation) headed by Richard Stallman to build a complete free professional Operating System. So lets talk about FSF before proceeding further.

FSF - RICHARD STALLMAN

The FSF was founded by Richard Stallman in 1984.Its also know as the GNU software project which was launched to built a complete free operating system.When richard started working for writing a free OS he felt that he should use a free editor to write programs for the Operating system,then he wrote the GNU emacs editor.Then they needed a free compiler to compile their C programs,thereby was born the GNU Compiler collection(gcc).Later when linus released Linux kernel free and it became popular,it was adopted by FSF as their kernel.So GNU utilities were used with the Linux kernel to make the complete Operating System.Now Linux remains as one of the most popular Open source operating system in the world.

Features of the Linux Kernel

I.Monolithic kernel with module support

The linux kernel is monolithic with module suport.So now let us try to decipher the meaning of the previous sentence and why linux adopted a monolithic kernel with module strategy.

Monolithic kernel

A monolithic kernel is a single large complex "do-it-yourself" kernel program which is composed of several different logical entities(kernel layers).Each kernel layer is integrated in to the large kernel program and runs in kernel mode(more on kernel mode later)on behalf of the current process.

Microkernel

A micro kernel consists of a small set of important fucntions in the kernel generally a simple scheduler,synchronisation primitives.Several System processes that run on top of the kernel to implement other OS layer functions like memory allocators,device drivers,system calls,file system etc., These kernel layers cordinate together by message passing between them.Therby because of the message passing the microkernel is slower than the monolithic kernel.

Monolithic Vs Microkernel

Monolithic Kernel is faster than microkernel as stated above.However,Microkernel has some theoritical advantages over the monolithic kernel.They are as follows,

1.The microkernel occupies less RAM,since system processes(as disscussed above) that are not doing their functionalities are swapped out or destroyed.

2.The architecture of the microkernel forces the programmers to adopt a modularized approach

as different layers of the kernel are independant of each other.Moreover,the different layers interact with each other through clear well defined software interfaces.

3.Moreover, an existing microkernel operating system can be fairly easily ported to other architectures, since all hardware dependent components are generally encapsulated in the microkernel code.

Modules,the linux way

Modules are a kernel feature that effectively achieves many of the theoretical advantages of microkernels without introducing performance penalties. A module is an object file whose code can be linked to (and unlinked from) the kernel at runtime. The object code usually consists of a set of functions that implements a filesystem, a device driver, or other features at the kernel's upper layer. The module, unlike the external layers of microkernel operating systems, does not run as a specific process. Instead, it is executed in Kernel Mode on behalf of the current process, like any other statically linked kernel function.

Advantages provided by a monolithic kernel with modules

1.Less main memory usage

A module is linked to the kernel when its functionality is needed and unlinked when its no longer used.This mechanism is done automatically by the kernel and is transparent to the user.

2.Modularized approach

Modules force the programmers to intoduce well defined software interfaces for interaction.

3.Platform independence

A module does not depend on a fixed hardware platform.A module like device driver is infact specfic to the device but not to the hardware platform(x86,sparc etc..,)

4.Faster

Since the module is linked in to the kernel,it is faster like the monolithic kernel as there is no message passing as in microkernel.Infact there is small time we lose for linking and unlinking of the modules which is less than that of the time required for message passing in microkernels.

II.Linux Filesystem

Files are a basic abstraction provided by the operating system along with processes(more about processes later).A file is an information container structured as a sequence of bytes.From the user's point of view, files are organized in a tree-structured name space starting from /(parent) which is called the root directory.

Different file types in linux

The beauty of linux lies in the fact that it almost treats everything as files including devices. There are the following types of files

1. Regular files

2. Directory files

3. Symbolic links

4. Device files(character,block).

5. Pipes

6. Sockets

The first three types are constituents of the linux filesystem.Device files are related to I/O devices and device drivers integrated into the kernel.Pipes and sockets are special files used for interprocess communication.

Inode

All information needed by the filesystem to handle a file in included in a data structure called the inode.Each file has its own inode which the filesystem uses to identify the file.The following information is kept in the inode

1.File type(as discussed above)

2.Number of hard links associated with the file(see next section)

3.File length in bytes

4.Inode number that identifies the file within the filesystem

5.User ID of the file owner(discussed below)

5.Group ID of the file(discussed below)

6.The last modify time

7.Access rights and file mode (discussed below)

Hard links and symbolic links

The same file may have several links included in the same directory or in different ones, thus several filenames.

Hardlink

A hardlink is just a different filename but points to the same inode on the disc.So the file information of the both the file and the hard link will coincide as they point to the same inode.The unix command used to create a hard link is

$ln f1 f2

f2 is the hard link for file f1

Limitations of hard link

1.Hard links cannot exist to directories as it might transform the tree structure in to a graph with cycles thus making ti impossible to locate a file according to its name.

2.Hard links can be created only for files in the same filesystem as inode is the same.This is a serious limitation as Linux supports variuos other filesystems.

Softlink

Symbolic links are short files that contain an arbitrary pathname of another file. The pathname may refer to any file located in any filesystem,it may even refer to a non exixtent file or a file in another filesystem.Thus symbolic links are short files than contain the pathname of the file that is linked to.So a symbolic link will have a separate inode for itself.The unix command to create a symbolic link is

$ln -s f1 f2

f2 is a symbolic link to f1.The linux filesystem will create a sym link f2 and will write in to it the pathname for f1.In this way f2 can refer to f1.

Users and Groups

A multiuser system is a computer that is able to concurrently and independently execute several applications belonging to two or more users. "Concurrently" means that applications can be active at the same time and contend for the various resources such as CPU, memory, hard disks, and so on. "Independently" means that each application can perform its task with no concern for what the applications of the other users are doing.

In a multiuser system, each user has a private space on the machine: typically, he owns some quota of the disk space to store files, receives private mail messages, and so on. The operating system must ensure that the private portion of a user space is visible only to its owner. In particular, it must ensure that no user can exploit a system application for the purpose of

of violating the private space of the another user.

All users are identified by a unique number called the User ID , or UID. Usually only a restricted number of persons are allowed to make use of a computer system. When one of these users starts a working session, the operating system asks for a login name and a password.If the user does not input a valid pair, the system denies access. Since the password the assumed to be private the users privacy is maintained.In order to selectively share material with other users, each user is a member of one or more groups, which are identified by a unique number called a Group ID,or GID. Each file is associated with a UID and GID.

Access rights and mode

The users of a file fall in to one of this three classes

1.The owner of the file

2.The users who belong to the same groups as that of the owner

3.All other users(others) in the system

There are three types of access rights for each of these classes namely

Read,write and execute.

Thus the set of access rights associated with a file in linux consists of nine(3(for diff classes of users) * 3(for different access rights)) different flags.There are three additional flags which define the file mode which have a meaning when applied to executable files.They are

1.SUID flag

If the executable file has the SUID flag set, the process gets the UID of the file owner.

2.SGID

If the executable file has the SUID flag set, the process gets the GID of the file group.

The suid and sgid programs are important programs to be protected in a secure system as they change the id's during execution.So an intruder might use these programs for executing something malicious on behalf of the user who is suid or sgid.

3.sticky

An executable file with the sticky flag set corresponds to a request to the kernel to keep the program in memory after its execution terminates.These flag is set when many processes share the same program for example vi might be used by many processes.So vi can have its sticky bit set.This flag has become obsolete as other approaches like copy-on-write are used now for sharing code pages between processes.

chmod is the unix command used to allow the user to set access and mode flags for a file.

Example

$chmod 4777 f1

4777 in binary is 100111111111.So there are 12 bits corresponding to User classes,access and mode permissions as below.

100---will set the suid flag for f1(mode of the file)

111---will give read,write,exec access to owner of f1

111---will give read,write,exec access to other users of the group which the user belongs to.

111---will give read,write,exec access to other remaining users in the system.

Virtual File System technology

Linux follows a object oriented Virtual File System technology inspired from SVR4 and solaris.There linux supports most of the filesystems like DOS,FAT,ext3,resierfs,JFS etc..,Also porting a file system to Linux is very easy task because of the VFS technology that linux follows.

III.Processes in Linux

Process is another fundamental abstraction(apart from File) provided by the OS.Having seen a overview of the filesystem in linux let us see how linux handles processes.

A process can be defined either as "an instance of a program in execution," or as the "execution context" of a running program. In traditional operating systems, a process executes a single sequence of instructions in an address space,the address space is the set of memory addresses that the process is allowed to reference.Operating systems like linux allow multiple execution flows,that is,multiple sequences of instructions executed in the same address space.

Multiuser systems must allow different processes to be active concurrently and thereby contend for tbe resources,mainly the CPU.Such systems are said to be multitasking systems.The scheduler is the part of the kernel which decided which process will run on the CPU at a given instant of time.It is done in such a manner that every process feels that it is the only process running on the CPU.This concept is called virtualization of the processor.Another virtualisation that is provided by linux(or any OS) to processes is the virtual memory where in a process feels that it has the entire memory on system available to it.Processes of a multiuser system must be preemptive ie., the scheduler of the kernel will decide how long each process can hold the CPU.Thereby if a higher priority process comes in to execution the scheduler will preempt the lower priority running process.

Linux is a multiprocessing system with preemptive processes.

Process management in Linux

The fork( ) and exit( ) system calls are used respectively to create a new process and to terminate it.Linux maintains a clear distinction between the process and the program by using exec( )-like system call to load a new program.After exec has been done the process resumes execution with a brand new address space containing the loaded program.

Process Creation

Processes in Linux follow a parent child relationship.The Process which invokes the fork is the parent and the process that is created is the child.The init process(created by the init.c of the kernel) is the root parent of all the other processes in linux.The task_struct is the data structure in the kernel that defines the process.Parents and children can easily find each other as the data structure contains information about the relationship.Linux implements fork using the copy-on-write approach which defers address space duplication of parent to the child on fork.The address space is copied only when a write is being made in to the address space.So till a write happens the parent and the child share only the Page tables and not the address space.The copy-on-write has the following advantage

1.Most instances of fork are followed by an exec to a program as the child does some other functionailty when compared to the program.Thereby it is a waste(an overhead) to copy the address space of the parent to the child and then again immediately overwrite the address space.So this overhead is reduced by the copy-on-write approach.

Process Termination

The exit system call is used to terminate a process.The kernel handles this system call by releasing the resources owned by the process and sending the parent process a SIGCHLD signal, which is ignored by default.

Zombie processes

The parent enquires about the termination of the child process by the wait( ) system call which allows a process to wait until one of its children terminates; it returns the process ID (PID) of the terminated child.A special zombie process state is introduced to represent terminated processes on which the parent has not issued a wait system call.The process descriptor of the child is released after the wait is executed by the parent and the child process goes to the stopped state.Now the question arises if the parent does not issue a wait call and if it terminates what happens to the child in Zombie state.There will be many zombies which will occupy useful memory.The solution lies in init process which takes over as the parent of child process whose parents have terminated.It routinely issues wait calls thereby getting rid of the zombies.

IV.The process/Kernel model

Having known about the kernel architecture and the basic abstractions(file,process) let us now see how the linux kernel is modelled.On multiuser/multitasking systems the operating system must hide all low level details concerning the physical organization of the computer from applications run by user.So when a user application wants to access a hardware,it request the kernel which evaluates the request and if it chooses to grant access,it interacts with the hardware on behalf of the process.This thereby enhances the security on multiuser systems which prevent user applications from damaging the system hardware resources.Probably,this is the reason why DOS does not require such a model as it is single user system which allows the user to do anything with the systems hardware.

Well how does linux implement the above mentioned feature.All modern operating systems,implement the above mentioned feature with the help of hardware specific features which forbids the user programs to interact directly with the hardware.For example,the x86 CPU provides four rings of execution from ring 0 to ring 3 in the order of descending privileges.Linux uses the two rings namely ring 0 and ring 3 for implementing the feature.User mode applications run in ring 3 of x86 and kernel runs in ring 0 of x86.Therefore these rings correspond to the User mode and kernel mode concept of the linux operating system.

Note:Intel introduced protected mode(ring levels) starting from 80386.So Linux was developed for 80386 and above(commonly referred as i386/i686 architectures).

When a program is executed in User Mode, it cannot directly access the kernel data structures or the kernel programs. When an application executes in Kernel Mode, however, these restrictions no longer apply. Each CPU model provides special instructions to switch from User Mode to Kernel Mode and vice versa. A program executes most of the time in User Mode and switches to Kernel Mode only when requesting a service provided by the kernel. When the kernel has satisfied the program's request, it puts the program back in User Mode.

The kernel is a process manager and not a process by itself.The creation,deletion and handling of processes are done by a group of routines in the kernel.The process/kernel model in linux allows a process to request a kernel service through system calls.System calls thereby take the process from user mode to kernel mode,does the necessary request and puts the process back in the user mode.

A switch to Kernel mode from user mode will happen by any one of these methods

1.Through system call by a process as discussed above

2.The CPU exceutes an exception.The exception has to be handled by the kernel on behalf of the process that caused the exception.For example,the kernel must handle the page fault exception.

3.A device issues an interrupt to the CPU to notify the CPU an event.In this case the kernel executes the corresponding interrupt handler for the device.

Linux also has some privileged kernel level processes.They are called kernel threads.Linux uses kernel threads in a limited way for certain functionalites.They execute in the kernel thread.keventd is an example of a kernel thread.

V.Kernel Synchronisation

On multiuser/multitasking systems many processes must be handled by the kernel at a single instant of time as several processes may be executing in the kernel at the same time.For example ,a process executing on a CPU in a uniprocessor system might be waiting on some I/0.During this time the process in kernel mode is interleaved and another process is executed in the kernel.When the I/O interrupt is finished the process waiting for I/O is executed again.So the Linux kernel must be reentrant,ie..,multiple processes must be handled by the kernel maintaining the global data structures they use in a consistent state.

Before proceeding further,we will see the definition of a kernel control path.A kernel control path is a sequence of instructions executed in the kernel mode on behalf of a process or on behalf of an interupt.

How can Kernel reentrancy be achieved?

The following are the methods to achieve kernel reentrancy

1.Reentrant functions

2.Atomic operations

3.Non Premptive kernel

4.Interrupt disabling

5.Locking mechanisms(semaphores and spinlocks)

Reentrant functions

Reentrant functions are those functions which operate only on local variable and not on global data structures.But the kernel cannot only be limited to reentrant functions.Also the kernel has a fixed stack which is small,so local variable must be less.

Before looking at other mechanisms of achieving reentarncy let us see what a race condition is and what is a critical region.

Assume that there is a global data structure(a resource) R1.If R1 is one the resource is free.Now a kernel control path KCP1 reads the value of R1 which is 1 i.e.., the resource is free.Now if KCP1 is interleaved from the kernel and if KCP2 reads the value of R1 which is still 1.It will take the resource and decrement the value to 0.Now if KCP1 resumes execution it still sees that the resource is free and decrements the value of R1 to -1,thereby taking the resource.So both the KCP's are using the resources leading to dangerous effects.This is a race condition.

Atomic operations

It is always safe to access a global variable with a single atomic uninteruptible instruction.For example in the previuos example if the two kernel paths have read the data and decremented the value of R1 in a singl operation there would have been no race condition.

But its always not possible to access data structures in a single atomic operation.Any section of code that should be finished by a process befored another process is scheduled is called the critical region.Further mechanisms we will see how to protect critical regions.

Non Premptive kernel

A simple solution to synchronisation problems is to make the kernel non preemptive ie., when a process is in kernel mode it cannot be interleaved by any other process until it voluntarily relinquishes the CPU(in which case it makes sure that the Data structures are in a consistent state).Therefore in a non preemptive kernel all the global data structures except those that are used by interupts and exceptions are safe(as interleaving of a process in kernel mode happens when a interuppt or exception occurs).Non premptability is ineffective in Multiprocessor systems as two kernel control paths executing in different CPU's can access the same data structure.The linux kernel was non preemptable until 2.5 devt series and 2.6 stable series.Now the kernel is preemptible.Preemptible kernels are more suited for time critical real time processes.

Interrupt disabling

Another method to achieve synchronisation is to disable interuppts before entering a critical region and enabling it after the critical region.This is a simple solution but is not optimal as large critical region will have the Hardware interrupts freezed for a long time leading to a freeze.Also it is ineffective in multiprocessor systems as the data structure might be accessed by another process running in a different CPU.

Locking mechanisms

The locking mechanisms lock the corresponding global data structure in question thereby making sure that when the lock is acquired only a single process can access the data structure.They are effective both in Uniprocessor and Multiprocessor systems.The locking mechanisms used by the linux kernel are

1.Semaphores

2.Spin Locks

Semaphores

A semaphore is simply a counter associated with a data structure; the semaphore is checked by all kernel threads before they try to access the data structure.Each semaphore may be viewed as an object composed of:

a)An integer variable

b)A list of waiting processes

c)Two atomic methods: down() and up()

The down() method decrements the value of the semaphore. If the new value is less than 0, the method adds the running process to the semaphore list and then blocks (i.e., invokes the scheduler). The up() method increments the value of the semaphore and, if its new value is greater than or equal to 0, reactivates one or more processes in the semaphore list. Each data structure to be protected has its own semaphore, which is initialized to 1. When a kernel control path wishes to access the data structure, it executes the down() method on the proper semaphore. If the value of the new semaphore isn't negative, access to the data structure is granted. Otherwise, the process that is executing the kernel control path is added to the semaphore list and blocked. When another process executes the up() method on that semaphore, one of the processes in the semaphore list is allowed to proceed.

SpinLocks

In multiprocessor systems, semaphores are not always the best solution to the synchronization problems. Some kernel data structures should be protected from being concurrently accessed by kernel control paths that run on different CPUs. In this case, if the time required to update the data structure is short, a semaphore could be very inefficient. To check a semaphore, the kernel must insert a process in the semaphore list and then suspend it. Since both operations are relatively expensive, in the time it takes to complete them, the other kernel control path could have already released the semaphore. In these cases, multiprocessor operating systems make use of spin locks. A spin lock is very similar to a semaphore, but it has no process list: when a process finds the lock closed by another process, it "spins" around repeatedly, executing a tight instruction loop until the lock becomes open. Of course, spin locks are useless in a uniprocessor environment. When a kernel control path tries to access a locked data structure, it starts an endless loop. Therefore, the kernel control path that is updating the protected data structure would not have a chance to continue the execution and release the spin lock. The final result is that the system hangs.

Signals and interprocess communication

The linux kernel implements signals for communicating to the process an event.For example,SIGKILL is sent to the process if it receives a terminate signal.The linux kernel implements 32 different posix signals.User processes can communicate with each other with the help of SYS V IPCs like sahred memory,pipes,fifos,semaphores and message queues.

VI.Memory Management in Linux

Memory management is the most complex(as it is architecture dependant) and important activity in the kernel.Linux supports Virtual memory management.Linux uses paging to implement virtual memory concept.Linux does not use segmentation.Memory management will be described in detail in a later article.For now the advantages a virtual memory offers are

1.Several processes can be executed concurrently.

2.It is possible to run applications whose memory needs are larger than the available physical memory.

3.Processes can execute a program whose code is only partially loaded in memory.

4.Each process is allowed to access a subset of the available physical memory.

5.Processes can share a single memory image of a library or program

6.Programs can be relocatable, that is, they can be placed anywhere in physical memory.

7.Programmers can write machine-independent code, since they do not need to be concerned about physical memory organization.

RAM USAGE

The usage of memory is one very important thing that has to be taken care by the kernel.Linux clearly distiguishes between Memory that is dedicated to the kernel and the memory that can be used by the processes.The static kernel image is loaded from the 1st Megabyte of the RAM and is pinned(it is not swapped or paged out).The remaining part of the RAM is used for

1.Kernel dynamic structures

2.Memory for processes

3.Caches for disks etc., to get better performance.

How the memory is allocated for above mentioned three is very important and hence requires a separate article.In a few words, linux takes care of memory allocation problems like internal fragmentation,external fragmentation etc., by making use of buddy system algorithm and slab allocation mechanism.So Linux uses a Slab allocator on top of a buddy system algorithm.

Virtual Adddress space of a process

Every process in linux has a virtual address space(ranging from 0 to 4GB on a 32 bit intel CPU).

A address space of a process contains all the virtual memory addresses that the process can reference.The kernel usually stores a process virtual address space as a list of memory area descriptors(for example memory area descriptors to the code segment,stack segment,heap etc.,).Linux uses demand paging ie., the page is allocated after a page fault happens.

VII.Device drivers

Having discussed most of kernel subsystems namely filesystem,process,synchronisation,interrupts,syscalls,meory management lets see in a nutshell about device drivers.The kernel interacts with I/O devices with help of device drivers.Device drivers are included in the kernel and consist of data structures and functions that control one or more devices like hard disks,keyboard,mouse etc.,Each driver interacts with the remaining part of the kernel (even with other drivers) through a specific interface.There the device driver layer can be seen as the last layer in the kernel interacting with other layers through well defined interfaces.This approach helps programmers to write device specfic code in a separate module without knowing about the kernel source code as well as the internal architecture.

VIII.Linux implementation of threads

Finally,it is mandatory to discuss how linux supports multithreaded application programming as it does in a unique manner.In linux threads are also processes which share the address space of the processes.Linux implements threads as processes because the process creation time in linux is much faster compared to other OS'es.A thread is therefore a process which can scheduled independently of the main process and it shares the same address space.

SUMMARY

In summary a linux kernel is monolithic with modular support and consists of the following subsystems,

1.Filesystem

2.Process management

3.Memory management

4.Synchronisation

5.System calls

6.Device drivers

7.Interrupts and exceptions

8.Signals

The explanation and deciphering of the different kernel layers will be explained in future articles contirbuted by the various members of the lkg_india.I also promise two more articles which will be extension of this article namely

1.Linux kernel 2.6 features

2.Linux VS other Operating systems and the future of linux

Tuesday, September 15, 2009

Unix & Linux admin questions

1. How do you list the files in an UNIX directory while also showing hidden files?
2. How do you execute a UNIX command in the background?
3. What UNIX command will control the default file permissions when files are created?
4. Explain the read, write, and execute permissions on a UNIX directory.
5. What is the difference between a soft link and a hard link?
6. Give the command to display space usage on the UNIX file system.
7. Explain iostat, vmstat and netstat.
8. How would you change all occurrences of a value using VI?
9. Give two UNIX kernel parameters that effect an Oracle install
10. Briefly, how do you install Oracle software on UNIX.
11. What are the main differences between Apache 1.x and 2.x?
12. What does the “route” command do?
13. What are the read/write/execute bits on a directory mean?
14. What does iostat do?
15. what does vmstat do?
16. What does netstat do?
17. What is the most graceful way to bring a system into single user mode?
18. How do you determine disk usage?
19. What is AWK?
20. What is SED?
21. What is the difference between binaries in /bin, and /usr/bin?
22. What is a dynamically linked file?
23. What is a statically linked file?
24. How do you list the files in an UNIX directory while also showing hidden files? ls -ltra
25. How do you execute a UNIX command in the background? Use the “&”.
26. What UNIX command will control the default file permissions when files are created? umask
27. Explain the read, write, and execute permissions on a UNIX directory. Read allows you to see and list the directory contents. Write allows you to create, edit and delete files and subdirectories in the directory. Execute gives you the permissions to run programs or shells from the directory.
28. What is the difference between a soft link and a hard link? A symbolic (soft) linked file and the targeted file can be located on the same or different file system while for a hard link they must be located on the same file system.
29. Give the command to display space usage on the UNIX file system. df -lk
30. Explain iostat, vmstat and netstat. iostat reports on terminal, disk and tape I/O activity. vmstat reports on virtual memory statistics for processes, disk, tape and CPU activity. netstat reports on the contents of network data structures.
31. How would you change all occurrences of a value using VI? %s/(old value)/(new value)/g
32. Give two UNIX kernel parameters that effect an Oracle install. SHMMAX & SHMMNI
33. Briefly, how do you install Oracle software on UNIX? Basically, set up disks, kernel parameters, and run orainst.
34. Job Scheduling; mainly crontab, at, batch command
35. Backup stetegy; incremental, full system back up; diff between tar & ufsdump
36. diff between hard link & softlink
37. How to list only the directories inside a directory (Ans. ls -l|grep “^d”)
38. RAID levels; pros & cons of diffrent levels; what is RAID 1+0
39. How to recover a system whose root password has lost?
40. What is a daemon?
41. How to put a job in background & bring it to foreground?
42. What is default permissions for others in a file?
43. Questions on shell initialization scripts?
44. Questions on restricted shell
45. What is diff betwn grep & find?
46. What is egrep?
47. Questions on shell programming
48. What is a pipe?
49. Questions on Solaris patch management like pkgadd etc
50. Questions on file system creation; actually what happens when we create a file system?
51. Questions on RBAC? what is a role accound & what is a profile?
52. From command line how will you add a user account? the full command will all arguments.
53. Fs it advisable to put a swap partion in RAID1 (mirroring?) pros & cons?

Monday, September 14, 2009

Linux Interview Questions For software QA Engineers

Software testing - Questions and Answers - Linix / Unix
1. Q. How do you list files in a directory?
A. ls - list directory contents
ls �l (-l use a long listing format)
2. Q. How do you list all files in a directory, including the hidden files?
A. ls -a (-a, do not hide entries starting with .)
3. Q. How do you find out all processes that are currently running?
A. ps -f (-f does full-format listing.)
4. Q. How do you find out the processes that are currently running or a particular user?
A. ps -au Myname (-u by effective user ID (supports names)) (a - all users)
5. Q. How do you kill a process?
A. kill -9 8 (process_id 8) or kill -9 %7 (job number 7)
kill -9 -1 (Kill all processes you can kill.)
killall - kill processes by name most (useful - killall java)
6. Q. What would you use to view contents of the file?
A. less filename
cat filename
pg filename
pr filename
more filename
most useful is command: tail file_name - you can see the end of the log file.
7. Q. What would you use to edit contents of the file?
A. vi screen editor or jedit, nedit or ex line editor
8. Q. What would you use to view contents of a large error log file?
A. tail -10 file_name ( last 10 rows)
9. Q. How do you log in to a remote Unix box?
A. Using telnet server_name or ssh -l ( ssh - OpenSSH SSH client (remote login program))
10.Q. How do you get help on a UNIX terminal?
A. man command_name
info command_name (more information)
11.Q. How do you list contents of a directory including all of its
subdirectories, providing full details and sorted by modification time?
A. ls -lac
-a all entries
-c by time
12.Q. How do you create a symbolic link to a file (give some reasons of doing so)?
A. ln /../file1 Link_name
Links create pointers to the actual files, without duplicating the contents of
the files. That is, a link is a way of providing another name to the same file.
There are two types of links to a file:Hard link, Symbolic (or soft) link;
13.Q. What is a filesystem?
A. Sum of all directories called file system.
A file system is the primary means of file storage in UNIX.
File systems are made of inodes and superblocks.
14.Q. How do you get its usage (a filesystem)?
A. By storing and manipulate files.
15.Q. How do you check the sizes of all users� home directories (one command)?
A. du -s
df
The du command summarizes disk usage by directory. It recurses through all subdirectories and shows disk usage by each subdirectory with a final total at the end.
Q. in current directory
A. ls -ps (p- directory; s - size)
16.Q. How do you check for processes started by user 'pat'?
A. ps -fu pat (-f -full_format u -user_name )
17.Q. How do you start a job on background?
A. bg %4 (job 4)
18 Q. What utility would you use to replace a string '2001' for '2002' in a text file?
A. Grep, Kde( works on Linux and Unix)
19. Q. What utility would you use to cut off the first column in a text file?
A. awk, kde
20. Q. How to copy file into directory?
A. cp /tmp/file_name . (dot mean in the current directory)
21. Q. How to remove directory with files?
A. rm -rf directory_name
22. Q. What is the difference between internal and external commands?
A. Internal commands are stored in the; same level as the operating system while external
commands are stored on the hard disk among the other utility programs.
23. Q. List the three main parts of an operating system command:
A. The three main parts are the command, options and arguments.
24 Q. What is the difference between an argument and an option (or switch)?
A. An argument is what the command should act on: it could be a filename,
directory or name. An option is specified when you want to request additional
information over and above the basic information each command supplies.
25. Q. What is the purpose of online help?
A. Online help provides information on each operating system command, the
syntax, the options, the arguments with descriptive information.
26. Q. Name two forms of security.
A. Two forms of security are Passwords and File Security with permissions specified.
27. Q. What command do you type to find help about the command who?
A. $ man who
28. Q. What is the difference between home directory and working directory?
A. Home directory is the directory you begin at when you log into the
system. Working directory can be anywhere on the system and it is where you are currently
working.
29. Q. Which directory is closer to the top of the file system tree, parent directory or current directory?
A. The parent directory is above the current directory, so it is closer to
the root or top of the
file system.
30. Q. Given the following pathname:
$ /business/acctg/payable/supplier/april
a) If you were in the directory called acctg, what would be the relative
pathname name for the file called april?
b) What would be the absolute pathname for april?
A.
a) $ payable/supplier/april
b) $ /business/acctg/payable/supplier/april
31. Q. Suppose your directory had the following files:
help. 1 help.2 help.3 help.4 help.O1 help.O2
aid.O1 aid.O2 aid.O3 back. 1 back.2 back.3
a) What is the command to list all files ending in 2?
b) What is the command to list all files starting in aid?
c) What is the command to list all "help" files with one character extension?
A.
a) ls *2
b) ls aid.*
c) ls help.?
32. Q. What are two subtle differences in using the more and the pg commands?
A. With the more command you display another screenful by pressing
the spacebar, with pg you press the return key.
The more command returns you automatically to the UNIX
shell when completed, while pg waits until you press return.
33. Q. When is it better to use the more command rather than cat command?
A. It is sometimes better to use the more command when you are viewing
a file that will display over one screen.
34. Q. What are two functions the move mv command can carry out?
A. The mv command moves files and can also be used to rename a file or directory.
35. Q. Name two methods you could use to rename a file.
A. Two methods that could be used:
a. use the mv command
b. copy the file and give it a new name and then remove the original file if no longer needed.
36. The soccer league consists of boy and girl teams. The boy file names begin
with B, the girl teams begin with G. All of these files are in one directory
called "soccer", which is your current directory:
Bteam.abc Bteam.OOl Bteam.OO2 Bteam.OO4
Gteam.win Gteam.OOl Gteam.OO2 Gteam.OO3
Write the commands to do the following:
a) rename the file Bteam.abc to Bteam.OO3.
b) erase the file Gteam. win after you have viewed the contents of the file
c) make a directory for the boy team files called "boys", and one for the girl team files
called" girls"
d) move all the boy teams into the "boys" directory
e) move all the girl teams into the "girls" directory
f) make a new file called Gteam.OO4 that is identical to Gteam.OOl
g) make a new file called Gteam.OO5 that is identical to Bteam.OO2
A.
a) mv Bteam.abc Bteam.OO3.
b) cat Gteam.win -or- more Gteam.win
rm Gteam. win
c) mkdir boys
mkdir girls
d) mv Bteam* boys
e) mv Gteam* girls
f) cd girls
cp Gteam.OO1 Gteam.OO4
g) There are several ways to do this. Remember that we are currently in the directory
/soccer/girls.
cp ../boys/Bteam.OO2 Gteam.OO5
or
cd ../boys
cp Bteam.OO2 ../girls/Gteam.OO5
37. Q. Draw a picture of the final directory structure for the "soccer"
directory, showing all the files and directories.
38. Q. What metacharacter is used to do the following:
1.1 Move up one level higher in the directory tree structure
1.2 Specify all the files ending in .txt
1.3 Specify one character
1.4 Redirect input from a file
1.5 Redirect the output and append it to a file
A.
1. 1.1 double-dot or ..
1.2 asterisk or *
1.3 question or ?
1.4 double greater than sign: >>
1.5 the less than sign or <
39. Q. List all the files beginning with A
A. To list all the files beginning with A command: ls A*
40. Q. Which of the quoting or escape characters allows the dollar sign ($) to retain its special meaning?
A. The double quote (") allows the dollar sign ($) to retain its special meaning.
Both the backslash (\) and single quote (') would remove the special meaning of the dollar sign.
41. Q. What is a faster way to do the same command?
mv fileO.txt newdir
mv filel.txt newdir
mv file2.txt newdir
mv file3.txt newdir
A. A shortcut method would be: mv file?.txt newdir
42. Q. List two ways to create a new file:
A.
a. Copy a file to make a new file.
b. Use the output operator e.g. ls -l > newfile.txt
43. Q. What is the difference between > and >> operators?
A. The operator > either overwrites the existing file (WITHOUT WARNING) or creates a new file.
The operator >> either adds the new contents to the end of an existing file or creates a new file.
44. Write the command to do the following:
44.1 Redirect the output from the directory listing to a printer.
44.2 Add the file efg.txt to the end of the file abc.txt.
44.3 The file testdata feeds information into the file called program
44.4 Observe the contents of the file called xyz.txt using MORE.
44.5 Observe a directory listing that is four screens long.
A.
44.1 ls > lpr
44.2 cat efg.txt >> abc.txt
44.3 program < testdata
44.4 more < xyz.txt
44.5 ls > dirsave | more
45. Q. How do you estimate file space usage
A. Use du command (Summarize disk usage of each FILE, recursively for
directories.) Good to use arguments du -hs
(-h, --human-readable print sizes in human readable format (e.g., 1K 234M 2G)
(-s, --summarize display only a total for each argument)
46. Q. How can you see all mounted drives?
A. mount -l
47. Q. How can you find a path to the file in the system?
A. locate file_name (locate - list files in databases that match a pattern)
48. Q. What Linux HotKeys do you know?
A. Ctrl-Alt-F1 Exit to command prompt
Ctrl-Alt-F7 or F8 Takes you back to KDE desktop from command prompt
Crtl-Alt-Backspace Restart XWindows
Ctrl-Alt-D Show desktop
49. Q. What can you tell about the tar Command?
A. The tar program is an immensely useful archiving utility. It can combine
an entire directory tree into one large file suitable for transferring or
compression.
50. Q. What types of files you know?
A. Files come in eight flavors:
Normal files
Directories
Hard links
Symbolic links
Sockets
Named pipes
Character devices
Block devices
51. Q. How to copy files from on PC to another on the same network
A. Use the following command:scp yur_file you_login@your_IP
example: copy .conf file from your PC to alex computer-
scp /etc/X11/xorg.conf alex@10.0.10.169:
52. Q. Please describe information below:
-rw-rw-r-- 1 dotpc dotpc 102 Jul 18 2003 file.buf
drwxr-xr-x 9 dotpc dotpc 4096 Oct 21 09:34 bin
lrwxrwxrwx 1 dotpc dotpc 20 Mar 21 15:00 client -> client-2.9.5
drwxrwxr-x 11 dotpc dotpc 4096 Sep 2 2005 client-2.8.9
drwxrwxr-x 7 dotpc dotpc 4096 Dec 14 12:13 data
drwxr-xr-x 12 dotpc dotpc 4096 Oct 21 09:41 docs
drwxr-xr-x 5 dotpc dotpc 4096 Dec 7 14:22 etc
drwxr-xr-x 11 dotpc dotpc 4096 Mar 21 15:54 client-2.9.5
-rw-r--r-- 1 dotpc dotpc 644836 Mar 22 09:53 client-2.9.5.tar.gz
A. This is a result of command $ls -l
we have two files, 6 directories and one link to client-2.9.5 directory.
There is number of files in every directory, size and data of last change.
53. Q. If you would like to run two commands in sequence what operators you can use?
A. ; or && the difference is:
if you separate commands with ; second command will be run automatically.
if you separate commands with && second command will be run only in the case
the first was run successfully.
54. Q. How you will uncompress the file?
A. Use tar command (The GNU version of the tar archiving utility):
tar -zxvf file_name.tar.gz
55. Q.How do you execute a program or script, my_script in your current directoty?
A. ./my_script
56. Q.How to find current time configuration in the file my_new.cfg
A. grep time my_new.cfg
Grep searches the named input files (or standard input if
no files are named, or the file name - is given) for lines
containing a match to the given pattern.
Q. What does grep() stand for?
A. General Regular Expression Parser.
57. Q. What does the top command display?
A. Top provides an ongoing look at processor activity in real
time. It displays a listing of the most CPU-intensive
tasks on the system, and can provide an interactive inter­
face for manipulating processes. (q is to quit)
58. Q. How can you find configuration on linux?
A. by using /sin/ifconfig
If no arguments are given, ifconfig displays the status of the cur-
rently active interfaces. If a single interface argument is given, it displays the status of the given interface only; if a single -a argu-
ment is given, it displays the status of all interfaces, even those
that are down. Otherwise, it configures an interface.
59. Q. How to find difference in two configuration files on the same server?
A. Use diff command that is compare files line by line
diff -u /usr/home/my_project1/etc/ABC.conf /usr/home/my_project2/etc/ABC.conf
60. Q. What is the best way to see the end of a logfile.log file?
A. Use tail command - output the last part of files
tail -n file_name ( the last N lines, instead of the last 10 as default)
61. Q. Please write a loop for removing all files in the current directory that contains a word 'log'
A. for i in *log*; do rm $i; done
62. Question: How to switch to a previously used directory?
Answer: cd -
1. Q.How many VI editor modes do you know?
A.Three modes -
Command mode: letters or sequence of letters interactively command vi.
Insert mode: Text is inserted.
Command line mode: enter this mode by typing ":" and entry command line at the foot of the screen.
2. Q. How can you terminate VI session?
A.
# Use command: ZZ that is save changes and quit.
# Use command line: ":wq" that is write changes and quit.
# Use command line: ":q!" to ignore changes and quit. 3. Q. How can you copy lines into the buffer in command mode? A. yy - copy a single line defined by current cursor position 3yy - copy 3 lines. Current line and two lines below it.

 
Things You Should Know About Linux !!!