Monday, 12 December 2016

RHCSA

clear or ctrl+l   #clear the screen
;        #if want to type more than 1 command on a single line
which vim     #shows the full path of vim commands.
man -k passwd     #-k is keyword, search the command got man page or not
Chapter 2 - Managing Files:
touch song{1..5}    #or touch lagu1 lagu2 lagu3  #create empty file
ls -R     #-R is recursive
mv chapter2.odf chapter2_review.odf       #rename
echo "The price of cola is \$20.00"     # \ is escape character
Practice:
1) touch song1.mp3 song2.mp3 song3.mp3 song4.mp3 song5.mp3 song6.mp3
2) mv song1.mp3 song2.mp3 song3.mp3 song4.mp3 song5.mp3 song6.mp3 Music   
#the last argument must be a directory
3) mkdir friends family work     #create 3 directory
4) cd friends
     cp ~/Music/song1.mp3 ~/Music/song2.mp3 .     #copy files to currect directory
5) rm -r friends     #remove directory with files inside, cannot use rmdir friend
6) rmdir family work     #remove empty directory
Lab:
1) touch tv_season{1..2}_episode{1..6}.ogg     #create 12 files
2) mkdir Video/season{1..2}        #create 2 subdirectory
3) cp chapters.odf chapters_$(date +%d%m%y).odf       #$() is command substitution
Chapter 4 - Creating, Viewing and Editing Text Files:
cal > cal.out1   #redirect stdout to overwrite a file
echo "My name is Steve" >> cal.out1        #redirect stdout to append a file
find /etc -name passwd 2> /tmp/errors       
#redirect errors to a file (coz normal users are denied access to system directory)
find /etc -name passwd > /tmp/output 2> /tmp/errors   
# redirect stdout and error messages to separate files
find /etc -name passwd > /tmp/output 2> /dev/null    #discard error messages
find /etc -name passwd &> /tmp/save-both   #store output and error messages together
find /etc -name passwd >> /tmp/save-both 2>&1       #append output and errors to existing file
Lab:
1) ls -al > editing_final_lab.txt
2) V        #enter visual line, select 1st 3 lines
     x       #delete 1st 3 lines
3) v       #enter visual character, select 1st line permission
     x        #delete 1st line permission
4) Ctrl+v              #enter visual block, select all the permission column
     x            #delete all the permission column
Chapter 5 - Managing Local Linux Users and Groups:
userdel -r stanley            #delete user and user's home directory
groupdel javaapp              #delete a group
usermod -e 1 dolly   #immediately expire the user
usermod -e -1 dolly    #will set “Account expires” to never
usermod -s /sbin/nologin reba       #user cannot login to the system
Practice (Managing groups):
1) groupadd -g 30000 shakespeare       #create new group with group ID 30000                 
2) usermod -G shakespeare juliet            
#add user juliet to the shakespeare group as a supplementary group
3) id juliet        #show user and group id
Practice (Managing user password aging):
1) usermod -L romeo              # lock romeo account
2) usermod -U romeo           #unlock romeo account   
3) chage -M 90 romeo            #require new password every 90 days for romeo
     chage -l romeo          #-l is show account aging information
4) chage -d 0 romeo           
#change password for next logon.  -d is set date of last password change            
5) date -d "180 days"   #determine a date 180 days
6) chage -E 2016-08-31 stanley        #set accounts to expire a date 180 days
Lab:
1) vim /etc/login.defs            
#all newly created users must change password every 30 days
     PASS_MAX_DAYS   30
2) groupadd -g 40000 consultants
3) useradd -G consultants sam
     useradd -G consultants betty
     useradd -G consultants dick
4) chage -d 0 sam          
     chage -d 0 betty
     chage -d 0 dick
5) date -d "+90 days"  
     chage -E 2016-07-19 sam
     chage -E 2016-07-19 betty
     chage -E 2016-07-19 dick
6) chage -M 15 betty
Chapter 6 - Controlling Access to Files with Linux File System Permissions:
1) drwxrwxrwx     #d is directory
2) chown abu:ladmin sample.txt               
#Change the owner to abu and change the group to ladmin for sample.txt
3) chmod a+r sample.txt      #a is all
     chmod ug-rw sample.txt     #u is user, g is group, o is others
