Top 50 Linux Commands You Must Know as a Regular User

  • ls – The most frequently used command in Linux to list directories
  • pwd – Print working directory command in Linux
  • cd – Linux command to navigate through directories
  • mkdir – Command used to create directories in Linux
  • mv – Move or rename files in Linux
  • cp – Similar usage as mv but for copying files in Linux
  • rm – Delete files or directories
  • touch – Create blank/empty files
  • ln – Create symbolic links (shortcuts) to other files
  • clear – Clear the terminal display
  • cat – Display file contents on the terminal
  • echo – Print any text that follows the command
  • less – Linux command to display paged outputs in the terminal
  • man – Access manual pages for all Linux commands
  • uname – Linux command to get basic information about the OS
  • whoami – Get the active username
  • tar – Command to extract and compress files in linux
  • grep – Search for a string within an output
  • head – Return the specified number of lines from the top
  • tail – Return the specified number of lines from the bottom
  • diff – Find the difference between two files
  • cmp – Allows you to check if two files are identical
  • comm – Combines the functionality of diff and cmp
  • sort – Linux command to sort the content of a file while outputting
  • export – Export environment variables in Linux
  • zip – Zip files in Linux
  • unzip – Unzip files in Linux
  • ssh – Secure Shell command in Linux
  • service – Linux command to start and stop services
  • ps – Display active processes
  • kill and killall – Kill active processes by process ID or name
  • df – Display disk filesystem information
  • mount – Mount file systems in Linux
  • chmod – Command to change file permissions
  • chown – Command for granting ownership of files or folders
  • ifconfig – Display network interfaces and IP addresses
  • traceroute – Trace all the network hops to reach the destination
  • wget – Direct download files from the internet
  • ufw – Firewall command
  • iptables – Base firewall for all other firewall utilities to interface with
  • apt, pacman, yum, rpm – Package managers depending on the distribution
  • sudo – Command to escalate privileges in Linux
  • cal – View a command-line calendar
  • alias – Create custom shortcuts for your regularly used commands
  • dd – Majorly used for creating bootable USB sticks
  • whereis – Locate the binary, source, and manual pages for a command
  • whatis – Find what a command is used for
  • top – View active processes live with their system usage
  • useradd and usermod – Add a new user or change existing user data
  • passwd – Create or update passwords for existing user

File and Directory Commands

CommandDescriptionExample
lsList directory contents.ls
cdChange directory.cd /path/to/directory
pwdShow current directory.pwd
mkdirCreate a new directory.mkdir new_directory
rmdirRemove an empty directory.rmdir empty_directory
rmDelete files or directories.rm file.txt
touchCreate an empty file.touch new_file.txt
cpCopy files or directories.cp file.txt /path/to/destination
mvMove or rename files.mv file.txt /path/to/new_location
catDisplay file contents.cat file.txt
nano / vimEdit files in terminal.nano file.txt
findSearch for files in a directory hierarchy.find . -name "file.txt"
grepSearch text using patterns.grep "pattern" file.txt
tarArchive and compress files.tar -cvf archive.tar file1.txt file2.txt
dfShow disk usage of file systems.df
duShow directory/file size.du -sh /path/to/directory
chmodChange file permissions.chmod 755 file.txt
chownChange file owner.chown user:group file.txt
mountMount a filesystem.mount /dev/sdb1 /mnt
umountUnmount a filesystem.umount /mnt
				
					1. ls – List directory contents
................................

ls → Lists files in the current directory

ls -l → Long listing format (includes permissions, owner, size, date)

ls -a → Shows hidden files (those starting with .)



2. cd – Change directory
.........................

cd /path/to/directory → Go to specific directory

cd .. → Move up one directory

cd ~ or just cd → Go to home directory



3. pwd – Print working directory
.................................

Shows the full path of your current directory
Example: /home/username/Documents


4. mkdir – Make new directory
.............................

mkdir newfolder → Creates a folder named newfolder

mkdir -p folder1/folder2 → Creates nested folders


5. rmdir – Remove an empty directory
....................................

rmdir myfolder → Removes the folder only if it's empty


6. rm – Remove files or directories
....................................

rm file.txt → Deletes a file

rm -r folder/ → Deletes a folder and all contents recursively

rm -rf folder/ → Same as above, but forces deletion without asking (⚠️ dangerous!)



7. cp – Copy files and directories
..................................

cp file1.txt file2.txt → Copies file1.txt to file2.txt

cp -r dir1/ dir2/ → Copies an entire directory



8. mv – Move or rename files and directories
............................................

mv file.txt /new/location/ → Moves file

mv oldname.txt newname.txt → Renames file



9. touch – Create an empty file
................................

