Posts

Showing posts from 2010
Conditional command execution -it is possible to specify that a command in a script will only run if particular condition Is met - such conditions are always expressed in terms of the exit status of another program, as follows: Command1 && command2 Means that command2 will only run if command1 Completes with an exit status of 0 Command3 || command4 Means that command4 will only run if command3 completes with an exit status that is not 0 For example: ls file1 && cp file1 ./tmp cp abc xyz && echo The file was copied OK diff fileA fileB || echo The fiels are different ls file2 || exit -The only problem with these constructs is that they are very limited: - You can only perform one command if the condition is met (however, it is possible to group commands) - You cannot specify a second command to be run If the condition is not met The if Statement -A much more powerful (and readable) shell programming construct is the if stat

bash | read variable

Many shell variables are inherited from the login shell Environment. In other words, they are preset variables For example, when running a script the following Variables will be available (amongst others): -HOME -PATH -LOGNAME -TERM echo $LOGNAME --> iam user Such variables may be changed by the script, but the changes will not be seen by the login shell unless the script was run using the "." operator. llist=`who | sort` #shell command echo $llist llist=who | sort #string echo the date is `date +%m/%d/%y` today Groupping commands: ( ls date ) Please enter your name: ; read name Tom and Jerry echo $name Tom and Jerry Please enter your name: $name This command is split \ over several lines ------- Conditional code True and False -When every UNIX command completes, it invisibly Returns a value to the program that started it (usually the shell) Informing that program of the "status" of completiono f the command - This

run bash | set variables

If it ever becomes necessary to pass one of the special Characters as a parameter to another program, one of three Actions is required: -prefix the character with a \ (for example, \$) -surround the character with a pair of " (for example "#") Note, this doesn't work for all characters - surround the character with a pair of ' characters (for example '$') This works for all characters except ' echo "the fee is $10" --> the fee is 0 echo 'the fee is $10' --> the fee is $10 echo the fee is \$10 --> the fee is $10 echo the fee is "$"10 --> the fee is $10 echo the fee is "$10" --> the fee is 0 There are 4 ways to run a shell script on the command-line 1.myscript The script must be executable 2.sh myscript Technically the same as method 1., but the file doesn't need To be made executable 3. .myscript The commands in the script are executed by the CURRENT shell 4.exec m
echo enter your name: read name Mark V echo hello $echo read number stree type 12 Smith Road echo $number -->12 echo $street -->Smith echo $type --> Road If more words are provided than there are variables, the Extra words are added to the last variable If not enough words are provided, the extra variables will Contain nothing cat f echo -n "Enter your name:" read name echo Hello, $name Позволяет вводить значение переменной в той же строчке cat f echo "Enter your name:\с" read name echo Hello, $name \с такой же результат что и -n -- Standard Error is a separate stream from Standard Output, And mey be redirected to a file using 2> For example: ls a f ls a f d > filelist 2> errors cat errors Невозможно получить достук к d -- Standard Output and Standard Error can be directed to the same file as follows: ls a f d > filelist 2>&1 -- Any unneeded output may be redirected to the special file /d
#mv folder newfolder Если папка newfolder уже существует, папка folder Копируется в папку newfolder. Если папки newfolder нет, folder переименовывается в Папку newfolder man -k = apropos nohup command & - выполнение команды будет продолжено после выхода из системы Весь вывод команды сохраняется в файле nohup.out Cmp Diff Echo * == ls rename 's/\.bak$//' *.bak - strips .bak from the filename Экземпляр выполняющейся программы - процесс Например, wc - это программа; каждый раз когда она запускается, создается новый процесс (со своим PID) ps -ax (BSD) = ps -ef (System V) ps -ag - показывает информацию о процессах, Исполняющихся в этот момент. export - позволяет использовать переменные в разных программах Byte= symbol in unix file - команда делает предположение о типе файла crypt - используется для шифрования файлов от root'a newgrop - изменяет текущую группу пользователей /etc/passwd - регистрационный файл /bin/passwd - программа дл
Mainteance of Linux System part 2 $tar cvpf /mnt/zip/tarball1 /home /etc tar options: --diff (short d) --compare Tar commands for incremental and differential backups: $Tar cvpf /mnt/zip/tarball1 --newer 20May02 /home /etc This command backups all data since 20May02 Linux-backup.net Tar restore: $rm linux-syllabus.txt In tar backups "/" are removed /home/perry/linux...... $cd / $tar xvpf /mnt/zip/tarball1 home/perry/linux-syllabus.txt $tar tvpf /mnt/zip/tarball1 | more - lists all contents of archive SWAP Space vs. Main Memory (RAM) Active to Idel and vice verse How much memory and SWAP should you have? $free $free -s 5 - runs free every 5 seconds SWAP PARTITIONS $su $dd if=/dev/zero of=/swapfile bs=1024 count=1024 (add 1 mbyte swap file) $mkswap /swapfile $swapon /swapfile $free $swapoff /swapfile - turn off swapfile #df - display available space #man gdb - GNU Debugger Gdb -c corefile --- shows what program

