Frequently Used Linux Commands

Introduction

This post originated from my personal notes while learning Linux back when there was no AI assistance, so you’ll find a mix of beginner and more advanced commands. All of them work, and remember that in Linux there are many ways to achieve the same task.

Also remember to search using CTRL+F, both with accents and without accents, because sometimes I typed with an English keyboard and it wasn’t easy to use accent marks.
For example, if you want to see how to set a static IP in CentOS, search for “direccion” without an accent and jump through the results until you find what you’re looking for.

These commands are mainly from Debian and RedHat families.

Index

General commands

– Requesting Help for Any Command

Linux

man <comando>

Example:
man grep

– Disk Partitioning

– Create, View, Delete Partitions

Linux

fdisk /dev/hda

– Create a Partition on the Primary Hard Drive

Linux

mkfs -t ext2 -c /dev/hda1
  • -t specifies the filesystem type (ext2 in this case).
  • -c checks for bad sectors before formatting.

Recommended disk layout (varies depending on intended Linux use):

  • /boot → 102–150 MB
  • /swap → Twice the physical memory
  • / (root) → The rest of the disk
  • Ext3 is preferable → ext2 with journaling

– Clear the Screen

Linux

clear

– Reset Terminal to Default Values

Linux

reset

– Show System Users Information

Linux

finger

– Show Users Currently Logged In

Linux

who

– Display Logged‑in Users and Their Sessions/Tasks

Linux

w

– Show Current Username

Linux

whoami

– Show Numeric IDs and Groups for Current User

Linux

id

– Show Current Date and Time

Linux

date

– Show Calendar for Current Month

Linux

cal

– View File Contents

Linux

cat

– Exit the Current Shell

Linux

exit

– Print Output to the Screen

Linux

echo

– Show Current Shell

Linux

echo $SHELL

– Shell Variable

Linux

$

– Home Directory Shortcut

Used for example with cd ~ which takes you to /home/<user>.

Linux

~

– Run a Command in the Background

Example:
nmap -O 192.168.1.1-24 & runs Nmap in the background while you continue using the terminal.

Linux

&

– Input/Output Redirection

Linux

< << > >>

– Pipe to Chain Commands

Example:
cat file.txt | grep name

Linux

|

– Shell Wildcards

Example:
ls *.txt

Linux

?[]*

– Quoting and Metacharacters

Linux

' " \

– Command Substitution

Linux

