Linux needed for LFCS Administrator

Hello KodeKloud community,

Below is the LINUX needed for you to excel LFCS

find is used to search the files based on its size, permission, type from a folder location.
Below are some sample examples

find /home/bob -size 213k -perm 402
find /usr/share -name dogs.txt
sudo find /var/ -type d -name pets
sudo find /var -type f -perm 0777 -print
sudo find /usr -type f -mmin -120
sudo find /usr -type f -size +5M -size -10M > /home/bob/size.txt
find ! -newermt “01/01/2020” -type f -exec rm {} ;
find -maxdepth 1 -size -3k -type f -exec mv {} ./small ; # move
find -maxdepth 1 -perm 777 -type f # find

Stream Editor(sed)
s at beginning stands for substitution
The g character at the end of the s subcommand tells the sed command to make as many substitutions as possible on each line.
-i option will edit the input file in-place
“in-place” would really mean that: literally editing the very same file (the same inode).

sed -i ‘s/enabled/disabled/g’ /home/bob/values.conf
sed -i ‘s/disabled/enabled/gi’ /home/bob/values.conf
sed -i ‘500,2000s/enabled/disabled/g’ values.conf substite from 500 to 2000th line

Make sure the cursor is on the very first line; then without entering into the insert mode, enter number 1000 and press dd immediately after that. Finally save the file.

diff file1 file2 (to get the difference in file1 and file2)

egrep ‘[0-9]{5}’ textfile (expression grep)
egrep -c ‘^2’ /home/bob/textfile > /home/bob/count → to get count
egrep -w ‘man’ /home/bob/testfile (exact match)

tail -500 /home/bob/textfile (last 500 lines)

sort -du /home/bob/values.conf > /home/bob/values.sort

openssl req -newkey rsa:4096 -keyout priv.key -out cert.csr (To generate PRIVATE KEY and CERTIFICATE)
openssl req -x509 -noenc -days 365 -keyout priv.key -out kodekloud.crt

sudo shutdown +120
sudo shutdown -c (cancel scheduled shutdown)

sudo systemctl set-default graphical.target (set to graphical by default)
sudo systemctl status sshd.service (see status of ssh service)
sudo systemctl is-enabled sshd.service (see if ssh service is enabled)
sudo systemctl mask apache2.service
sudo systemctl unmask apache2.service

Below are some commands to see NICE values
ps lax for nice values
ps aux
sudo renice NICE_VALUE

sudo lsof -p PID > /home/bob/files.txt

sudo journalctl --unit=ssh.service -n 20 --no-pager (To search logs)

pgrep -a rpcbind (process grep)

sudo grep -r --text ‘reboot’ /var/log/ > reboot.log

cd /home/bob
sudo journalctl -p err > .priority/priority.log
sudo journalctl -p info -g ‘^c’ (-p for priority and -g for regular expression)

strace -p PID
sudo kill PID
ps u PID (u to get process usage)
USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND
root 1 0.0 0.0

sleep 3000 & (make sure its runs in background)

Writing a CronJob spec
Schedule syntax
The .spec.schedule field is required. The value of that field follows the Cron syntax:

┌───────────── minute (0 - 59)

│ ┌───────────── hour (0 - 23)

│ │ ┌───────────── day of the month (1 - 31)

│ │ │ ┌───────────── month (1 - 12)

│ │ │ │ ┌───────────── day of the week (0 - 6) (Sunday to Saturday)

│ │ │ │ │ OR sun, mon, tue, wed, thu, fri, sat

│ │ │ │ │

│ │ │ │ │

* * * * *

mhdmd day of the week

edit or substitute as user
sudo su user
cd
pwd

vim /etc/crontab (all cronjobs are defined in this file)

sudo crontab -e
sudo cronatb -l → to see list of crontabs

add given command like below
0 0 1 * * /usr/bin/touch monthly
0 6,23 * * 0 sudo systemctl restart nginx ( at 6 am and 11 pm)

atq → What is the command to see the jobs that are scheduled to run in at utility? atq

atrm jobid (Remove the job using jobid)

sudo vim /etc/anacrontab

sudo apt search “apache http server”
sudo apt update
sudo apt install apache2

sudo apt-get remove --auto-remove -y ziptool (unintsall package ziptool)

dpkg(Debian Package) is a tool to install, build, remove and manage Debian packages.
dpkg --search /bin/ls (search the package)
dpkg --listfiles coreutils | grep ^/bin

Navigate to the /home/bob/tmux directory and follow the below steps to install an application from the binary.
cd tmux

Run autogen.sh to generate the necessary build files
sudo ./autogen.sh

Configure the build
sudo ./configure

./configure --prefix=/some/path