4) setuid =4 (only executable file) ;
setgid=2 (only execuatable file and want inherit directory) ;
sticky=1 (only owner can delete own file directory)
5) ls -l /usr/bin/passwd    
#setuid, only meaningful to executable file. All users can run this executable file


    chmod 4600 test.exe       #setuid to executable file. 4 is setuid     

6) chmod 2600 test2.exe           
#setgid to executable file. 2 is setgid. All users can this executable file,
#when user run this file, will represent group owner   
  
7) ls -ld /tmp      
#sticky bit to directory only. Only owner can delete the files they own

     chmod 1777 /testdir   
#set sticky bit to directory only. Better put permission 777 for all users and groups to write

Practice (Managing file security):
1) mkdir /home/ateam-text
2) chown :ateam /home/ateam-text         #change group ownership to ateam
3) chmod g+w /home/ateam-text          # allows group members to create and delete files
4) chmod 770 /home/ateam-text           #forbids others from accessing its file
     ls -ld /home/ateam-text 
Practice (Controlling new file permissions and ownership):
1) umask    #check default umask value (default permission)
     '0022     #file = 666, dir = 777. default file is 644, default dir is 755.
2) mkdir /tmp/shared
     ls -ld /tmp/shared
     drwxr-xr-x. 2 root root 6 Mar  7 10:58 /tmp/shared     #default dir is 755.
3) chown :ateam /tmp/shared         #change the group ownership
     ls -ld /tmp/shared
     drwxr-xr-x. 2 root ateam 6 Mar  7 10:58 /tmp/shared
4) touch /tmp/shared/alice3
     ls -l /tmp/shared/alice3
     -rw-r--r--. 1 root root 0 Mar  7 11:02 /tmp/shared/alice3   
#new file in /tmp/shared/ will not be inherited for group ownership
5) chmod g+s /tmp/shared         
#setgid, file created in the /tmp/shared will be inherited the group ownership
     ls -ld /tmp/shared
     drwxr-sr-x. 2 root ateam 19 Mar  7 11:02 /tmp/shared/      #check and confirm
     touch /tmp/shared/alice4
     -rw-r--r--. 1 root ateam 0 Mar  7 11:13 /tmp/shared/alice4
6) vim ~/.bashrc           #change the default umask for alice
     umask 007       #add at the end. Prohibit all access for users not in the group
      #log out and back to confirm persistent
Lab:
1) mkdir /home/stooges
2) chown :stooges /home/stooges       #change group permission
3) chmod 2770 /home/stooges        
#setgid, file created in the /tmp/shared will be inherited the group ownership.
#770 is Prohibit all access for users not in the group
     ls -ld /home/stooges          #check and confirm
4) vim /etc/bashrc              #change the global default umask
    vim /etc/profile
Chapter 7 - Monitoring and Managing Linux Processes:
1) sha1sum /dev/zero > /dev/null &    
#start the process. when sha1sum compute /dev/zero,
#it will keep on changing and keep generating the process,
#will give a lot of output, that's why put into /dev/null
2) ps -eaf | grep sha1sum            #to get the process id
     ps aux | grep sha1sum   #check process state
3) kill -l                # -l is list all the kill option
4) kill 32525              #default is -15 (grace kill). -9 is force kill
     * killall sha1sum    #killall has to put process name
5) grep "model name" /proc/cpuinfo     #check how many cpu
6) top
     M           #sort by memory
     P          #sort by cpu utilization
Practice (Background and Foreground Processes):
1) in left terminal, (while true; do echo -n "rock " >> ~/outfile; sleep 1; done)        
#start a process that continuously appends the word "rock" and
#a space to the file ~/outfile at one-second intervals
2) in right terminal, tail -f ~/outfile        #-f is follow. Will continue show as file grow
3) in left terminal, ctrl+z        #temporary stop the process            
4) in left terminal, jobs          #+ is current job
     bg               #restart the job in background
     jobs      #check and confirm
5) in left terminal, (while true; do echo -n "paper " >> ~/outfile; sleep 1; done) &         
#& is run at the background
     (while true; do echo -n "scissors " >> ~/outfile; sleep 1; done) &
     jobs       #check and confirm