touch newfile.txt → Creates a blank file
(Also updates timestamp if the file already exists)



10. find – Search for files
...........................

find / -name filename.txt → Searches for a file starting from root

find . -name "*.txt" → Finds all .txt files in current directory and subdirectories



11. cat – View contents of a file
.................................

cat file.txt → Displays file contents

Combine with > to create files: cat > newfile.txt



12. less or more – View long files one page at a time
.....................................................

less file.txt → Scroll up/down with arrow keys

more file.txt → Similar, but less flexible than less



13. stat – Show file or directory status
........................................

stat file.txt → Gives detailed info (size, permissions, timestamps)
				
			

Networking Commands

CommandDescriptionSample Usage
pingTest connectivity to a host.ping google.com
ifconfig / ip aDisplay network interfaces.ifconfig or ip a
netstat / ssShow network connections.netstat -tuln or ss -tuln
wgetDownload files via HTTP/FTP.wget http://example.com/file.zip
curlTransfer data using URL syntax.curl -O http://example.com/file.zip
nc (Netcat)Network debugging and data transfer.nc -zv 192.168.1.1 80
tcpdumpCapture and analyze network packets.tcpdump -i eth0
iptablesConfigure firewall rules.iptables -A INPUT -p tcp --dport 22 -j ACCEPT
tracerouteTrace the path packets take to a network host.traceroute example.com
nslookupQuery DNS to obtain domain name or IP address mapping.nslookup example.com
sshSecurely connect to a remote host.ssh user@example.co

 

Basic Networking Commands

CommandDescriptionExample
ip a or ip addrShow IP addresses and interfacesip a
ip linkShow or manage network interfacesip link show
ip routeDisplay routing tableip route

Connectivity Testing

CommandDescriptionExample
pingTest if host is reachableping google.com
tracerouteShow route packets take to a hosttraceroute google.com
mtrReal-time traceroute (advanced)mtr google.com
telnetTest open ports on remote systemtelnet example.com 80
nc (netcat)Test connections or transfer datanc -zv google.com 443

DNS Tools

CommandDescriptionExample
nslookupQuery DNS for recordsnslookup google.com
digAdvanced DNS queryingdig google.com
hostSimple DNS lookuphost google.com

Monitoring and Interface Info

CommandDescriptionExample
ifconfigShow interface info (deprecated)ifconfig
ip -s linkShow stats for interfacesip -s link
ethtoolView/set Ethernet device settingsethtool eth0
iwconfigConfigure wireless interfacesiwconfig wlan0
nmcliNetworkManager CLI (for desktops)nmcli device status

Port and Socket Monitoring

CommandDescriptionExample
netstatShow network connections (old)netstat -tuln
ssShow open sockets (modern)ss -tuln
lsof -iList open files using networklsof -i
nmapPort scanner / network mappernmap 192.168.1.1

Downloading and Transfers

CommandDescriptionExample
curlTransfer data from URLscurl https://example.com
wgetDownload files from webwget https://file.com/file.zip
scpSecure copy over SSHscp file.txt user@host:/path
rsyncSync files/directoriesrsync -avz /src user@host:/dest

Troubleshoot Network Issue

  1. Check your IP: ip a

  2. Test DNS: dig google.com

  3. Ping a site: ping google.com

  4. Check open ports: ss -tuln

  5. Traceroute to a server: traceroute google.com

 

Process and System Monitoring Commands

CommandDescriptionExample Command
psShow running processes.ps aux
topDynamic process viewer.top
htopEnhanced version of top.htop
killSend a signal to a process.kill <PID>
killallKill processes by name.killall <process_name>
uptimeSystem uptime and load.uptime
whoamiCurrent logged-in user.whoami
envDisplay environment variables.env
straceTrace system calls of a process.strace -p <PID>
systemctlManage systemd services.systemctl status <service_name>
journalctlView system logs.journalctl -xe
freeDisplay memory usage.free -h
vmstatReport virtual memory statistics.vmstat 1
iostatReport CPU and I/O statistics.iostat
lsofList open files by processes.lsof
dmesgPrint kernel ring buffer messages.dmesg

 

User and Permission Management Command

CommandDescriptionExample Command
passwdChange user password.passwd <username>
adduser / useraddAdd a new user.adduser <username> or useradd <username>
deluser / userdelDelete a user.deluser <username> or userdel <username>
usermodModify user account.usermod -aG <group> <username>
groupsShow group memberships.groups <username>
sudoExecute commands as root.sudo <command>
chageChange user password expiry information.chage -l <username>
idDisplay user identity information.id <username>
newgrpLog in to a new group.newgrp <group>

👤 1. User Management Commands