`

– Grouping Commands

Linux

() {}

– Cancel a Running Command

Press and hold CTRL, then press C.

Linux

CTRL+C

File Viewing, Search & Text Processing

– View the Last 10 Lines of a Text File

Linux

tail <nombrearchivo>

– View the Last 30 Lines

Linux

tail -30 <nombrearchivo>

– Follow File Changes in Real Time (useful for logs)

Linux

tail -f <nombredelarchivo>

– View the First 10 Lines

Linux

head <nombrearchivo>

– View the First 30 Lines

Linux

head -30 <nombrearchivo>

– List the Most Recently Modified File in a Directory

Linux

ls -Art | tail -n 1

– Show Only Directories

Linux

ls -l|grep ^d
ls -p |grep /
ls -l | egrep '^d'

– Search for Text in Files (basic examples)

Linux

grep "spc_eee1.gif" *
grep -r -i "textoAbuscar" *.*

-r = recursive
-i = ignore case

– Search for Text and Show Line Numbers

Linux

grep -nr textoabuscar

– Use awk to Extract Columns (example: extract IPs from Apache logs)

Linux

awk '{print $1}' access-hackvolution.log

– Remove Duplicate Results Using sort and uniq

Linux

awk '{print $1}' access-hackvolution.log |sort |uniq

– Count Repeated Values and Sort by Frequency

Linux

awk '{print $1}' access-hackvolution.log |sort |uniq -c |sort -rn

– Search Inside .sh Scripts for the Word “user”

Linux

find / -name '*.sh' 2>/dev/null | xargs grep -i 'user'

– Search for Script Files (.ksh, .sh, .pl, .py, .zsh, .bash, .bsh, .sql)

Linux

find / -type f \( -iname \*.ksh -o -iname \*.sh -o -iname \*.pl -o -iname \*.py -o -iname \*.zsh -o iname \*.bash -o -iname \*.bsh -o -iname \*.sql \)

– Search for Files Owned by a User and Starting with “#!” (shebang)

Linux

find / -user $UID -type f | while read fn; do head -n1 "$fn" | grep -q "^#\!" && echo "$fn" && chmod 755 "$fn"; done

– Search for the Word “password” in Script Files

Linux

grep --include=\*.{ksh,sh,pl,py,zsh,bash,bsh,sql} -rnw '/' -e "password"

– Alternative Text Search Examples

Linux

grep 'user' $(find / -name '*.sh')
find / -name '*.sh' -exec grep 'texto' {} \;

– Remove Commented Lines from squid.conf (remove lines starting with # and empty lines)

Linux

cat /etc/squid/squid.conf | egrep -v "^\s*(#|$)"

– Remove First and Last Character of Each Line

Linux

cat lista.txt | cut -c 2- | sed 's/.$//' > clean-lista.txt

– Extract Valid IPs Using Regex

Linux

grep -oE '(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)' file.txt

– Search for Files Containing “wants to contact you”

Linux

find ./ -name *.htm |xargs grep "wants to contact you"

– Exclude a Directory While Searching

Linux

find / \( ! -name tmp -o -prune \) -name "file.rar" -print 2>/dev/null

– Search Using locate (requires index)

Linux

locate <nombredelarchivoabuscar>

– Remove Comments and Clean Configuration Files Using sed

Linux

sed -e '/string-aqui/d' /opt/archivo-origen.csv > archivodestino.csv

– Remove Windows CR Line Endings

Linux

sed -i 's/\r$//' nombredelarchivo.txt

– Delete Everything From a Keyword to End of File

Linux

sed -i '/mfa/,$d' ~/.aws/credentials

– Convert DOS Line Endings to Unix Using dos2unix

Linux

dos2unix <nombredelarchivo>

– Hexadecimal View of Files

Linux

hexdump -C <nombrearchivo>

– Sort IPs Numerically

Linux

sort -t . -k 1,1n -k 2,2n -k 3,3n -k 4,4n ips.txt

– Quick Version-Based Sort

Linux

sort -V ips.txt

– Extract Public IP

Linux

dig +short myip.opendns.com @resolver1.opendns.com

– Convert File Names from Windows Encoding to UTF‑8

Linux

convmv -f latin1 -t utf-8 -r --notest *

– Convert ANSI/ASCII Files to UTF‑8

Linux

iconv -f 8859_1 -t utf-8 2lista.lst > lista.lst

File & Directory Management

– Clear the Screen

Linux

clear

– Exit the Current Shell

Linux

exit

– Print Text on Screen

Linux

echo

– List Files in Long Format

Linux

ls -l

– Show Number of Files in a Directory

Linux

echo *.* | wc

– Show Number of Directories in a Folder

Linux

echo */ | wc

– Delete All Files with Extension *.xxx Across the Entire Disk

Linux

find / -type f -name "*.xxx" -exec rm {} \;

– Delete Directories (Be Careful With -rf)

Linux

rm -rf foldername

– Remove Empty Directories

Linux

rmdir <nombredelfolder>

– Delete All Files Except One Folder (example: keep “wiki”)

Linux

shopt -s extglob
rm -rf -v !("wiki")

– Copy Entire CD-ROM Contents to a Folder

Linux

cp -av /mnt/cdrom /install

– Copy Files Incrementally Using rsync

Linux

rsync -avzhP /home/lmoreno/datos lmoreno@192.168.1.50:/mnt/data/datosbackup

-v verbose
-r recursive
-a archive mode
-z compress
-h human readable
-P progress

– Copy Remote Directory to Local Directory

Linux

rsync -aOvzhP -e "ssh -i EC2.private" root@192.168.1.30:/var/www/html/content/user_1/shoutcast198 /home/ec2-user/logs/

-O do not copy folder timestamps

– Move Many Files When “Argument List Too Long” Error Appears

Linux

find . -type f -name "*.txt" -exec mv {} /opt/movehere/ \;

– Move Files One by One Using find

Example of workaround for “Argument list too long”:

Linux

-bash: /bin/mv: Argument list too long
Linux

for i in `find . -name ap\*`
do
mv $i ..
done

– Change File Extensions in Bulk

Linux

for f in *.htm; do mv $f `basename $f .htm`.html; done;

– Concatenate Files into One

Linux

cat *.csv >> archivoconcatenado.csv

– Create Backup of a Folder in Compressed Form

Linux

tar -czvf myarchive.tgz mydirectory/

– Compress a Folder into a .tar.gz File

Linux

tar -zcvf archive_name.tar.gz directory_to_compress

-z gzip
-c create
-v verbose
-f file

– Compress Entire Folder in zip Format

Linux

zip -qq -R archivozip directorio

– Compress All .html Files into a Zip

Linux

find . -name "*.html" | xargs zip HTMLs-Nessus

– Extract a .zip File

Linux

unzip nombre-archivo

– Extract a tar.bz2 File

Linux

tar -xvjf file.tar.bz2

– Extract a .tar File

Linux

tar -xvf foo.tar

– Extract a .gz File

Linux

gunzip archivo.gz

– Extract Contents of a .zip Without Output

Linux

unzip -qq archive -d ruta-directorio

– Extract rar Files (install unrar first)

Linux

yum install unrar

Then:

Linux

unrar x archivo.rar

– Split a File Into Smaller Parts (by size example)

Linux

split -b 200M nombredearchivo

– Sort Folder Sizes from Smallest to Largest

Linux

du -hs * | sort -h

– Show Largest Files in Current Directory (top 10)

Linux

du -hs * | sort -rh | head -10

– Show Largest Files Including Subdirectories (top 10)

Linux

du -Sh | sort -rh | head -10

– Show Used Disk Space

Linux

df -h

– Show Size of a Specific Folder

Linux

du -s /media/Nabucodonosor/data

– Show Disk Usage Summary of Subfolders

Linux

du --max-depth=1 -h

– Create a File Filled with Zeros

Linux

dd if=/dev/zero of=/test bs=1048576 count=1024

Users, Groups & Permissions

– Add a User

Linux

useradd <nombreusuario>

– Set User Password

Linux

passwd <nombreusuario>

Example:

Linux

useradd -c "Luis Moreno" morenol
passwd mi_password
-c sets the GECOS field (user description)

– Add User With Custom Home and Shell

Linux

/usr/sbin/useradd -d /home/lmoreno -s /bin/bash -c "Luis Moreno" lmoreno && mkdir /home/lmoreno && chown lmoreno /home/lmoreno && passwd mysupapassw0rd

– Same as Above but Without Setting Password

Linux

/usr/sbin/useradd -d /home/lmoreno -s /bin/bash -c "Luis Moreno" lmoreno && mkdir /home/lmoreno && chown lmoreno /home/lmoreno

– Delete a User

Linux

deluser <nombredeusuario>

Example:
deluser -r dsantos
-r removes home directory and mailbox

– List System Users

Linux

cat /etc/passwd

– List System Groups

Linux

cat /etc/group

– Add a Group

Linux

groupadd <nombredelgrupo>

– Lock/Disable a User (manual method)

Linux

agregar el signo "+" delante de la línea del usuario en el archivo /etc/passwd

– Lock User Using passwd

Linux

passwd -l <nombreUsuario>

– Add User to Supplementary Group

Linux

usermod -a -G web luis

– Change User’s Primary Group

Linux

usermod -g www luis

– Change File Permissions (symbolic)

Linux

chmod u+wr,g+wr,o-r

– Change File Permissions (numeric)

Linux

chmod 664

read = 4
write = 2
execute = 1

– Make File Executable for Everyone

Linux

chmod 111 <nombreDelArchivo>

– Give Root Full Permissions on a File

Linux

chmod 700 <nombreDelArchivo>

– Give Full Permissions to Everyone (dangerous)

Linux

chmod 777 <nombreDelArchivo>

– Apply rwx Permissions Recursively on Folder and Subfolders

Linux

chmod 777 -R archivos/*

– Clone Permissions From One File to Another

Linux

chown --reference=otherfile thisfile

– Create a Device File

Linux

mknod /dev/fd1 b 2 1

– Change File Owner

Linux

chown luis /carpeta/archivo

– Change File Owner and Group

Linux

chown luis.grupo /carpeta/archivo

– Change Group Ownership Only

Linux

chgrp grupo /carpeta/archivo

– Password Policy Configuration: Edit /etc/login.defs

Linux

PASS_MAX_DAYS 60
PASS_MIN_DAYS 0
PASS_MIN_LEN 8
PASS_WARN_AGE 10

Explanation:

  • PASS_MAX_DAYS → maximum days before requiring password change
  • PASS_MIN_DAYS → minimum days before password can be changed again
  • PASS_MIN_LEN → minimum password length
  • PASS_WARN_AGE → expiration warning days

– Apply Password Policy to Existing Users Using chage

– Enable Strong Password Enforcement With pam_cracklib

Networking & IP Configuration

– Show Network Configuration (CentOS/RedHat)

Linux

cat /etc/sysconfig/network-scripts/ifcfg-eth0

– Show Network Configuration (Debian/Ubuntu)

Linux

cat /etc/sysconfig/network

– Example Network Configuration (CentOS)

Linux

HWADDR=00:08:A2:0A:BA:B8
TYPE=Ethernet
BOOTPROTO=none
IPADDR=192.168.2.203
PREFIX=24
GATEWAY=192.168.2.254
DNS1=192.168.2.254
DNS2=8.8.8.8
DNS3=8.8.4.4
DEFROUTE=yes
IPV4_FAILURE_FATAL=no
IPV6INIT=no
NAME=eth0
UUID=41171a6f-bce1-44de-8a6e-cf5e782f8bd6
DEVICE=eth0
ONBOOT=yes

– Restart Network Service

Linux

systemctl restart network

– View dmesg for Newly Connected Hardware

Linux

dmesg
dmesg |grep sdb

– Mount USB or External Disk

Linux

mount /dev/sdb1 /media/usb

– Mount NTFS Partition

Linux

mount -t ntfs-3g /dev/sda2 /media/DiscoLocalC -o force

– Change System Timezone (Ubuntu)

Linux

dpkg-reconfigure tzdata

– TCP Traceroute to a Specific Port

Linux

traceroute -T -p 80 72.14.213.104

– Network Configuration in Ubuntu (interfaces file)

Linux

/etc/network/interfaces

– Example Static IP (Ubuntu)

auto eth0 iface eth0 inet static address 192.168.1.100 netmask 255.255.255.0 gateway 192.168.1.254 dns-nameservers 192.168.1.254

– Configure Static IP in Netplan (Ubuntu 18+)

Linux

sudo vim /etc/netplan/50-cloud-init.yaml

network: ethernets: enp0s3: addresses: [192.168.1.2/24] gateway4: 192.168.1.1 nameservers: addresses: [8.8.8.8,8.8.4.4] dhcp4: no version: 2

– Apply Netplan Config

Linux

sudo netplan apply

– Configure DHCP with Netplan

Linux

sudo vim /etc/netplan/50-cloud-init.yaml

network: ethernets: enp0s3: addresses: [] dhcp4: true version: 2

– Restart Networking (Ubuntu)

Linux

sudo ip addr flush eth0 && sudo systemctl restart networking.service

– Bring Network Interface Up

Linux

ip link set eth0 up

– Set IP Address

Linux

ip addr add 10.23.34.46/29 dev eth0

– Delete IP Address

Linux

ip addr del 10.23.34.46/29 dev eth0

– Set Default Route

Linux

ip route add default via 47.23.34.41 dev eth0

– View Routes (Route Table)

Linux

route -n

– View Routing Table (Alternative)

Linux

netstat -r

– Add Static Route

Linux

route add -net 200.66.81.64 netmask 255.255.255.192 dev eth0

– Bring Interface Down

Linux

ifdown eth0

– Bring Interface Up

Linux

ifup eth0

– Change MAC Address (MAC Spoofing)

Linux

ifdown eth0
ifconfig eth0 hw ether 00:01:02:03:04:05
ifup eth0

– Configure DNS Temporarily

Linux

echo "nameserver 192.168.16.254" >> /etc/resolv.conf

– Edit resolv.conf Manually

Linux

vi /etc/resolv.conf

– Flush DNS Cache

Linux

/etc/rc.d/init.d/nscd restart

– ARP: Add ARP Entry

Linux

arp -s 200.66.81.110 00:04:23:DC:D9:AC

– List ARP Table

Linux

arp -n

– ARP Neighbors

Linux

arp -an
ip neigh
sudo arp-scan -l

– Change Hostname (RedHat)

Linux

hostname nuevonombre

– Edit Hostname Permanently

Edit:

/etc/sysconfig/network

HOSTNAME=

– Change Hostname in Ubuntu

Linux

hostname nuevonombre

Edit:

/etc/hostname

– Mount Windows Shared Folder (CIFS)

Linux

mount -t cifs //servidor/carpetawindows -o username=luis.moreno,password=Misuperpassword /mnt/windows

– Older Systems (smbfs)

Linux

mount -t smbfs -o username=luis.moreno,password=Misuperpassword //servidor/carpetawindows /mnt/windows

– List Open Network Files

Linux

lsof -i -n

– Detect Link Speed (Ethernet)

Linux

ethtool eth0

SSH, SCP & Remote Access

– Enable SFTP and SCP Support (RedHat)

To use SFTP and SCP, ensure this line exists in /etc/ssh/sshd_config:

Linux

Subsystem sftp /usr/libexec/openssh/sftp-server

– Copy a Local File to a Remote Host

Linux

scp archivo-origen usuario@host:directorio/archivo-remoto

– Copy a File From a Remote Host to Local

Linux

scp usuario@host:directorio/archivo-origen archivo-destino

– SCP Using a Non‑Default Port (use -P)

Linux

scp -P 2222 usuario@host:/directorio/archivo-origen archivo-destino

– Copy an Entire Folder to a Remote Host (recursive)

Linux

scp -r directorio-origen usuario@host:directorio-destino

– Copy a Remote Folder to Local (with private key)

Linux

scp -r -i /Users/lmoreno/MyDropbox/EC2/EC2.private root@stream.com:/var/www/html/content/user_1/shoutcast198/* .

– Copy a Local File to Remote Using Private Key and Custom Port

Linux

scp -P 443 -i /Users/lmoreno/MyDropbox/EC2/Luisit0.private /Users/lmoreno/MyDropbox/EC2/EC2.private ubuntu@kolibers.com:/home/ubuntu

– Copy Local Datastore Folder to Remote Server

Example:

Linux

scp -r /vmfs/volumes/datastore/ root@192.168.16.1:/vmfs/volumes/
scp -Cpr /var/www/html/images/products lmorenor@192.168.16.5:/var/www/sites/www.mysitioweb.com/images/products

– Stop SSH Service

Linux

cd /etc/rc.d/init.d

Then:

Linux

sh sshd stop

Or:

Linux

service sshd stop

– Kill SSH Sessions (Find PIDs)

Linux

netstat -tanp

Look for ESTABLISHED SSH connections, then kill the PID:

kill 29460
Avoid using kill -9 unless absolutely necessary.

– Configure SSH Timeout (Disconnect Idle Users)

Edit /etc/ssh/sshd_config and add:

Linux

ClientAliveInterval 600
ClientAliveCountMax 3

This disconnects idle sessions after ~30 minutes.

– Change Default SSH Port (22 → custom)

Edit:

Linux

vi /etc/ssh/sshd_config

Locate:

#Port 22

Change to your custom port, e.g.:

Port 2995

Reload service:

Linux

service sshd reload

– If SSH Is Managed by xinetd

Edit:

Linux

vi /etc/xinetd.d/sshd

Change:

port = 22

Restart service afterward.

– SSH Through a Proxy Using corkscrew

Download corkscrew:

Linux

http://www.agroman.net/corkscrew/

Install:

cd Downloads
tar -xvzf corkscrew-x.y.tar.gz
cd corkscrew-x-y
./configure –host=apple
make
cp corkscrew $HOME/.ssh/

– Modify SSH Client Config to Use Proxy

Edit:

Linux

vim $HOME/.ssh/config

Add:

Linux

ProxyCommand $HOME/.ssh/corkscrew ip-del-proxy puerto %h %p

– Keep SSH Sessions Alive (Client Side)

Edit:

Linux

vim .ssh/config

Add:

ServerAliveInterval 60
ServerAliveCountMax 10

Client will try for ~10 minutes before disconnecting.

– Decompress .gz Files

Linux

gunzip /usr/share/wordlists/rockyou.txt.gz

– Decompress .7z Files

Linux

7za e hashcat-2.00.7z -ohashcat2

– Edit SSH Config File

Linux

vim $HOME/.ssh/config

– Send a Message to All Users (wall)

Linux

wall "Nada mas jugando"

– Find Your Current Terminal

Linux

tty

– Send a Message Directly to Another Terminal

echo "message" > /dev/pts/<number>

– Disable wall Message Reception

Linux

mesg n

– Send Email From Command Line

Linux

echo "20 minutos para la junta" | /bin/mail -s "Meeting" micorreo@miservidor.com

– Change SSH User Temporarily

Linux

su -s /bin/bash - apache

Processes & System Monitoring

– Show All Processes (including other users)

Linux

ps -al

– Show Processes With Their Process Tree and Associated Crontab

Linux

ps -auxfw

– Show Processes Using the Most CPU Resources

Linux

top

Press q to exit the top interface.

– View Open Files and Network Connections

Linux

lsof -i -n

To view files opened by a specific PID:

Linux

lsof -p 8295

– View System CPU Usage for a Specific Core

Linux

grep 'cpu1 ' /proc/stat | awk '{usage=($2+$4)*100/($2+$4+$5)} END {print usage "%"}'

– CPU Usage for All Cores

Linux

grep 'cpu ' /proc/stat | awk '{usage=($2+$4)*100/($2+$4+$5)} END {print usage "%"}'

– CPU1, CPU2, CPU3 Individually

Linux

grep 'cpu1 ' /proc/stat | awk '{usage=($2+$4)*100/($2+$4+$5)} END {print usage "%"}'
grep 'cpu2 ' /proc/stat | awk '{usage=($2+$4)*100/($2+$4+$5)} END {print usage "%"}'
grep 'cpu3 ' /proc/stat | awk '{usage=($2+$4)*100/($2+$4+$5)} END {print usage "%"}'

– View Attempts of Failed Logins (btmp log)

Linux

last -f /var/log/btmp

– Secure btmp permissions (only root should read)

Linux

chown root:utmp /var/log/btmp && chmod 600 /var/log/btmp

– Check Which MTA (Mail Transfer Agent) Is Active

Linux

alternatives --config mta

– View History of Commands

Linux

history

– Show Commands 125 to 130 From History

Linux

fc -l 125 130

– View Command History With Timestamp

Linux

fc -li 100

– Set Date/Time Format for History

Linux

HISTTIMEFORMAT="%Y-%m-%d %T "

– Execute a Command From History (number n)

Linux

!n

– Clear Command History

Linux

history -c

Or manually edit:

~/.bash_history

– Send a Running Process to Background

Linux

ctrl+z

– Resume Background Process

Linux

bg

– Bring Background Job to Foreground

Linux

fg

– View Running Jobs

Linux

jobs

Package Management (RPM, YUM, DPKG, APT)

– Install an .rpm Package

Linux

rpm -ivh <nombre del archivo .rpm>

i = install
v = verbose
h = human-readable progress

– Example: Install Nessus

Linux

rpm -ivh nessus.rpm

– Check if a Package Is Installed

Linux

rpm -q "nombredelpaquete"

– List All Installed RPM Packages

Linux

rpm -qa

– Remove Packages (force if dependencies block uninstall)

Linux

rpm -e --nodeps php-pear-1.4.9-1.2
rpm -e php-5.1.6-1.2

– Find Which Package Provides a File

Linux

locate libdts.so.0

Then:

Linux

yum provides /etc/libdts.so.0

– Install a Package Using YUM

Linux

yum install <nombredelpaquete>

– Search for a Package With YUM

Linux

yum search <paquete>

– Get Detailed Info About a Package

Linux

yum info net-snmp-utils

– Remove Packages With YUM

Linux

yum remove <nombredelpaquete>

– Install a Package From a Specific Repository

Linux

yum --disablerepo=extras install paqueteA

To permanently exclude a package from a repo, add to .repo file:
exclude=paqueteA

– Install Unsigned Packages With YUM

Option 1: install via rpm
Option 2: set gpgcheck=0 in /etc/yum.conf

– Add EPEL Repository

Linux

wget http://dl.fedoraproject.org/pub/epel/epel-release-latest-7.noarch.rpm
rpm -ivh epel-release-latest-7.noarch.rpm

– Check Enabled Repositories

Linux

yum repolist

– Install Package From EPEL

Linux

yum --enablerepo=epel install zabbix

– Update the Entire System

Linux

yum update

– Install an Ubuntu/Debian Package (.deb)

Linux

dpkg -i nombredelarchivo.deb

If dependencies fail:

Linux

sudo apt-get install -f

Then run dpkg -i again.

– Example: Install TeamViewer

Linux

sudo dpkg -i teamviewer_linux.deb

When dependency errors appear, run:

Linux

sudo apt-get install -f

Then reinstall.

– Fix DPKG Overwrite Errors

Linux

sudo dpkg -i --force-overwrite <filename>

– Query Installed Packages in Ubuntu/Debian

Linux

yum list installed

(For rpm-based systems)

– Query Installed Packages With repoquery

Linux

repoquery -a --installed

– Install Packages on RedHat Using apt-rpm (legacy)

Linux

http://dag.wieers.com/rpm/FAQ.php#B

– Common Error With YUM Mirrors

Linux

[Errno 4] IOError: [Errno ftp error] 502 Command REST not allowed by policy.

Solution: download package manually into:

/var/cache/yum/updates/packages

Then run yum install again.

Firewall / IPTables

– IPTables Configuration File (RedHat/CentOS)

/etc/sysconfig/iptables

– Restart IPTables Service

Linux

service iptables restart

– Block a Specific Host

Linux

iptables -I INPUT -s 192.168.16.8 -j DROP

– Allow SSH on Port 22 Only From a Specific IP Range

Linux

iptables -A INPUT -p tcp --destination-port 22 -m iprange --src-range 192.168.16.100 -j ACCEPT

Use:
--src-range = e.g., 192.168.16.100-192.168.16.200

After adding rules, restart service:
service iptables restart

– List Active IPTables Rules

Linux

iptables -L

– Temporarily Allow an IP to Access FTP (port 21)

Linux

/sbin/iptables -I INPUT -s 200.52.66.116/32 -p tcp --dport 21 -j ACCEPT

– Remove the Rule After Testing

Linux

/sbin/iptables -t filter -D INPUT 1

– File With IPTables Custom Scripts

/etc/sysconfig/iptables

– View Open Ports Using netstat

Linux

netstat -pn -A inet

– View Listening Ports

Linux

netstat -lpn -A inet

– View All TCP Ports

Linux

netstat -lantp

Flags explained:

  • -l listening
  • -a all connections
  • -n numeric ports
  • -t TCP
  • -p show PID/program
  • -A inet show only TCP, UDP, raw, etc.

– View Listening Ports Using lsof

Linux

lsof -iTCP -sTCP:LISTEN

– View All Open Ports (TCP/UDP)

Linux

lsof -i

– Scan Localhost Ports Using nmap

Linux

nmap -sT -O localhost

– Identify Unknown Service by Port Number

Check /etc/services:

cat /etc/services | grep 834

If not listed, identify via netstat or lsof:

netstat -anp | grep 834
lsof -i | grep 834

– Find PID of a Running Service

Linux

pgrep sendmail

– Advanced grep + perl for nmap OS detection (unchanged from original)

Linux

cat nmap-os-db | perl -ne 'while(<>) { chomp;if (/^fingerprint\s+([^\#]+)/i) { if (defined($owin) and defined($cwin) and $owin ne $cwin) { print "$oname ($owin vs. $cwin)\n";} $oname=$1;undef($cwin);undef($owin);} elsif (/^T(4|6)\(.*W=([^%]+)/) { if ($1 eq 4){$owin=$2;} else { $cwin = $2; }}}' | sort -f

VNC, X11 & GUI Tools

– Set a VNC Password

Linux

vncpasswd

– Edit VNC Server Configuration (RedHat/CentOS)

File to edit:

/etc/sysconfig/vncservers

– Enable VNC Server at Boot

Linux

chkconfig vncserver on

– Start VNC Server

Linux

service vncserver start

– Configure Advanced VNC Session (custom desktop)

Edit:

/home/username/.vnc/xstartup

– GUI Firewall Configuration Tool

Linux

system-config-securitylevel

– View or Change X11 Display Settings

Main configuration file:

/etc/X11/xorg.conf

– Launch GNOME Desktop Environment

Linux

yum groupinstall "gnome"

– Repair GRUB Bootloader (after Windows overwrites it)

Linux

chroot /mnt/
grub-install /dev/sda

– Edit GRUB Menu Entries (rename OS options)

Linux

vi /boot/grub/menu.lst

Edit names like:

  • “Other” → “Windows XP”
  • “Other” → “Windows Vista”

– Remove GNOME Keyring Password Prompt

Delete:

Linux

.gnome2/keyrings/default.keyring

– Install rdesktop (Remote Desktop Client for Windows)

Linux

yum install rdesktop

Usage example: rdesktop -g 1024x768 windowssrv

– Hex Editor for Red Hat (GUI)

Linux

ghex

– View File in Hexadecimal (CLI)

Linux

hexdump -C <nombrearchivo>

– Change Display Resolution via X11 Config

Edit:

/etc/X11/xorg.conf

– Keyboard Shortcuts for iTerm2 Split Screen (macOS)

Horizontal split:

Linux

CMD + shift + D

Vertical split:

Linux

CMD + D

Crontab & Automation

– View Scheduled Cron Jobs

Linux

crontab -l

– Edit the Current User’s Crontab

Linux

crontab -e

– System Cron File (RedHat/CentOS)

Not recommended to edit directly, but located at:

Linux

`/var/spool/cron/root`

– System Cron File (Ubuntu/Debian)

Linux

/var/spool/cron/crontabs

– Cron Format Reference

Linux

*   *   *   *   *   Comando a ejecutar
-   -   -   -   -
|   |   |   |   |
|   |   |   |   +---- day of week (0–6; Sunday=0)
|   |   |   +-------- month (1–12)
|   |   +------------ day of month (1–31)
|   +---------------- hour (0–23)
+-------------------- minute (0–59)

– Example: Split a File Into Parts Based on Size

Linux

split -b 200M nombredearchivo

– Fix dpkg Update Error (force overwrite)

Linux

sudo dpkg -i --force-overwrite <filename>

– Example Error Message

Linux

error processing /var/cache/apt/archives/python-apport_2.0.1-0ubuntu9_all.deb

Solution (example):

Linux

sudo dpkg -i --force-overwrite /var/cache/apt/archives/python-problem-report_2.0.1-0ubuntu9_all.deb

Disk, Devices & System Boot

– Partition a Disk (create, delete, view partitions)

Linux

fdisk /dev/hda

– Create a Filesystem on a Partition (ext2 example)

Linux

mkfs -t ext2 -c /dev/hda1

-t = filesystem type
-c = check for bad sectors

– Show Disk List / Partitions

Linux

fdisk -l

– Mount a Floppy Disk (MS-DOS format)

Linux

mount -t msdos /dev/fd0 /floppy

– Mount CD-ROM

Linux

mount cd-rom
mount -t iso9660 /dev/cdrom /media/cdrom/

– Mount USB or External Disk

Linux

mount /dev/sdb1 /media/usb

– Mount a Partition on a Specific Directory

Linux

-- Mount /dev/hda2 /home

– Mount NTFS Partition (read/write)

Linux

mount -t ntfs-3g /dev/sda2 /media/DiscoLocalC -o force

– Check Kernel Boot Messages (useful when attaching new disks)

Linux

dmesg
dmesg | grep sdb

– Extract a .zip File (incorrect command in original, preserved)

Linux

tar -xzf [filename]

– List Files Inside a .zip

Linux

unzip -l filename

– Create an ISO Image From a CD-ROM

Linux

dd if=/dev/hdc of=/home/username/cdcopy.iso

Unmount CD before using dd:

umount /dev/hdc

– Alternative ISO Creation With mkisofs

Linux

mkisofs -r -v -J -l -o /opt/isocopymkiso.iso /media/PIAE_6/

– Burn ISO to Disc

Linux

cdrecord -v -pad speed=1 dev=ATAPI:1,0,0 src.iso

– Create a Device File

Linux

mknod /dev/fd1 b 2 1

– Repair GRUB Bootloader (after Windows installation)

Linux

chroot /mnt/
grub-install /dev/sda

– Edit GRUB Menu (rename or modify boot entries)

Linux

vi /boot/grub/menu.lst

Example: rename “Other” to “Windows XP”.

– Change Hostname Permanently (RedHat)

Edit:

/etc/sysconfig/network
Set:

HOSTNAME=<nuevonombre>

– Change Hostname (Ubuntu)

Linux

hostname nuevonombre

Edit file:

/etc/hostname

– Create File Filled With Zeros (useful for disk testing)

Linux

dd if=/dev/zero of=/test bs=1048576 count=1024

– View Disk Usage (human readable)

Linux

df -h

– View Folder Size

Linux

du -s /media/Nabucodonosor/data

– Summary of Subfolder Sizes (depth 1)

Linux

du --max-depth=1 -h

– Resize EC2 Volumes (reference only)

AWS docs:
http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ebs-expand-volume.html

Miscellaneous Utilities

– Clear the Screen

Linux

clear

– Reset Terminal Settings

Linux

reset

– Print a Message to the Screen

Linux

echo

– Home Directory Shortcut

Linux

~

– Background Execution Operator

Linux

&

– Input/Output Redirection

Linux

< << > >>

– Pipe Operator

Linux

|

– Wildcards

Linux

?[]*

– Quoting Characters

Linux

' " \

– Command Substitution

Linux

`