Compile the source code
sudo make

Install the application
sudo make install

Now access it by running command
tmux

uptime
free --mega
lscpu → cpu per socket
sudo xfs_repair -n /dev/vdb > /home/bob/fscheck 2>&1

Note: First navigate to the directory that has dockerfile using cd command
docker build -t myapp:v1 . (. is mandatory)
docker run -d --name c1 -p 1234:80 --memory 30m myapp:v1

docker pull image-name

docker run -d -p 1234:80 --name website Docker Hub Container Image Library | App Containerization

docker images
docker ps -a
docker stop $CONTAINER_ID
docker rm $CONTAINER_ID
docker rmi Image_ID
docker run -d -p 9080:80 --restart always --name webinstance1 httpd (–restart on-failure:3)
sudo docker run -d --name frontend_v3 --memory 30m -p 1234:80 nginx:alpine
sudo docker inspect docker_name

virsh autostart VM1
virsh list --all
virsh start VM1
virsh destroy VM1
virsh undefine VM1 (to remove VM1)
virsh define /opt/testmachine2.xml
virsh setmem VM2 80M --config

sudo chage -W 2 jane → gets warning 2 days boefore
sudo chage --lastday 0 jane → expire password immediately

sudo usermod -g rugby sam
sdo usermod -e 2030-03-01(yyyy-mm-dd) jane
sudo usermod -e “” jane → this never expires

sudo useradd -G soccer sam --uid 5322
sudo useradd --system apachedev → to create system account apachedev

Create a user with a Non-Interactive Shell
adduser ravi -s /sbin/nologin

sudo passwd username → to assign password tp the user

sudo groupadd -g 9875 cricket
sudo groupmod -n soccer(new_name) cricket(old_name)

sudo groupdel appdevs

How do I check which groups a user belongs to in Linux
groups username

vi ~/.bashrc
export MYVAR=TRUE
source ~/.bashrc

sudo vi /etc/environment
source /etc/environment

sudo vi /etc/profile.d/welcome.sh

sudo vi /etc/security/limits.conf
trinity -nproc 30 (Configure process limits)
stephen hard fsize 4096
@salesteam soft nproc 20 (Salesteam group limit)

sudo visudo /etc/sudoers
%salesteam ALL=(ALL) ALL (group salesteam)
trinity ALL=(sam) ALL Trinity can command as user sam

ulimit -a → to see all current limits

The ss (socket statistics) tool is a CLI command used to show network statistics
sudo ss -tunlp (to see if processes are listening)

ip a, addr, address (all 3 are same)
ip route show (To get the default gateway)

sudo vi /etc/hosts (For static hostname resolution)

sudo ip a add 192.168.9.3/24 dev eth1

sudo chmod 600 /etc/netplan/99-custom.yaml
sudo netplan apply

sudo vim /etc/systemd/resolved.conf
#DNS → DNS=8.8.8.8

By default, Uncomplicated Firewall (ufw) is disabled. It means all the tarrfic is blocked. So first we must enable it and then add the rules.

sudo ufw enable
sudo ufw allow 22
sudo ufw allow 53/tcp (thru TCP port)
sudo ufw deny 443/tcp
sudo ufw delete deny 443/tcp (delete the firewall rule)
sudo ufw status numbered
sudo ufw allow from 207.45.232.181
sudo ufw delete 8
sudo ufw insert 1 deny from 10.0.0.19

sudo vi /etc/ssh/sshd_config
sudo systemctl restart sshd

lsblk → to display disk or partitions

sudo mkswap /vd1 → to convert partition as swap space

swapon --show
swapoff /dev/vdb2

sudo mkfs.xfs -L “DataDisk” /dev/vdb
sudo mkfs.ext4 -N 2048 /dev/vdc (-N for inodes)
sudo mkfs -t ext4 /dev/xa1

mount /dev/vdb /mnt
umount /mnt
findmnt /dev/vda1
mount -o ro,noexec,nosuid /dev/vdb1 /mnt (-o for mount options)
mount -o remount,rw /dev/vdb1 /mnt

pvcreate /dev/vdb /dev/vdc (created 2 PV’s,name sprted by space)
pvs → to see all pV’s
pvremove
vgcreate volume1 /dev/vdb → /dev/vdb is PV
vgextend volume1 /dev/vdc
vgreduce volume1 /dev/vdc → to remove PV /dev/vdc from VG volume1
vgs
lvcreate --size 0.5G --name smalldata volume1(volume group name)
lvresize --size 752M volume1/smalldata
sudo lvremove volume1/smalldata (VG/LV)

sudo lvresize --extents 100%VG volume1/smalldata1