CommandDescriptionExample
adduserAdd a new user (interactive, preferred)sudo adduser john
useraddAdd user (non-interactive, more control)sudo useradd -m john
passwdSet/change a user’s passwordsudo passwd john
usermodModify a user accountsudo usermod -aG sudo john
deluserDelete a usersudo deluser john
userdelDelete a user (and optionally their home dir)sudo userdel -r john
idShow user ID and group infoid john
whoamiShow the current logged-in usernamewhoami

👥 2. Group Management Commands

CommandDescriptionExample
addgroupAdd a new groupsudo addgroup developers
groupaddAdd group (alternative command)sudo groupadd staff
groupdelDelete a groupsudo groupdel staff
usermod -aGAdd a user to a groupsudo usermod -aG developers john
groupsShow groups of a usergroups john
gpasswdAdminister group membershipsudo gpasswd -a john developers

🗂️ 3. File Ownership and Permissions

CommandDescriptionExample
chownChange ownership of a file/directorysudo chown john:developers file.txt
chmodChange file/directory permissionschmod 755 script.sh
chgrpChange group ownershipchgrp developers file.txt
ls -lView file permissions and ownershipls -l /home/john/
umaskShow or set default permission maskumask

 4. Understanding chmod (Permissions)

Permission format: rwxr-xr--

SymbolMeaningBinary
rRead4
wWrite2
xExecute1

Example:

  • chmod 755 file.sh
    → Owner: read/write/execute
    → Group: read/execute
    → Others: read/execute

NumericMeaning
7read + write + execute
6read + write
5read + execute
4read only
0no permissions

 5. Useful Combinations

TaskCommand
Add user and assign to a groupsudo adduser john developers
Add user to sudoerssudo usermod -aG sudo john
Change file to be executablechmod +x script.sh
Give read/write to user onlychmod 600 file.txt
Change owner to rootsudo chown root:root file.txt

 6. Audit User Activity

CommandDescriptionExample
lastShow recent loginslast
whoShow who is logged inwho
wShow logged in users + what they’re doingw
historyShow command historyhistory
sudoExecute as another user (usually root)sudo apt update

 Summary Cheat Table

AreaKey Commands
Useradduser, useradd, passwd, userdel
Groupaddgroup, usermod -aG, groups, groupdel
Permissionschmod, chown, chgrp, ls -l
Auditlast, who, w, history
				
					How to change pemisson ownership?
..................................
sudo chown -R username:group directory
centos - chown :groupnamr <filename>
         chown	<username> <filename>



How to show  users?
...................
getent passwd


How to show  group?
...................
getent group


How to check user which group join?
...................................
groups <username>


How to show all gropus?
.......................
compgen -g


How to show all users?
......................
compgen -u


How to List All Groups in Linux?
................................
cat /etc/group


How to List All Members of a Group on Ubuntu ?
.............................................
getent group <group_name>


How to add User in a Group on Ubuntu?
......................................
sudo usermod -aG <group_name> <user_name>


How to remove User from a Group on Ubuntu ?
...........................................
sudo gpasswd -d <user_name> <group_name>


How to change password users self ?
...................................
passwd


How to normal users permisson to root privilage?
................................................
usermod -aG sudo <username>
sudo some-command
sudo visudo
sudo passwd -e bob
sudo passwd --expire sumita


How to Account Lokking Unlokking?
.................................
sudo passwd -l bob
sudo passwd -u bob
skill -u USERNAME


How to delete user forcefully kill?
....................................
sudo killall -u username
sudo userdel -f username
How to del group?
delgroup -f <group name>


				
			

Text Processing Commands

CommandDescriptionExample Command
awkPattern scanning and processing.awk '{print $1}' file.txt
sedStream editor for filtering/modifying text.sed 's/old/new/g' file.txt
cutRemove sections from lines of text.cut -d':' -f1 /etc/passwd
sortSort lines of text.sort file.txt
grepSearch for patterns in text.grep 'pattern' file.txt
wcCount words, lines, and characters.wc -l file.txt
pasteMerge lines of files.paste file1.txt file2.txt
joinJoin lines of two files on a common field.join file1.txt file2.txt
headOutput the first part of files.head -n 10 file.txt
tailOutput the last part of files.tail -n 10 file.txt
CommandDescriptionExample Command
aliasCreate shortcuts for commands.alias ll='ls -la'
unaliasRemove an alias.unalias ll
historyShow previously entered commands.history
clearClear the terminal screen.clear
rebootReboot the system.reboot
shutdownPower off the system.shutdown now
dateDisplay or set the system date and time.date
echoDisplay a line of text.echo "Hello, World!"
sleepDelay for a specified amount of time.sleep 5
timeMeasure the duration of command execution.time ls
watchExecute a program periodically, showing output fullscreen.watch -n 5 df -h

 