6) in left terminal, fg %1              #bring the job "rock" to foreground. 1 is job id
     ctrl+z       #temporary stop the process            
     jobs      #check and confirm
7) in left terminal, fg %2      #bring the job "paper" to foreground. 2 is job id
     ctrl+c        #permanent stop the process            
     jobs     #check and confirm
8) in left terminal, ps j     # j is job control format
9) in left terminal, fg %1         #bring the job "rock" to foreground. 1 is job id
     ctrl+c       #permanent stop the process            
     in left terminal, fg %3      #bring the job "scissors" to foreground. 3 is job id
     ctrl+c       #permanent stop the process            
     jobs      #check and confirm
3) in right terminal, ctrl+c        #permanent stop the process           
Chapter 8 - Controlling Services and Daemons:
1) systemctl list-units --type=service          #list all service units
2) systemctl list-units --type=socket --all               #list all socket units
3) systemctl list-unit-files --type=service         #list enabled or disabled states of all service units
4) systemctl status sshd
5) systemctl stop sshd
6) systemctl start sshd
7) systemctl disable sshd
8) systemctl enable sshd
9) systemctl restart sshd         #process id change
10) systemctl reload sshd      #process id not change, not all service support reload
Chapter 9 - Configuring and Securing OpenSSH Service:
1) /etc/ssh/ssh_host_rsa_key.pub           #ssh server public key
     ~/.ssh/known_hosts         #ssh client, will copy the ssh server public key to here
2) rm ~/.ssh/known_hosts         #remove known_hosts in client host
3) scp root@192.168.100.197:/etc/hosts server1.host        
#copy from server (no prompt for password if ssh-copy-id done)
     scp server1.host root@192.168.100.197:/root/           #copy to server
4) #PuTTYgen for windows, generate private key and public key,
#no prompt for password when login to ssh server
Practice (SSH Key-based Authentication):
1) ssh-keygen   
#from ssh client, generate private key ~/.ssh/id_rsa and public key  ~/.ssh/id_rsa.pub
2) ssh-copy-id root@192.168.100.197         #from ssh client, copy public key to ssh server
Lab:
1) vim /etc/ssh/sshd_config
     PermitRootLogin no          #not allow ssh as root
     PasswordAuthentication no              #prevent password login
2) systemctl restart sshd
Chapter 10 - Analyzing and Storing Logs:
1) vim /etc/rsyslog.conf   
#facility.priority (priority is the severity of the message).
#Not recommend to add new log here, should put in /etc/rsyslog.d/
2) man rsyslog.conf            #Looks for SELECTORS, explain about facility.priority
3) vim /etc/logrotate.conf              #default rotate period configuration.
Practice (Finding log entries):
1) vim /etc/rsyslog.d/debug.conf          #file in /etc/rsyslog.d/ must have .conf
     *.debug /var/log/messages-debug
2) systemctl restart rsyslog
3) tail -f /var/log/messages-debug         #check logger message got appear or not
     logger - p user.debug "Debug Message Test"          #update the debug log, logger normally for test purpose
4) vim /etc/logrotate.d/syslog          #log file rotation, log will be delete 4 week old by default after update syslog 
Practice (Finding events with journalctl):     #by default, journal will be gone after reboot or delete in 4 week old
1) journalctl _PID=1            #pid 1 is systemd, find the journal message from systemd only
2) journalctl _UID=0             # uid 1 is root, find the journal message from user root only
3) journalctl -p warning            #-p is priority, find the journal message with priority warning            
4) journalctl --since 9:05:00 --until 9:15:00                  #find the journal message within the time
5) journalctl --since 9:00:00 _SYSTEMD_UNIT="sshd.service"          #find the journal message for sshd service
Practice (Configure a persistent systemd journal):       #make journal permanent, will not be gone after reboot
1)  mkdir /var/log/journal
2) chown root:systemd-journal /var/log/journal/
3) chmod 2755 /var/log/journal
4) killall -USR1 systemd-journald          #or reboot
5) ls -l /var/log/journal      #to verify
Practice (Adjusting system time):     
1) tzselect                     #check the correct time zone phrase, not update the timezone
2) timedatectl set-timezone America/Costa_Rica               #set the timezone
3) timedatectl                #verify the time zone
4) vim /etc/chrony.conf                 #change ntp server
5) systemctl restart chronyd               #restart chronyd service
6) timedatectl set-ntp true               #turn on NTP synchronization
7) timedatectl
8) chronyc sources -v           #verify new ntp server. * is current synced. As long as not longer than 5 mins is ok
Lab:
1) timedatectl list-timezones                    #check the correct time zone phrase
2) timedatectl set-timezone America/Jamaica
2) vim /etc/rsyslog.d/auth-errors.conf          #file in /etc/rsyslog.d/ must have .conf
     authpriv.alert /var/log/auth-errors