sudo lvresize --extents 75%VG volume1/website_files (VG is 4GB) (This will resize it t0 3Gb)

iptables is a command-line utility for configuring the built-in Linux kernel firewall. It enables administrators to define chained rules that control incoming and outgoing network traffic.

Chains
Chains are rule lists within tables. The lists control how to handle packets at different processing stages. There are different chains, each with a specific purpose:

INPUT. Handles incoming packets whose destination is a local application or service. The chain is in the filter and mangle tables.
OUTPUT. Manages outgoing packets generated on a local application or service. All tables contain this chain.
FORWARD. Works with packets that pass through the system from one network interface to another. The chain is in the filter, mangle, and security tables.
PREROUTING. Alters packets before they are routed. The alteration happens before a routing decision. The NAT, mangle, and raw tables contain this chain.
POSTROUTING. Alters packets after they are routed. The alteration happens after a routing decision. The NAT and mangle tables contain this chain.

Targets
A target is what happens after a packet matches a rule criteria. Common targets include:

ACCEPT. Allows the packet to pass through the firewall.
DROP. Discards the packet without informing the sender.
REJECT. Discards the packet and returns an error response to the sender.
LOG. Records packet information into a log file.
SNAT. Stands for Source Network Address Translation. Alters the packet’s source address.
DNAT. Stands for Destination Network Address Translation. Changes the packet’s destination address.
MASQUERADE. Alters a packet’s source address for dynamically assigned IPs.

iptables -A INPUT -i eth0 -p tcp --dport 5000 -j DROP
iptables -A PREROUTING -i eth0 -t nat -p tcp --dport 6000 -j REDIRECT --to-port 6001
iptables -A INPUT -i eth0 -p tcp --dport 6002 -s 192.168.10.80 -j ACCEPT
iptables -A OUTPUT -d 192.168.10.70 -p tcp -j DROP

Port 5000 should be closed
Redirect all traffic on port 6000 to local port 6001
Port 6002 should only be accessible from IP 192.168.10.80 (server data-001)
Block all outgoing traffic to IP 192.168.10.70 (server app-srv1)

-i interface
-p protocol
–dport destination port
-t type

Option Description
-A
–append Append a rule to a chain.
-C
–check Look for a rule that matches a chain.
-D
–delete Remove a rule from a chain.
-F
–flush Remove all rules.
-I
–insert Add a rule to a chain at the provided position.
-L
–list Show all rules in a chain.
-N
–new-chain Create a new chain.
-V
–verbose Show a more detailed output.
-X
–delete-chain Delete a chain.

Saving entries
You’ll probably want your configured iptables to survive reboots, so be sure to issue the following command to save your valuable entries, otherwise, you’ll have to import your rules after every reboot or script the import.

$ sudo iptables-save > /etc/sysconfig/iptables

Enable or disable IP forwarding

sysctl net.ipv4.ip_forward → to see the current value

sudo sysctl -w net.ipv4.ip_forward=0 (=0 shoudl be without spaces) → to chnage the value

echo 0 > /proc/sys/net/ipv4/ip_forward

OR

echo 1 > /proc/sys/net/ipv4/ip_forward

To enable SSH password authentication, you must SSH in as root to edit this file:

/etc/ssh/sshd_config
Then, change the line

PasswordAuthentication no
to

PasswordAuthentication yes
After making that change, restart the SSH service by running the following command as root:

sudo service ssh restart

Enable Logging In as root

sudo -i
If you instead want to be able to directly SSH in as root, again edit this file:

/etc/ssh/sshd_config
And change the line

PermitRootLogin no
to

PermitRootLogin yes
After making that change, restart the SSH service by running the following command as root:

sudo service ssh restart
If you enable this setting, don’t forget to set a strong password for root by running the command.

sudo passwd root

git push origin master or git push origin main

ps faux

timedatectl
timedatectl list-timezones
timedatectl set-timezone America/Los_Angeles

sudo apt install systemd-timesyncd

sudo timedatectl set-ntp true

systemctl status systemd-timesyncd.service

sudo systemctl restart systemd-timesyncd

sudo service systemd-timesyncd restart

sudo service systemd-timesyncd status

sudo apt install sysstat

iostat
pidstat -d

sudo dmsetup info /dev/vda1 dm-0

kill PID

kill -9 PID force kill
umount

NFS server
sudo apt install nfs-kernel-server
sudo vim /etc/exports

add the directry that we nned to share with and the hostnames that we ed to share with

/etc 172.1.2.3(ro) in exports file

sudo exportfs -r (re-export/refresh)

NFS client

sudo apt install nfs-common

sudo mount 12.0.0.1:/etc /mnt
sudo mount server1.com:/etc /mnt

umount /mnt