Linux LVM Commnds

What is LVM?

LVM (Logical Volume Manager) allows you to manage disk space flexibly by abstracting physical storage into logical volumes. You can resize, combine, and manage volumes more easily than with traditional partitions.

1. Install LVM (if not already installed)

 
sudo apt update sudo apt install lvm2

2. Basic LVM Workflow Overview

StepTaskCommand
1Create physical volume (PV)pvcreate /dev/sdX
2Create volume group (VG)vgcreate my_vg /dev/sdX
3Create logical volume (LV)lvcreate -L 10G -n my_lv my_vg
4Format LV with a file systemmkfs.ext4 /dev/my_vg/my_lv
5Mount the LVmount /dev/my_vg/my_lv /mnt

3. Physical Volume (PV) Commands

CommandDescription
pvcreate /dev/sdXInitialize a physical volume
pvdisplayShow detailed info about PVs
pvsShow a summary of all PVs
pvscanScan all disks for PVs
pvremove /dev/sdXRemove a physical volume (wipe LVM data)

4. Volume Group (VG) Commands

CommandDescription
vgcreate my_vg /dev/sdXCreate a volume group
vgextend my_vg /dev/sdYAdd PV to VG
vgreduce my_vg /dev/sdYRemove PV from VG
vgsShow summary of all VGs
vgdisplayDetailed info about VGs
vgremove my_vgRemove a VG
vgchange -a yActivate all volume groups
vgchange -a nDeactivate all volume groups

5. Logical Volume (LV) Commands

CommandDescription
lvcreate -L 10G -n my_lv my_vgCreate a logical volume
lvextend -L +5G /dev/my_vg/my_lvExtend a logical volume
lvresize -L 15G /dev/my_vg/my_lvResize LV to specific size
lvreduce -L 8G /dev/my_vg/my_lvReduce LV size (⚠️ careful!)
lvremove /dev/my_vg/my_lvRemove an LV
lvdisplayDetailed info about LVs
lvsShow summary of all LVs
lvscanScan for logical volumes

6. Resizing File Systems with LVM

⚠️ Always backup before resizing!

 Extend Logical Volume and File System:

 
sudo lvextend -L +5G /dev/my_vg/my_lv sudo resize2fs /dev/my_vg/my_lv # For ext4

⚠️ Shrink Logical Volume and File System:

 
sudo umount /dev/my_vg/my_lv sudo e2fsck -f /dev/my_vg/my_lv sudo resize2fs /dev/my_vg/my_lv 8G sudo lvreduce -L 8G /dev/my_vg/my_lv sudo mount /dev/my_vg/my_lv /mnt

7. Removing LVM Components

TaskCommand
Unmount the LVumount /mnt
Remove LVlvremove /dev/my_vg/my_lv
Remove VGvgremove my_vg
Remove PVpvremove /dev/sdX

8. Useful Monitoring and Status Commands

CommandDescription
lsblkLists all block devices (including LVMs)
df -hDisk space usage (mounted volumes)
mountCheck mounted file systems
blkidDisplay block device UUIDs and types
lvs, vgs, pvsShow LVM components in summary
				
					How To Cheking Linux Ubantu Disk Status?
.........................................
lsblk
fdisk -l
df -hT
lsblk -f                                              <Cheking Formating Partition >
mount -av                                             <cheking Mounting>


How To Create Linux Ubantu LVM?
...............................
Step#01 fdisk /dev/sdb                                        <Go To HDD >
Step#02 n, p, t, 8e, w                                        <New Partion Create>
Step#03 partprobe /dev/sdb                                    <Karnel Infom For New HDD Partition>
Step#04 pvcreate /dev/sdb1                                    <Create Pv>
Step#05 vgcreate nextcloud /dev/sdb1                          <Create VG>
Step#06 lvcreate -L 500G -n nextcloud nextcloudlv             <Create LV>
Step#07 mkfs.ext4 /dev/mapper/nextcloud-nextcloudlv           <Formating> 
Step#08 mount /dev/mapper/nextcloud-nextcloudlv /var/www/html <Create Mount Point For Use Disk Space>
Step#09 df -hT                                                <For Checking Mount>
Step#10 cat/etc/mtab                                          <Copy Full Path nextcloud-nextcloudlv For Entry Fstab>
Step#11 nano /etc/fstab
Step#11 /dev/mapper/nextcloud-nextcloudlv /var/www/html ext4   errors=remount-ro 0 1 <Paste This Line Fstab Then Save>



How To Cheking Linux Ubantu LVM Status?
........................................
pvdisplay              
vgdisplay
lvdisplay
lvs
vgs
pvs
lvscan
pvscan
vgscan