3) systemctl restart rsyslog
4) logger -p authpriv.alert "Logging test authpriv.alert"            #use logger to create new log entry
5) tail /var/log/auth-errors
Chapter 11 - Managing networking:
1) 192.168.20.0/27, assign the last ip address in the computer
2) Applications > Accessories > Calculator, change to programming with decimal
3) 11000000.10101000.00010100.00000000              #IP address
     11111111.11111111.11111111.11100000              #coz prefix is 27, subnet mask
     11000000.10101000.00010100.00000000             
#network address, 192.168.20.0, using AND Operator (1+1=1, 1+0=0, 0+1=0, 0+0=0),
#compare ip address with subnet mask.
     00000000.00000000.00000000.00011111              #invert subnet mask to calcualte broadcast address
     11000000.10101000.00010100.00011111              
#broadcast address, 192.168.20.31, using OR Operator (1+1=1, 1+0=1, 0+1=1, 0+0=0),
#compare ip address with invert subnet mask.
                                                                                                         
*fast way to convert broadcast address, convert last 5 network address number to 11111                                                                                              

 * fast way to convert broadcast address, convert network address last 5 number to 11111
1) nmcli connection delete "ens160"          #delete connection
2) nmcli connection add con-name "ens160" ifname ens160 type ethernet     #create new connection
3) nmcli connection modify "ens160" ipv4.addresses "192.168.100.199/23"       #add ip
4) nmcli connection modify "ens160" ipv4.gateway "192.168.100.1"        #add gateway
5) nmcli connection modify "ens160" ipv4.dns "8.8.8.8"        #add dns
6) nmcli connection modify "ens160" connection.autoconnect yes        #configure autoconnect when reboot
7) nmcli connection modify "ens160" ipv4.method static          #configure as static ip
8) nmcli connection up "ens160"       #activate the connection
Practice (Examining network configuration):     
1) ip addr          #replace ifconfig
2) ip -s link show ens160             #show Tx and Rx
3) ip route                #show routing
4) traceroute www.yahoo.com             #show all the hops
5) ss -tan                      
#-t is tcp, -a is all, -n is show numeric instead of name. to replace netstat -tanp, -p is show pid
6) more /etc/services         #show all the ports
Practice (Configuring networking with nmcli):     
1) nmcli connection show             #show all connections
2) nmcli connection show "ens160"          #show connection ens160 with details
3) nmcli device status            #show device status
4) nmcli device show ens160              #show settings for ens160 device
5) nmcli connection add con-name "static-ens160" ifname ens160 type ethernet ip4 172.25.0.11/24 gw4 172.25.0.254   
#create static connection
6) nmcli connection modify "static-ens160" ipv4.dns 172.25.254.254            
#modify new static connection to add dns setting
7) nmcli connection show
8) nmcli connection show --active               #show active connection
9) nmcli connection up "static-ens160"          
#activate new connection (only 1 connection can be active with same nic (ens160)
10) nmcli connection show
11) ip addr show ens160              #check ip address
12) ip route               #check default gateway
13) nmcli connection modify "ens160" connection.autoconnect no         
#disable original connection from autostarting at boot
Practice (Editing network configuration files):     
1) vim /etc/sysconfig/network-scripts/ifcfg-ens160
     IPADDR=192.168.100.199
     PREFIX=23
2) nmcli connection reload        #reload the configuration changes
3) nmcli connection up "ens160"       #restart connection with new settings
Practice (Configuring host names and name resolution):     
1) hostname         #show current host name
2) hostnamectl status       #show host name status
3) hostnamectl set-hostname server2.example.com         #change static (permanent) host name
     cat /etc/hostname            