id | chpasswd < file

id - print user identity apropos - search the manual page names and descriptions apt - Advanced Package Tool APT is a management system for software packages. Apt returns zero on normal operation, decimal 100 on error Way How to change passwords for all users: 1) create filetochangeps username01:password01 username02:password02 username03:password03 2) chpasswd < filetochangeps
Hardware Issues in Linux Hardware Drivers - where are they? -In the kernel -Manufacturer (of hard driver) -Special development projects Linux Hardware Projects Scanners: www.sane-project.org SANE = Scanner Access Now Easy USB Devices: www.linux-usb.org Adding Hardware 1.Physical connect it 2.Set jumpers 3.Load & Configure Drivers 4.Make device accessible to users Physical Connect Device Possibilities: -External Device -Internal Device -Expansion Cards Kernel Modules Controlled by /etc/modules.conf (or conf.modules) Commands Insmod, modprobe,lsmod insmod - f --- force installation
Troubleshooting in Linux Part 3 Backup/Restore Errors Computer-side problems -Drivers -Device permissions -File permissions Backup device-side problems -Media errors (corrupted) Donot GZIP file! Because it uses sequential coding for compression You have to backup of backups. Other branch of the same organization. Sdf.lonestar.org - Public UNIX access Hotscripts.com Perlcoders.com - sysmonitors scripts Network Structure User (209.11.135.226) <----> (Gateway) <--Nameserver->>--Linux.org-> Could locate cbtnuggets.com 1) ping 127.0.0.1 --- your network card is disabled? #/etc/init.d/network restart ping 127.0.0.10OK? 2) ping 209.11.135.226 - not local problem #route 127.0.0.1 - l0 209.11.135.224 - eth0 --- wire plugged? 3) #route --- shows gateway address ping gateway --- OK? 4) #dig www.linux.org - display what nameserver is used LINUXQUESTIONS.org Troubleshooting -Backup/Restore problems -Application Failures on Servers -Diagnosis Networking Problems -Outside help

troubleshooting /var/log syslog.con dmesg rout lpq kill

Troubleshooting Problems in a Linux System Types of Problems - Hardware - Operating System (Kernel) - Application Software - Configuration (change /etc files, change .dotfiles) - User Plan of Attack 1.Observe problem first hand 2.Formulate a guess as to cause 3.Attempt to fix 4.Go back to step 1 until fixed Preventative Measures - Buy supported hardware - Stay away from untested software (Beta versions) - Don't overclock your processor #cd /var/log boot.log - information about boot messages mail.log - info about mail utility To keep track what does each files hold: #cd /etc/ #more syslog.conf #man syslog.conf: Here you can find priorities: debug,info,notice,warning,warn,err,error,critical,alert,emerg(should be fixed imidiately),panic #Don't log private authentication messages *.info;mail.none;authpriv.none;cron.none /var/log/messages #Log all the mail messages in one place mail.* /var/log/maillog #Log cron stuff cron.* /var/log