How To Remove Linux Ubantu LVM?
...............................
lvremove /dev/nextcloud/nextcloudlv





				
			
				
					Ubantu LVM Root Partion Extend
...............................

1.sudo fdisk -l : find new drive
or lsblk or df -h

2.sudo pvscan

3.sudo fdisk /dev/sdb
n
p
1
[enter]
[enter]
t
8e
w

5.lsblk and see /dev/sdb1 added
if /dev/sdb1 is not seen then reboot before continuing further

6.sudo pvcreate /dev/sdb1

7.sudo vgdisplay : look for VG Name value (ubuntu-vg, vg00 etc)

8.sudo vgextend ubuntu-vg /dev/sdb1

9.sudo pvscan

10.sudo lvdisplay : look for LV Path value

11.sudo lvextend /dev/ubuntu-vg/ubuntu-lv /dev/sdb1
OR
sudo lvextend -L +5G /dev/my_vg/my_lv sudo resize2fs /dev/my_vg/my_lv # For ext4


12.sudo resize2fs /dev/ubuntu-vg/ubuntu-lv

lsblk will now show your size increase

				
			

Disk Management

				
					How to check hdd?
.................
sudo fdisk -l

How to check partition MBR/GPT
..............................
gdisk /dev/sda
lsblk


How to create partition?
........................
sudo fdisk /dev/sda
help- m
n
enter
enter
+20G
p- print
w-save
fdisk -l

How to format partition?
........................
mkfs.ext4 /dev/sda
lsblk -f -chcek format or not partition



How to mount partiton?
......................
sudo mount /dev/sda /<mount folder>
check - sudo mount
        lsblk
				
			
ToolCommandOutput Tells You
partedsudo parted /dev/sdX printgpt or msdos
gdisksudo gdisk -l /dev/sdXMBR or GPT
fdisksudo fdisk -l /dev/sdXDisklabel type
lsblklsblk -fFilesystem info
blkidsudo blkidUUIDs/labels
				
					Convert MBR to GPT using gdisk
...............................
sudo apt update
sudo apt install gdisk


Step 2: Identify the target disk
.................................
List available disks:lsblk
Find your disk (e.g., /dev/sda, /dev/sdb, etc.)


Step 3: Run gdisk to convert MBR to GPT
.......................................
sudo gdisk /dev/sdX
Replace /dev/sdX with your actual disk (not a partition, e.g., /dev/sda)
You’ll see a message like:MBR detected. Do you want to convert it? (Y/N)
Enter Y to proceed with the conversion.



Step 4: Write the new partition table
.....................................
Type the following in gdisk:

w → Write changes to disk

Y → Confirm

This writes the GPT structure and exits.



Step 5: Verify the new partition table
.......................................
sudo parted /dev/sdX print
It should now say: Partition Table: gpt



1. Using lsblk -f + blkid (to check GPT UUIDs)
...............................................
sudo lsblk -f
sudo blkid


2. Using fdisk (Shows Partition Type)
.....................................
sudo fdisk -l /dev/sdX







				
			
				
					How to create multiplefile touch commend?
.........................................
for i in {1..10}; do touch file$i.txt; done


How to create tar file?
......................
tar cvf <filename>.tar <filename> then enter


How to create tar file untar?
..............................
tar xvf <filename>.tar <filename> then enter
tar –xvzf <filename>.tar <filename> then enter



How to create compress reduce size tar file?
.............................................
tar cjf <filename>.tar.gz cvf <filename> then enter


How to create gzip?
....................
gzip <filename>


How to create gzip extarct ?
............................
gunzip <filename>
zcat   <filename>



How to view file size check?
............................
du -sh <filename>



				
			

VPS Server Install Apache WordPress

				
					
1. Install Apache

sudo apt update && sudo apt install apache2
............................................
2. Configure Firewall

sudo ufw allow OpenSSH

sudo ufw allow in "Apache Full"

sudo ufw enable

sudo ufw status


3. Test Apache
...............

sudo service apache2 status


4. Install MySQL
................

sudo apt update && sudo apt install mysql-server

sudo service mysql status


5. MySQL Security
..................

sudo mysql_secure_installation

-> ENTER | Y | Y | Y | Y

sudo mysqladmin -p -u root version



6. Install PHP
...............

sudo apt update && sudo apt install php libapache2-mod-php php-mysql

php -version


7. Installing phpMyAdmin
........................

sudo apt update && sudo apt install phpmyadmin php-mbstring

sudo ln -s /etc/phpmyadmin/apache.conf /etc/apache2/conf-available/phpmyadmin.conf

sudo a2enconf phpmyadmin.conf