#show host name configuration file. Can also change the host name here, need reboot.
5) hostname test.example.com             #change temporarily host name
     hostname         #show current host name
     hostnamectl status        #show host name status
6) vim /etc/hosts
Lab:
1) nmcli connection add con-name lab ifname ens160 type ethernet ip4 172.25.0.10/24 gw4 172.25.0.254        
#create new connection
     nmcli connection modify "lab" ipv4.dns 172.25.254.254
2) nmcli connection modify "lab" connection.autoconnect yes               
#configure new connection to be autostarted, other connection should not start auto
     nmcli connection modify "ens160" connection.autoconnect no
3) nmcli connection modify "lab" +ipv4.addresses 10.0.0.1/24          #add new connection 2nd ip address
4) vim /etc/hosts                 #configure 10.0.0.1 can be referenced as private
Chapter 12 - Archiving and copying files between systems:
1) sftp 192.168.100.197               #sftp is interactively copy
2) sftp> mkdir hostbackup             #create hostbackup directory in remote server
     sftp> cd hostbackup/
     sftp> put /etc/hosts                #upload local server file /etc/hosts to remote server hostbackup directory
3) sftp> get /etc/yum.conf       #download remote server /etc/yum.conf to local server current directory
     sftp> exit
1) scp 192.168.100.197:/etc/hosts renamed_hosts.txt          #scp with rename the copied file
Practice (Backing up and restoring files from a tar archive):     
1) tar czf /tmp/etc-var.tar.gz /etc /var              #-c is create, -z is using gzip, -f is file
     #go to /tmp and run ll -h /tmp/etc-var.tar.gz to check the file size
2) mkdir /backuptest
     cd /backuptest
3) [root@test backuptest]# tar xzf /tmp/etc-var.tar.gz         #extract to current directory. -x is extract
Practice (Copying files over the network with scp):     
1) mkdir /root/serverbackup            #create target directory
2) scp -r root@192.168.100.197:/etc/ssh /root/serverbackup           #-r is recursive
Practice (Synchronizing two directories securely with rsync):     
1) mkdir /serverlogs
2) rsync -av root@192.168.100.197:/var/log /serverlogs
3) ssh root@192.168.100.197 'logger "Log files synchronized"'       #create a new log in /var/log/messages
4) rsync -av root@192.168.100.197:/var/log /serverlogs             #copy the changes only
Lab:
1) mkdir /configsync
2) rsync -av root@192.168.100.197:/etc /configsync             #rsync remote server /etc to local server /configsync          
3) tar czf /root/configfile-backup-server2.tar.gz /configsync          #create archive from /configsync
4) scp /root/configfile-backup-server2.tar.gz root@192.168.100.197:/root          
#copy /root/configfile-backup-server2.tar.gz to remote server /root
5) mkdir /tmp/savedconfig
     cd /tmp/savedconfig
     tar xzf /root/configfile-backup-server2.tar.gz           #extract to current directory
Chapter 13 - Installing and updating software packages:
1) rpm -qa | grep gnuplot         #check the gnuplot package installed
2) rpm -e gnuplot       #-e is erase, remove the gnuplot package, its dependency will not be removed together
3) yum repolist         #check the repository available
4) yum erase gnuplot       #will remove dependencies also
5) yum search "plot"        #search package, cannot use *    
6) yum list gnu*                #search package, can use *
Practice (Installing and updating software with yum):     
1) yum search plot               #search for plotting package
2) yum info gnuplot              #find more info about gnuplot package
3) yum install gnuplot            #install gnuplot package
4) yum remove gnuplot          #remove gnuplot package
5) yum grouplist               #list all available component group
6) yum groupinfo "Compatibility Libraries"         #find more info about compatibility libraries component group
7) yum groupinstall "Compatibility Libraries"          #group install
8) yum history
9) yum history info 3          #confirm the last install is group installation
10) yum history undo 3              #remove the last set of packages installed.
Practice (Enabling software repositories):     
1) yum-config-manager --add-repo="http://content.example.com/rhel7.0/x86_64/rht"      #add rht repo
2) vim /etc/yum.repos.d/errata.repo        #add errata repo
3) yum-config-manager --disable content.example.com_rhel7.0_x86_64_rht        #disable rht repo
4) yum update -y                #will update kernel also
5) uname -r                   #-r is kernel release, show the current kernel using
Practice (Working with RPM package files):     
1) wget http://dl.fedoraproject.org/pub/epel/7/x86_64/e/epel-release-7-5.noarch.rpm    #download rpm
2) yum localinstall epel-release-7-5.noarch.rpm         
#install rpm with yum. using rpm -ivh epel-release-7-5.noarch.rpm also can, yum localinstall can have yum log.
Lab:
1) vim /etc/yum.repos.d/errata.repo
2) yum update kernel
     yum install rht-system