free | dd | df

free - display amount of free and used memory free -s dd if=/dev/zero of=/swapfile bs=1024 count=1024 mkswap /swapfile swapon /swapfile swapoff /swapfile df - disk space is used

types of backup

Mainteance of a Linux System You can use cron to run scripts on regular Backing up your system Options: Tape,ZIP,CD Tradeoffs: 1. $/GB 2. sequential vs. random access (faster) 3. capacity Types of backup 1.Full - every (every month) 2.Incremental - daily backups (every thing since last incremental backup) To restore system, you should restore Full backup and all 29 incremental backups 3.Differental Everything since last Full backup To restore syste, 1 Full backup + 1 differential backup
Runlevels 0 - off 1,s - single-user mode 2 - multi-user, without networking 3 - multi-user with networking 4 - varies 5 - X windows 6 - Shutdown, reboot
SET (tmp, variables, etc in Windows) = env in Linux which grep which pwd shows where grep,pwd and other program is situated

ls -lartR

ls -lt | more - show files by page ls -lart R -- recursevily shows all files from current folder and down
SUID permissions cd usr/bin --> ls -la smb* s - fileparameter means that every user can access it NFS mount adams :/home/johndoe /mnt/doe all files permissions carries from /home/johndoe to /mnt/doe more /etc/fstab cd /etc/ more exports cat > exports /home nugget1(rw) baker(rw) carl(ro) CTRL-D to exit rw- read write ro- read only
To share files between Linux and Windows machine --> SAMBA, NFS To initiate printer linux uses lpr command lpr takes the thing you want to print and gives it to lpd lpd - line printer domain lpd decides which print queue should print going USER-->lpr -->lpd --> print queue -->printer lpd doesn't know where lpr come from. from local or remote machine. When you prints something --> thing that you want to print transform into postscript postscript - is standard printer language. Printer is postscript cabable (ready) (DRIVER; Ghostscript) is used to translate between two languages.(postscript translates into driver) Print Queues /var/spool/lpd Config Files /etc/printcap A Hernative Printing Systems BSD - Berkley Standard Distribution LPRng CUPS - Common Unix Printing System /etc/cups Lets configure printer for the computer $printtool --- graphical user interface /etc/printcap - is generated when lpd is initiated $lpr -P hp1 d
Linux Essentials (CD2) Lilo (Linux loader) 1)First boots BIOS 2)Test hardware 3)Master boot record (stored bootloader) cat /etc/lilo.conf.anaconda default=linux boot=/dev/sda
X Windows components: - X Server ( www.xfree86.com ) - Window Manager (control look and feel) Most popular Window Managers:KWM,Sawfish - Desktop Environment (add utilities and config programs) Most popular desktop environments: KDE (key desktop environment), Gnome, CDE Xconfigurator Shell Scripting -mini-programs using shell commands cat,useradd -used for repetitive tasks (backups, startup, adding users) -good for inexperienced users Any script should have extension .sh #! /bin/bash -- path of the shell # <-- comment This is a silly script echo "this is a script" echo "what do you think?" # this is also a comment bash demo1.sh <-- run the script ./demo1.sh <-- also run the script #! /bin/bash echo "Hello $1." #parameter of the progrma NUMBER1=234 # local variables NUMBER2=456 let NUMBER3=$NUMBER1+$NUMBER2 echo "The answer is $NUMBER3" ./demo2.sh perry Hello perry The answer is 690 du
Список администраторов хранится в файле gshadow группа:пароль:админы:пользователи
Chown bob.project ProjX/ - changes ownership for group Chgrp Addgroup Newgroup ProjectX -> changes current group Than when you create directory , it owns by group ProjectX gpasswd - A bob ProjectX --> Now bob is administrator of group ProjectX gpasswd - a alice ProjectX --> Add alice to the group ProjectX gpasswd - d alice ProjectX --> Del alice to the group ProjectX
Administration of Networks in Linux -Overview -Configuration -Remote Access -Conytolling Access -Remote administration Network Overview -Hardware -Packets (information that transfers between computers) -Protocols (rules for packets) -Addressing (make hardware decide how move through the network) netconfig (Red Hat tool) - network configuration cd /etc/sysconfig/network-scripts/ cat ifcfg-eth0 uname -a --- shows the version of linux kernel email software - Balsa SECURITY SITES: linux-sec.net linux-firewall.com firewalls - can block access to any services inetd /w TCP Wrappers and xinetd - can block access to specific services inetd, xinetd - are superdaemons TCP Wrapper /etc/hosts.allow /etc/hosts.deny/ holds information about hosts that can access and cann'r access your system If information contains in allow and deny ->> allow xinetd.org Using X remotely (i.e. to connect to baker from adams) 1.Log into adams 2.type "xhost +baker" 3.log into baker with ssh 4.typ