sudo vim /etc/fstab

add below
127.0.0.1:/mnt nfs defaults 0 0

Quality emulator
qemu-img info ubuntu-24.04-minimal-cloudimg-amd64.img

qemu-img resize ubuntu-24.04-minimal-cloudimg-amd64.img 5G

virt-install --osinfo Ununtu_version --name VM1 --memory 1024(only on Mb) --import --disk iamge path location --graphics none --cloud-init root-passowrd-generate=on

bob@ubuntu-host ~ :heavy_multiplication_x: sudo usermod -G jane4Group jane3

bob@ubuntu-host ~ ➜ groups jane3
jane3 : jane3 jane4Group

bob@ubuntu-host ~ ➜ sudo usermod -g jane3Group jane3

bob@ubuntu-host ~ ➜ groups jane3
jane3 : jane3Group jane4Group

To change a user’s primary group in Linux without removing them from their old group, use the usermod command with the -g option, specifying the new group name; this will only modify the primary group, leaving any other group memberships intact.

Set up a port redirection rule that does the following: it redirects any IPv4 packet from the 10.5.5.0/24 CIDR range incoming on port 81 to another machine with the IP address 192.168.5.2 on port 80. To simplify this task, you are not required to specify input or output network interfaces.

sudo iptables -t nat -A PREROUTING -p tcp -s 10.5.5.0/24 --dport 81 -j DNAT --to-destination 192.168.5.2:80

Don’t forget to add the proper masquerading rule so that packets redirected from 10.5.5.0/24 have a way of getting back to that sender, by our machine sitting in the middle and acting as an ad-hoc router between those two networks.

sudo iptables -t nat -A POSTROUTING -s 10.5.5.0/24 -j MASQUERADE

Make sure that after you add the rules you make them persistent (so that when the machine is rebooted these changes are not lost).

sudo apt install iptables-persistent

Set up a port redirection rule. All connections coming from the 10.9.9.0/24 IP range, on port 8080 should be redirected to 10.100.0.8 on port 80.
sudo iptables -t nat -A PREROUTING -s 10.9.9.0/24 -p tcp --dport 8080 -j DNAT --to-destination 10.100.0.8:80

Make sure to also set up masquerading so that traffic can also be returned to the sender (10.9.9.0/24).
sudo iptables -t nat -A POSTROUTING -s 10.9.9.0/24 -j MASQUERADE

To identify the process with high TPS and the partition it is using, follow the steps below:

Run the sudo dstat --top-io --top-bio command to get the process name with I/O activity.
Run the pgrep python3 command to get the PID of the process.
Run sudo lsof -p to list the open files by the process.
Run sudo lsof -p | awk ‘{print $9}’ | while read file; do df $file; done to get the device details.
Find the actual partition used by running the pvs command and store the actual device name in /opt/devname.txt.

Run the command below to get the PID of the process with high kB_read/s:

sudo pidstat -d 1

sudo usermod -g developers -G jane,sudo jane

-g primary
-G Secondary

Find the filesystem that is almost full:

df -h

Let me know if you need any changes. Any feedback is most welcome.

I do not understand your question, nor the relevance of everything you have pasted above.

LFCS is an examination on the candidate’s ability to administer a Linux server.

Hello Alister, I have used KodeKloud for LFCS preparation. While I was preparing, I came up with this cheat sheet. I thought it will help other LFCS aspirants, so I have shared it in the community.

You might want to format it a bit better so it is legible, like this. Also means people can copy it and paste to a terminal. Without the code formatting, it will copy wrong sorts of quote marks and cause errors.


find is used to search the files based on its size, permission, type from a folder location.
Below are some sample examples

find /home/bob -size 213k -perm 402
find /usr/share -name dogs.txt
sudo find /var/ -type d -name pets
sudo find /var -type f -perm 0777 -print
sudo find /usr -type f -mmin -120
sudo find /usr -type f -size +5M -size -10M > /home/bob/size.txt
find ! -newermt “01/01/2020” -type f -exec rm {} ;
find -maxdepth 1 -size -3k -type f -exec mv {} ./small ; # move
find -maxdepth 1 -perm 777 -type f # find

Stream Editor(sed)
s at beginning stands for substitution
The g character at the end of the s subcommand tells the sed command to make as many substitutions as possible on each line.
-i option will edit the input file in-place
“in-place” would really mean that: literally editing the very same file (the same inode).

sed -i 's/enabled/disabled/g' /home/bob/values.conf
sed -i 's/disabled/enabled/gi' /home/bob/values.conf
sed -i '500,2000s/enabled/disabled/g' values.conf substitute from 500 to 2000th line

Thanks, Alister for the feedback. Sure, I will do it.