3) yum remove wvdial

Chapter 14 - Accessing linux file systems:
1) lsof /mnt/mydata           #list open file when cannot umount
2) kill -9 24348         #kill the process then umount
Practice (Making links between files):           
#for script/application to read (no recommend to write) the same file, no need to modify all file if got changes.
1) ln /usr/share/doc/qemu-kvm/qmp-commands.txt /root/qmp-manual.txt          
#create hard link (no way to tell which file is orignal after hardlink created), cannot be different file system
    
2) ln -s /tmp /root/tempdir                #create soft link (shortcut), can be different file system
Practice (Locating files on the system):           
1) updatedb              #manually update datebase for locate command. By default, will auto update every day.
2) locate logrotate.conf          #locate is search based on locate datebase, less powerful    
3) locate -i networkmanager.conf       #-i is ignore case.
4) find /var/lib -user chrony         #find files owned by user chrony
5) find /var -user root -group mail       #find files owned by user root and group mail
6) find /usr/bin -size +50k                   #find files with file size greater than 50kb
7) find /home/stanley -mmin +120         #find files that have changed more than 120 minutes
8) find /tmp -mmin -240                    #find files that have changed less than 240 minutes
Lab:
1) du /var/log > /tmp/results.txt               #generate disk usage report
2) blkid
     mkdir /mnt/myfreespace
     mount UUID="xxxx" /mnt/myfreespace
3) ln -s /mnt/myfreespace /root/myfreespace
2) find / -type l -name '*freespace*'       #-l is soft link (symbolic link)
Chapter 15 - Comprehensive review:
1) head -n 12 /usr/bin/clean-binary-files >/root/headtail.txt             
#show the 1st 12 lines and send output to headtail.txt
     tail -n 9 /usr/bin/clean-binary-files >>/root/headtail.txt            
#show last 9 lines and add output to headtail.txt
2) touch ~stanley/system_changes-machine{1..10}-month_{jan,feb,mar}.txt          
#create 30 files with file name with system_changes-machineY-month_Z.txt.
#Y is machine number, Z is months jan, feb, mar.
     mkdir -p /home/stanley/syschanges/{jan,feb,mar}      
#create directory with subdirectories jan, feb and mar
3) mv ~stanley/system_changes-machine*jan.txt /home/stanley/syschanges/jan/           
#move files by month into the corresponding subdirectory
     mv ~stanley/system_changes-machine*feb.txt /home/stanley/syschanges/feb/
     mv ~stanley/system_changes-machine*mar.txt /home/stanley/syschanges/mar/
     rm -f /home/stanley/syschanges/*/system_changes-machine{9,10}*.txt         
#remove files related to machine 9 and 10
4) vim /etc/login.defs            #new created users, passwords are changed at least every 60 days
     a) groupadd -g 30000 instructors         #create new group named instructors with GID 30000
     b) tail -5 /etc/group
    a) useradd -G instructors gorwell
    b) useradd -G instructors rbradbury
    c) useradd -G instructors dadams
    d) tail -5 /etc/group
     a) date -d "+60 days"         #determine the date 60 days in the future
     b) chage -E 2016-05-17 gorwell               #set user to expire on that date
          chage -E 2016-05-17 rbradbury
          chage -E 2016-05-17 dadams
    c) chage -M 10 gorwell        #set gorwell account to require new password every 10 days
    d) chage -d 0 gorwell        #set users to change password on first login
         chage -d 0 rbradbury
         chage -d 0 dadams
5) mkdir /home/instructors
     chown :instructors /home/instructors                  #change group permission to instructors
     chmod 2774 /home/instructors         #change permission