major directories | filesystems

Administration of Filesystem and Security -Mount/Manage Filesystems, Partitions, Devices -Security : Best Practices, RisksFilesystems, Partitions, Devices commands: -  mkfs  (create partition),  fdisk, fsck  (examine partitions, check partition for errors) -  mount, umount  (partitions and devices) -  df  (file system usage), du (info on disk usage) -  /mnt, /dev  (important direcotries) What's a filesytem? 1)Directory structure /etc/home 2)Low-level organization Ext2fs Ext3 ReiserFS fdisk -l  --->lists all disks sda  (scsi disk, A- first disk) sdb  - second disk boot *  - holds linux kernel image Swap partition gets used when main memory fills up (RAM) Swap like extension main memory We don't need swap partition and can use swap files, but swap files work much slower fdisk /dev/sda When you add new disk, you should add a new partition with command  fdisk /dev/sda fsck /dev/sda2  - Here you can see filesystem (EXT2 FS,etc) Administration of Files
Directory modes rwx -> full access r-x -> limited access (enter, read) --- -> no access d rwxr-x--- - directory permissions su root, su iam - switch user gpasswd -A bob projectX - user bob now is administrator of this group su bob gpasswd -a alice projectX (Adding user alice to group projectX) gpasswd -d candy projectX

File permissions

File Permissions (Modes) - Separate Permissions for User (owner of the file), Group, Other ls -l -- shows modes - rwxr-xr-- MEANS THAT THIS IS NOT A DIRECTORY - rwx r-xr-- User permission of the file (Read, write and execute) -rwx r-x r-- Groups permissions of the file -rwxr-x r-- Others (everyone of the system can read the file) -Root & Owner can change modes ------------- Changing file permissions chmod  has 2 formats 1.Symbolic chmod g+w filename (add permission to the group) chmod o-w filename (deny permission to the others) chmod ug=rw filename <<--means data-blogger-escaped-for="" data-blogger-escaped-permission="" data-blogger-escaped-strong="">users and group for read/write and NO ACCESS for Others 2.Binary Number chmod 754 filename 754  means 7-U, 5-G,4-O 7= 111 , 5= 101 , 4= 100  -->> - rwx r-x r--
cat /etc/passwd lisa:x:501:501::/home/lisa:/bin/bash x-password) userID=501 groupID=501 :(commend): - not presented here /home/lisa - home directory cat /etc/shadow - stores encrypted passwords useradd -c "Peter Ivanov" pivanov groupadd newgroup cat /etc/group usermod -G newgroup,projectX,progectY bob groups bob
-Add,Remove, Modify -Groups-Permission (modes) Users in LinuxUser=Account Account Attributes: User name, default shell, default group, expiration date,... Special Account -> Superuser (root) Useradd,userdel,usermod (in /usr/sbin) Default config files in /etc/skel Useradd -D - current user config