sudo service apache2 reload


8. Create MySQL User
....................

sudo mysql

CREATE USER 'newuser'@'localhost' IDENTIFIED BY 'password';

GRANT ALL PRIVILEGES ON * . * TO 'newuser'@'localhost';

FLUSH PRIVILEGES;
CREATE USER 'username'@'ip_address' IDENTIFIED BY 'password';
exit


9. Secure PhpMyAdmin
....................

sudo nano /etc/apache2/conf-available/phpmyadmin.conf

Alias /your_url /usr/share/phpmyadmin

sudo service apache2 reload



10. Install ZIP/Unzip
......................

apt-get update

apt-get install zip unzip



11. Enable .htaacess
.....................

sudo apt-get update

sudo a2enmod rewrite

systemctl restart apache2

sudo nano /etc/apache2/sites-enabled/000-default.conf

<Directory "/var/www/html">
  AllowOverride All
</Directory>


12. Configure Apache File
..........................

sudo nano /etc/apache2/apache2.conf

<Directory /var/www/>
    Options Indexes FollowSymLinks
    AllowOverride All
    Require all granted
 </Directory>

 <Directory /var/www/html>
    Options -Indexes
 </Directory>

 ServerSignature Off
 ServerTokens Prod


13. install SSL Certificate
............................

sudo apt update && sudo apt install certbot python3-certbot-apache

sudo certbot --apache

service apache2 restart
				
			

Redhat RHEL,Cent-OS User Group Commnds

1. Add / Create Users

CommandDescription
sudo adduser usernameAdd a user (interactive)
sudo useradd usernameAdd user (scriptable, non-interactive)
sudo passwd usernameSet password for a user
sudo useradd -m -s /bin/bash usernameCreate user with home directory and shell

Example:

 
sudo useradd -m -s /bin/bash alice sudo passwd alice

2. Delete / Remove Users

CommandDescription
sudo userdel usernameDelete a user
sudo userdel -r usernameDelete user and home directory

3. Modify Existing Users

CommandDescription
sudo usermod -l newname oldnameRename user
sudo usermod -d /new/home -m usernameMove home directory
sudo usermod -s /bin/zsh usernameChange user’s shell
sudo usermod -aG groupname usernameAdd user to a group (append)

Example:

 
sudo usermod -aG wheel alice

4. Lock / Unlock User Accounts

CommandDescription
sudo usermod -L usernameLock account (disable login)
sudo usermod -U usernameUnlock account
sudo passwd -l usernameLock password
sudo passwd -u usernameUnlock password

5. Add / Manage Groups

CommandDescription
sudo groupadd groupnameAdd new group
sudo groupdel groupnameDelete a group
sudo groupmod -n newname oldnameRename a group
sudo gpasswd -a username groupnameAdd user to group
sudo gpasswd -d username groupnameRemove user from group

Example:

 
sudo groupadd devs sudo gpasswd -a alice devs

6. View User & Group Info

CommandDescription
id usernameShow UID, GID, and groups
groups usernameList groups a user belongs to
getent passwd usernameShow user entry
getent group groupnameShow group entry
cat /etc/passwdList all users
cat /etc/groupList all groups

7. Sudo (Admin) Access

Add user to sudo group (Red Hat uses wheel):

 
sudo usermod -aG wheel username

Check sudo access:

 
sudo -l -U username

8. Change User Shell

CommandDescription
chsh -s /bin/bash usernameChange user’s default shell
cat /etc/shellsList available shells

Example:

 
sudo chsh -s /bin/zsh alice
 

 9. Account Expiry and Password Aging

CommandDescription
chage -l usernameShow password aging info
sudo chage -E 2025-12-31 usernameSet account expiration date
sudo chage -M 90 usernameSet max password age to 90 days
sudo chage -m 7 usernameSet min password age to 7 days
sudo chage -W 10 usernameWarn 10 days before expiry

 11. Switch Users and Become Root

CommandDescription
su - usernameSwitch to another user
sudo su -Become root user
sudo -iOpen a root login shell

Quick Summary Table

TaskCommand
Add useradduser / useradd
Delete useruserdel -r
Add groupgroupadd
Add user to groupusermod -aG
Set passwordpasswd
Lock/unlock userusermod -L/-U
View groupsgroups / id
Give sudo accessAdd to wheel group

Ubantu Server Firewall UFW Commnds

1. What is UFW?

UFW (Uncomplicated Firewall) is a frontend for iptables that makes it easier to manage firewall rules on Ubuntu. It’s ideal for most users who want simple, secure, and readable firewall configurations.

2. Enable or Disable UFW