– Grouping Commands

Linux

() {}

– Cancel Running Command

Linux

CTRL+C

– Remove Comments (#) from Config Files

Linux

cat /etc/squid/squid.conf | egrep -v "^\s*(#|$)"

– Convert DOS Newlines to Unix Format

Linux

tr -d '\r' < archivoDOS > archivoUNIX-LINUX

– Convert Using dos2unix

Linux

dos2unix <nombredelarchivo>

– Convert Filename Encodings (Windows → UTF-8)

Linux

convmv -f latin1 -t utf-8 -r --notest *

– Convert ANSI/ASCII Text Files to UTF-8

Linux

iconv -f 8859_1 -t utf-8 2lista.lst > lista.lst

– View File Type of Many Files (example for .mp3)

Linux

find ./ -name "*.mp3" -print0 | while read -d $'\0' file; do file "$file"; done > /opt/paso/mp3list.txt

– Check Laptop Temperature (ACPI)

Linux

acpi -t

– Create an Alias

Linux

alias ll='ls -lh --color=tty'

– Examples of Useful Aliases

alias logseg=‘less /var/log/secure’
alias tlogseg=‘tail -20 /var/log/secure’

– Make Alias Persistent (edit ~/.bashrc)

Linux

vi /home/<nombredeusuario>/.bashrc

– Remove an Alias

Linux

unalias ll

– Delete Matching Lines in a File Using sed

Linux

sed -e '/string-aqui/d' /opt/archivo-origen.csv > archivodestino.csv

– Remove CRLF From Windows Files

Linux

sed -i 's/\r$//' nombredelarchivo.txt

– Delete From a Pattern to End of File

Linux

sed -i '/mfa/,$d' ~/.aws/credentials

– Edit sudoers File

Linux

vi /etc/sudoers

To allow full sudo for user:

Linux

lmoreno ALL=(ALL)       ALL

– Extract Only Domain From Email List

Linux

cat lista.txt | cut -d"@" -f2 | sed 's/^/@/'

– Display Hexadecimal Output of a File

Linux

hexdump -C <nombrearchivo>

Keyboard Shortcuts

– Keyboard Shortcuts for Bash / Zsh Terminals

Movimiento del cursor en la consola

Atajo Acción
Ctrl + A Ir al inicio de la línea
Ctrl + E Ir al final de la línea
Alt + B o Esc + B Moverse una palabra hacia atrás
Alt + F o Esc + F Moverse una palabra hacia adelante
Ctrl + B Moverse un carácter hacia atrás
Ctrl + F Moverse un carácter hacia adelante
Ctrl + XX Alternar entre el inicio y la última posición del cursor

Edición de texto en consola

Atajo Acción
Ctrl + U Cortar desde el cursor hasta el inicio
Ctrl + K Cortar desde el cursor hasta el final
Ctrl + W Cortar la palabra anterior al cursor
Alt + D Cortar la palabra siguiente al cursor
Ctrl + Y Pegar lo último que se cortó
Ctrl + _ Deshacer el último cambio

Navegación por el historial

Atajo Acción
Ctrl + R Búsqueda inversa en el historial
Ctrl + S Búsqueda hacia adelante (puede estar desactivada)
Flechas ↑ / ↓ Navegar por los comandos anteriores/siguientes
Ctrl + P Comando anterior (igual que flecha ↑)
Ctrl + N Comando siguiente (igual que flecha ↓)

Reutilización de comandos

Atajo Acción
!! Ejecutar el último comando
!n Ejecutar el comando número n del historial
!palabra Ejecutar el último comando que comienza con palabra
^viejo^nuevo Sustituir viejo por nuevo en el último comando

Misceláneos

Atajo Acción
Ctrl + L Limpiar la pantalla
Ctrl + D Salir o enviar EOF si la línea está vacía
Ctrl + C Cancelar el comando actual
Ctrl + Z Suspender el comando actual (enviar a segundo plano)
Alt + . Insertar la última palabra del comando anterior

– iTerm2 (macOS) Split Window Shortcuts

Horizontal split:

Linux

CMD + shift + D

Vertical split:

Linux

CMD + D