packages installation

Installing Software (aka packages) - tar files - RPM RedHat Package manager - DEB Debian Package manager Database have info about what packages were installed You can mix RPM and DEB RPM - used by many distributions RH, Mandrake, Linux PPC, ... - naming convention: packagename-a.b.c.-x.arch.rpm (arch=386,586,686,PPC,SRC source code) Rpm [operations: I - install, u - update, q - query (query database), e - uninstall] [options: --force, --nodeps] [packages] Rpm - ivh packagename.rpm www.rpmfind.net www.rhn.redhat.com Debian Package Management - used by debian && offshoots (Storm, Corel) - commands: dpkg, apt-get Tar file - works on every distribution - more work to install - basic use: tar xvf pkg.tar(tgz - zipped) pkg_directory /etc/init.d/httpd start - start Apache /var/www/html -> index.html
Installation of LinuxMethods: Text, GUI, Scripted (optional) - on multiple machinesNetwork installation (ftp,http,LAN) - otherwise choose text or GUI Network installation not for novice users What type of system would you like to install? - Workstation- Server- Laptop- Custom- Upgrade existing systemDisk partitioning setup Autopartition (basic partition), Disk Druid (partition yourself), fdiskAutopartition -> Automatic Partitioning : -Remove all Linux Partitions on this system -Remove all partitions on this system-Keep all partitions and use existing free spaceDevice/dev/sda (scsi disk) - holds info of every partition/dev/sda1 - Mount Point /boot/dev/sda2 - Mount Point /Boot Loader Configuration -Use GRUB Boot Loader -Use LILO Boot Loader -No Boot LoaderBoot Loader Password:___ Confirm:___ Firewall Configuration: Security Level: High, Medium, No firewall Root Password: Add User: User ID Password Full Name User Account Setup: Authentication Configuration - Use Shadow Passwords -

filesystems

Linux supports numerous file system types Ext2: This is like UNIX file system. It has the concepts of blocks, inodes and directories. Ext3: It is ext2 filesystem enhanced with journalling capabilities. Journalling allows fast file system recovery. Supports POSIX ACL (Access Control Lists). Isofs (iso9660): Used by CDROM file system. Sysfs: It is a ram-based filesystem initially based on ramfs. It is use to exporting kernel objects so that end user can use it easily. Procfs: The proc file system acts as an interface to internal data structures in the kernel. It can be used to obtain information about the system and to change certain kernel parameters at runtime using sysctl command. For example you can find out cpuinfo with following command:
How to get kernel info kernelversion ls /boot
ls -a - (all) shows user config files .bash_history .gnome - desktop environment ls -l - use a long listing command su - switch to the administrator accound cd / - very top directory cd bin - here are situated the most common commands .bashrc - contains aliases (should run after modification -> source .bashrc )
pwd (Print Working Directory) cp - copy rm -i file.txt - ask YES/NO mv - move cd .. rmdir mkdir Text editors emacs; vi - 3 modes command (insert) exec mode (write file, quit) edit mode press ESC to go to the command mode В редакторе vi есть два основных режима: командный режим и режим вставки . По умолчанию, работа начинается в командном режиме. В режиме вставки клавиатура используется для набора текста. Для выхода в командный режим используется клавиша Esc или комбинация Ctrl + c . В командном режиме алфавитные клавиши соответствуют командам перемещения и изменения текста. Команды h , j , k , l перемещают курсор на одну позицию влево, вниз, вверх, вправо соответственно, команда x удаляет один символ и т. д. Для полнотекстовых операций имеется возможность задавать команды ex в подобии командной строки, например, :1,.s/wiki/[[wiki]]/g заключит все вхождения последовательности символов wiki от начала текста до текущей позиции в двойные квадратные скобки. [ править