TaskCommand
Enable firewallsudo ufw enable
Disable firewallsudo ufw disable
Check firewall statussudo ufw status
Verbose statussudo ufw status verbose
Reset firewall (clear all rules)sudo ufw reset

3. Allow or Deny Services and Ports

 Allow Traffic

TaskCommand
Allow specific portsudo ufw allow 22
Allow service by namesudo ufw allow ssh
Allow port with protocolsudo ufw allow 80/tcp
Allow port rangesudo ufw allow 1000:2000/tcp
Allow IP access to portsudo ufw allow from 192.168.1.100 to any port 22

 Deny Traffic

TaskCommand
Deny specific portsudo ufw deny 23
Deny servicesudo ufw deny telnet

4. Managing Incoming/Outgoing Rules

TaskCommand
Allow outgoing trafficsudo ufw default allow outgoing
Deny all incoming by defaultsudo ufw default deny incoming
Allow all incomingsudo ufw default allow incoming
Deny all outgoingsudo ufw default deny outgoing

5. Deleting Rules

TaskCommand
Delete by rulesudo ufw delete allow 22
Delete by number (from ufw status numbered) 
 
sudo ufw status numbered sudo ufw delete [number]

6. Logging & Monitoring

CommandDescription
sudo ufw logging onEnable logging
sudo ufw logging offDisable logging
sudo ufw status verboseShow with logging info
Logs are stored in/var/log/ufw.log

7. Application Profiles

Many services define UFW profiles (e.g., OpenSSH, Apache, Samba, etc.)

TaskCommand
List available profilessudo ufw app list
Show details of a profilesudo ufw app info Apache
Allow a profilesudo ufw allow 'Apache Full'

8. Enable UFW on Boot

UFW is usually enabled to start at boot automatically once you enable it:

 
sudo systemctl enable ufw

9. Disable UFW Temporarily

TaskCommand
Disable firewallsudo ufw disable
Re-enable firewallsudo ufw enable

10. Common Examples

TaskCommand
Allow SSHsudo ufw allow ssh or sudo ufw allow 22
Allow HTTP & HTTPSsudo ufw allow 80,443/tcp
Allow MySQL from local networksudo ufw allow from 192.168.1.0/24 to any port 3306
Block all except SSH 
 
sudo ufw default deny incoming sudo ufw allow ssh

Check Summary

 
sudo ufw status numbered sudo ufw status verbose

 Important Tips

  • Always allow SSH before enabling the firewall remotely:

     
    sudo ufw allow ssh sudo ufw enable

Redhat,Cent-OS Server Firewall Commnds

Basics of firewalld on CentOS / RHEL

  • Service: firewalld

  • Command-line tool: firewall-cmd

  • Zones: Used to define trust levels for network connections (e.g., public, internal, external, etc.)

  • Default zone: Usually public

				
					Start/Enable/Disable firewalld
...............................
sudo systemctl start firewalld       # Start the firewall
sudo systemctl enable firewalld      # Enable at boot
sudo systemctl stop firewalld        # Stop the firewall
sudo systemctl disable firewalld     # Disable at boot
sudo systemctl status firewalld      # Check status


Check firewall status & rules
.............................
firewall-cmd --state                             # Running or not
firewall-cmd --get-active-zones                  # Shows active zones
firewall-cmd --get-default-zone                  # Default zone
firewall-cmd --list-all                          # List all rules for default zone
firewall-cmd --list-all --zone=public            # List rules for a specific zone
firewall-cmd --list-services                     # List allowed services


Add / Remove Ports and Services
................................
Add service (permanent and runtime)
# Runtime (immediate)
sudo firewall-cmd --zone=public --add-service=http

# Permanent (persists after reboot)
sudo firewall-cmd --zone=public --add-service=http --permanent
sudo firewall-cmd --reload    # Reload to apply permanent rules



Remove service
...............
sudo firewall-cmd --zone=public --remove-service=http --permanent
sudo firewall-cmd --reload



Add port
.........
sudo firewall-cmd --zone=public --add-port=8080/tcp --permanent
sudo firewall-cmd --reload


Remove port
...........
sudo firewall-cmd --zone=public --remove-port=8080/tcp --permanent
sudo firewall-cmd --reload



Rich Rules (Advanced)
Example: Allow IP through firewall
...................................
sudo firewall-cmd --permanent --add-rich-rule='rule family="ipv4" source address="192.168.1.100" accept'
sudo firewall-cmd --reload

Example: Block an IP
sudo firewall-cmd --permanent --add-rich-rule='rule family="ipv4" source address="192.168.1.200" reject'
sudo firewall-cmd --reload


Reload / Reset Firewall
.......................
sudo firewall-cmd --reload                         # Reload after changes
sudo firewall-cmd --complete-reload                # Full reload (drops runtime configs)
sudo firewall-cmd --permanent --reset-default-zone # Reset default zone


Lockdown Mode
..............
sudo firewall-cmd --lockdown-on                   # Enable lockdown
sudo firewall-cmd --lockdown-off                  # Disable lockdown
sudo firewall-cmd --query-lockdown                # Check lockdown status


Predefined Services
...................
firewall-cmd --get-services



				
			

File Transfer Linux Server SCP Commnds

				
					SCP stands for Secure Copy Protocol
...................................

Copy from local to remote
..........................
scp /path/to/local/file username@remote_host:/path/to/remote/destination

Example:

scp file.txt root@192.168.1.100:/home/root/



Copy from remote to local
.........................
scp username@remote_host:/path/to/remote/file /path/to/local/destination

Example:

scp file.txt root@192.168.1.100:/home/root/



Copy a directory recursively
............................
scp -r /local/dir username@remote_host:/remote/dir

Example:

scp -r myfolder user@192.168.1.101:/var/www/



Specify a non-default port
..........................
scp -P 2222 file.txt user@host:/path/


Upload file to remote server
............................
scp index.html root@192.168.1.10:/var/www/html/


Download file from remote server
.................................
scp root@192.168.1.10:/var/log/messages ~/logs/


Copy folder to remote server with port
......................................
scp -P 2200 -r website/ user@host:/home/user/


Transfer a ZIP file via SCP
............................
From Local to Remote
scp website_backup.zip root@192.168.1.10:/home/root/backups/


From Remote to Local
.....................
scp root@192.168.1.10:/home/root/website_backup.zip ~/Downloads/


Combine zip and scp in one line (local to remote)
.................................................
zip -r myfolder.zip myfolder && scp myfolder.zip user@host:/destination/


SSH uses a non-default port (e.g., port 2222)
.............................................
scp -P 2222 myfile.zip user@host:/remote/path/


Common Options:
-r: Recursively copy entire directories.
-P: Specify a custom SSH port (note the uppercase P).
-i: Specify a private key file for authentication.
-v: Enable verbose mode to see more detailed output for debugging.
-C: Enable compression to speed up the transfer for large files.

				
			

Linux Server File Compression

				
					ls -lh
Compressing a Big file
.......................
gzip myfile.txt           # Produces myfile.txt.gz


Unompressing a Big file
.......................
gunzip myfile.txt


Directory Compress
...................
mkdir backup        <Create a Folder>
tar -cvf backup.tar backup/ <Backup/ Means Folder Name>
ls -ltr              <Show File>
gzip backup.tar      <Compress For Backup.tar File>
ls


D Compress
..........
tar -xzvf backup.tar.gz
ls -ltr

Without backup.tar.gz Extrat File Show
.......................................
tar -tzvf backup.tar.gz
Or
zcat backup.tar


Single Step Commnd Compress
............................
tar -czvf backup.tar.gz backup
tar -xzvf backup.tar.gz backup <Extract Commnd>


Zip Commnd
..........
Example- file1 file2
Compress:- zip file.zip file1 file2 
ls -ltr


Without file.zip Extrat File Contain Show
..........................................
zipinfo files.zip
unzip -l files.zip

UnZip Commnd
.............
unzip file.zip



scp -v backup.tar.gz user@192.168.1.100:/home/user/backups/


Check the File on Remote
........................
ssh user@192.168.1.100
ls -lh /home/user/backups/



				
			

rsync on Linux Server

What is rsync?

rsync is a powerful, efficient tool used to copy and sync files/directories between locations, either locally or over a network (e.g., between two servers). It only transfers changed parts of files, making it much faster than scp for repeated syncs.

				
					1. Installing rsync on Ubuntu
.............................
Open a terminal and run:
sudo apt update
sudo apt install rsync

Check the version to confirm installation
..........................................
rsync --version


2. Basic rsync Usage
.....................
Local Sync (Directory to Directory):

rsync -av /source/folder/ /destination/folder/


-a: Archive mode (preserves permissions, timestamps, etc.)

-v: Verbose (shows progress)


Remote Sync (Over SSH)
......................
From Local to Remote:
rsync -av /local/folder/ user@remote_ip:/remote/folder/


You can add -z for compression if sending over the internet:
rsync -avz /local/folder/ user@remote:/remote/folder/

Example

rsync -av backup.tar.gz user@192.168.1.100:/home/user/backups/


Using SSH Key (Optional, Recommended)
.....................................
To avoid typing the password every time:

1.Generate SSH key (if you don’t have one):
ssh-keygen


2.Copy it to remote server:
ssh-copy-id user@remote_ip


3.Now rsync will work without asking for a password.