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
- 01 - General Commands
- 02 - File Viewing, Search & Text Processing
- 03 - File & Directory Management
- 04 - Users, Groups & Permissions
- 05 - Networking & IP Configuration
- 06 - SSH, SCP & Remote Access
- 07 - Processes & System Monitoring
- 08 - Package Management (RPM, YUM, DPKG, APT)
- 09 - Firewall / IPTables
- 10 - VNC, X11 & GUI Tools
- 11 - Crontab & Automation
- 12 - Disk, Devices & System Boot
- 13 - Miscellaneous Utilities
- 14 - Keyboard Shortcuts
General commands
– Requesting Help for Any Command
man <comando>
Example:
man grep
– Disk Partitioning
– Create, View, Delete Partitions
fdisk /dev/hda
– Create a Partition on the Primary Hard Drive
mkfs -t ext2 -c /dev/hda1
-tspecifies the filesystem type (ext2 in this case).-cchecks 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
clear
– Reset Terminal to Default Values
reset
– Show System Users Information
finger
– Show Users Currently Logged In
who
– Display Logged‑in Users and Their Sessions/Tasks
w
– Show Current Username
whoami
– Show Numeric IDs and Groups for Current User
id
– Show Current Date and Time
date
– Show Calendar for Current Month
cal
– View File Contents
cat
– Exit the Current Shell
exit
– Print Output to the Screen
echo
– Show Current Shell
echo $SHELL
– Shell Variable
$
– Home Directory Shortcut
Used for example with cd ~ which takes you to /home/<user>.
~
– 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.
&
– Input/Output Redirection
< << > >>
– Pipe to Chain Commands
Example:
cat file.txt | grep name
|
– Shell Wildcards
Example:
ls *.txt
?[]*
– Quoting and Metacharacters
' " \
– Command Substitution
`
– Grouping Commands
() {}
– Cancel a Running Command
Press and hold CTRL, then press C.
CTRL+C
File Viewing, Search & Text Processing
– View the Last 10 Lines of a Text File
tail <nombrearchivo>
– View the Last 30 Lines
tail -30 <nombrearchivo>
– Follow File Changes in Real Time (useful for logs)
tail -f <nombredelarchivo>
– View the First 10 Lines
head <nombrearchivo>
– View the First 30 Lines
head -30 <nombrearchivo>
– List the Most Recently Modified File in a Directory
ls -Art | tail -n 1
– Show Only Directories
ls -l|grep ^d
ls -p |grep /
ls -l | egrep '^d'
– Search for Text in Files (basic examples)
grep "spc_eee1.gif" *
grep -r -i "textoAbuscar" *.*
-r = recursive
-i = ignore case
– Search for Text and Show Line Numbers
grep -nr textoabuscar
– Use awk to Extract Columns (example: extract IPs from Apache logs)
awk '{print $1}' access-hackvolution.log
– Remove Duplicate Results Using sort and uniq
awk '{print $1}' access-hackvolution.log |sort |uniq
– Count Repeated Values and Sort by Frequency
awk '{print $1}' access-hackvolution.log |sort |uniq -c |sort -rn
– Search Inside .sh Scripts for the Word “user”
find / -name '*.sh' 2>/dev/null | xargs grep -i 'user'
– Search for Script Files (.ksh, .sh, .pl, .py, .zsh, .bash, .bsh, .sql)
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)
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
grep --include=\*.{ksh,sh,pl,py,zsh,bash,bsh,sql} -rnw '/' -e "password"
– Alternative Text Search Examples
grep 'user' $(find / -name '*.sh')
find / -name '*.sh' -exec grep 'texto' {} \;
– Remove Commented Lines from squid.conf (remove lines starting with # and empty lines)
cat /etc/squid/squid.conf | egrep -v "^\s*(#|$)"
– Remove First and Last Character of Each Line
cat lista.txt | cut -c 2- | sed 's/.$//' > clean-lista.txt
– Extract Valid IPs Using Regex
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”
find ./ -name *.htm |xargs grep "wants to contact you"
– Exclude a Directory While Searching
find / \( ! -name tmp -o -prune \) -name "file.rar" -print 2>/dev/null
– Search Using locate (requires index)
locate <nombredelarchivoabuscar>
– Remove Comments and Clean Configuration Files Using sed
sed -e '/string-aqui/d' /opt/archivo-origen.csv > archivodestino.csv
– Remove Windows CR Line Endings
sed -i 's/\r$//' nombredelarchivo.txt
– Delete Everything From a Keyword to End of File
sed -i '/mfa/,$d' ~/.aws/credentials
– Convert DOS Line Endings to Unix Using dos2unix
dos2unix <nombredelarchivo>
– Hexadecimal View of Files
hexdump -C <nombrearchivo>
– Sort IPs Numerically
sort -t . -k 1,1n -k 2,2n -k 3,3n -k 4,4n ips.txt
– Quick Version-Based Sort
sort -V ips.txt
– Extract Public IP
dig +short myip.opendns.com @resolver1.opendns.com
– Convert File Names from Windows Encoding to UTF‑8
convmv -f latin1 -t utf-8 -r --notest *
– Convert ANSI/ASCII Files to UTF‑8
iconv -f 8859_1 -t utf-8 2lista.lst > lista.lst
File & Directory Management
– Clear the Screen
clear
– Exit the Current Shell
exit
– Print Text on Screen
echo
– List Files in Long Format
ls -l
– Show Number of Files in a Directory
echo *.* | wc
– Show Number of Directories in a Folder
echo */ | wc
– Delete All Files with Extension *.xxx Across the Entire Disk
find / -type f -name "*.xxx" -exec rm {} \;
– Delete Directories (Be Careful With -rf)
rm -rf foldername
– Remove Empty Directories
rmdir <nombredelfolder>
– Delete All Files Except One Folder (example: keep “wiki”)
shopt -s extglob
rm -rf -v !("wiki")
– Copy Entire CD-ROM Contents to a Folder
cp -av /mnt/cdrom /install
– Copy Files Incrementally Using rsync
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
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
find . -type f -name "*.txt" -exec mv {} /opt/movehere/ \;
– Move Files One by One Using find
Example of workaround for “Argument list too long”:
-bash: /bin/mv: Argument list too long
for i in `find . -name ap\*`
do
mv $i ..
done
– Change File Extensions in Bulk
for f in *.htm; do mv $f `basename $f .htm`.html; done;
– Concatenate Files into One
cat *.csv >> archivoconcatenado.csv
– Create Backup of a Folder in Compressed Form
tar -czvf myarchive.tgz mydirectory/
– Compress a Folder into a .tar.gz File
tar -zcvf archive_name.tar.gz directory_to_compress
-z gzip
-c create
-v verbose
-f file
– Compress Entire Folder in zip Format
zip -qq -R archivozip directorio
– Compress All .html Files into a Zip
find . -name "*.html" | xargs zip HTMLs-Nessus
– Extract a .zip File
unzip nombre-archivo
– Extract a tar.bz2 File
tar -xvjf file.tar.bz2
– Extract a .tar File
tar -xvf foo.tar
– Extract a .gz File
gunzip archivo.gz
– Extract Contents of a .zip Without Output
unzip -qq archive -d ruta-directorio
– Extract rar Files (install unrar first)
yum install unrar
Then:
unrar x archivo.rar
– Split a File Into Smaller Parts (by size example)
split -b 200M nombredearchivo
– Sort Folder Sizes from Smallest to Largest
du -hs * | sort -h
– Show Largest Files in Current Directory (top 10)
du -hs * | sort -rh | head -10
– Show Largest Files Including Subdirectories (top 10)
du -Sh | sort -rh | head -10
– Show Used Disk Space
df -h
– Show Size of a Specific Folder
du -s /media/Nabucodonosor/data
– Show Disk Usage Summary of Subfolders
du --max-depth=1 -h
– Create a File Filled with Zeros
dd if=/dev/zero of=/test bs=1048576 count=1024
Users, Groups & Permissions
– Add a User
useradd <nombreusuario>
– Set User Password
passwd <nombreusuario>
Example:
useradd -c "Luis Moreno" morenol
passwd mi_password
– Add User With Custom Home and Shell
/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
/usr/sbin/useradd -d /home/lmoreno -s /bin/bash -c "Luis Moreno" lmoreno && mkdir /home/lmoreno && chown lmoreno /home/lmoreno
– Delete a User
deluser <nombredeusuario>
Example:
deluser -r dsantos
-r removes home directory and mailbox
– List System Users
cat /etc/passwd
– List System Groups
cat /etc/group
– Add a Group
groupadd <nombredelgrupo>
– Lock/Disable a User (manual method)
agregar el signo "+" delante de la línea del usuario en el archivo /etc/passwd
– Lock User Using passwd
passwd -l <nombreUsuario>
– Add User to Supplementary Group
usermod -a -G web luis
– Change User’s Primary Group
usermod -g www luis
– Change File Permissions (symbolic)
chmod u+wr,g+wr,o-r
– Change File Permissions (numeric)
chmod 664
read = 4
write = 2
execute = 1
– Make File Executable for Everyone
chmod 111 <nombreDelArchivo>
– Give Root Full Permissions on a File
chmod 700 <nombreDelArchivo>
– Give Full Permissions to Everyone (dangerous)
chmod 777 <nombreDelArchivo>
– Apply rwx Permissions Recursively on Folder and Subfolders
chmod 777 -R archivos/*
– Clone Permissions From One File to Another
chown --reference=otherfile thisfile
– Create a Device File
mknod /dev/fd1 b 2 1
– Change File Owner
chown luis /carpeta/archivo
– Change File Owner and Group
chown luis.grupo /carpeta/archivo
– Change Group Ownership Only
chgrp grupo /carpeta/archivo
– Password Policy Configuration: Edit /etc/login.defs
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)
cat /etc/sysconfig/network-scripts/ifcfg-eth0
– Show Network Configuration (Debian/Ubuntu)
cat /etc/sysconfig/network
– Example Network Configuration (CentOS)
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
systemctl restart network
– View dmesg for Newly Connected Hardware
dmesg
dmesg |grep sdb
– Mount USB or External Disk
mount /dev/sdb1 /media/usb
– Mount NTFS Partition
mount -t ntfs-3g /dev/sda2 /media/DiscoLocalC -o force
– Change System Timezone (Ubuntu)
dpkg-reconfigure tzdata
– TCP Traceroute to a Specific Port
traceroute -T -p 80 72.14.213.104
– Network Configuration in Ubuntu (interfaces file)
/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+)
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
sudo netplan apply
– Configure DHCP with Netplan
sudo vim /etc/netplan/50-cloud-init.yaml
network: ethernets: enp0s3: addresses: [] dhcp4: true version: 2
– Restart Networking (Ubuntu)
sudo ip addr flush eth0 && sudo systemctl restart networking.service
– Bring Network Interface Up
ip link set eth0 up
– Set IP Address
ip addr add 10.23.34.46/29 dev eth0
– Delete IP Address
ip addr del 10.23.34.46/29 dev eth0
– Set Default Route
ip route add default via 47.23.34.41 dev eth0
– View Routes (Route Table)
route -n
– View Routing Table (Alternative)
netstat -r
– Add Static Route
route add -net 200.66.81.64 netmask 255.255.255.192 dev eth0
– Bring Interface Down
ifdown eth0
– Bring Interface Up
ifup eth0
– Change MAC Address (MAC Spoofing)
ifdown eth0
ifconfig eth0 hw ether 00:01:02:03:04:05
ifup eth0
– Configure DNS Temporarily
echo "nameserver 192.168.16.254" >> /etc/resolv.conf
– Edit resolv.conf Manually
vi /etc/resolv.conf
– Flush DNS Cache
/etc/rc.d/init.d/nscd restart
– ARP: Add ARP Entry
arp -s 200.66.81.110 00:04:23:DC:D9:AC
– List ARP Table
arp -n
– ARP Neighbors
arp -an
ip neigh
sudo arp-scan -l
– Change Hostname (RedHat)
hostname nuevonombre
– Edit Hostname Permanently
Edit:
/etc/sysconfig/network
HOSTNAME=
– Change Hostname in Ubuntu
hostname nuevonombre
Edit:
/etc/hostname
– Mount Windows Shared Folder (CIFS)
mount -t cifs //servidor/carpetawindows -o username=luis.moreno,password=Misuperpassword /mnt/windows
– Older Systems (smbfs)
mount -t smbfs -o username=luis.moreno,password=Misuperpassword //servidor/carpetawindows /mnt/windows
– List Open Network Files
lsof -i -n
– Detect Link Speed (Ethernet)
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:
Subsystem sftp /usr/libexec/openssh/sftp-server
– Copy a Local File to a Remote Host
scp archivo-origen usuario@host:directorio/archivo-remoto
– Copy a File From a Remote Host to Local
scp usuario@host:directorio/archivo-origen archivo-destino
– SCP Using a Non‑Default Port (use -P)
scp -P 2222 usuario@host:/directorio/archivo-origen archivo-destino
– Copy an Entire Folder to a Remote Host (recursive)
scp -r directorio-origen usuario@host:directorio-destino
– Copy a Remote Folder to Local (with private key)
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
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:
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
cd /etc/rc.d/init.d
Then:
sh sshd stop
Or:
service sshd stop
– Kill SSH Sessions (Find PIDs)
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:
ClientAliveInterval 600
ClientAliveCountMax 3
This disconnects idle sessions after ~30 minutes.
– Change Default SSH Port (22 → custom)
Edit:
vi /etc/ssh/sshd_config
Locate:
#Port 22
Change to your custom port, e.g.:
Port 2995
Reload service:
service sshd reload
– If SSH Is Managed by xinetd
Edit:
vi /etc/xinetd.d/sshd
Change:
port = 22
Restart service afterward.
– SSH Through a Proxy Using corkscrew
Download corkscrew:
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:
vim $HOME/.ssh/config
Add:
ProxyCommand $HOME/.ssh/corkscrew ip-del-proxy puerto %h %p
– Keep SSH Sessions Alive (Client Side)
Edit:
vim .ssh/config
Add:
ServerAliveInterval 60
ServerAliveCountMax 10
Client will try for ~10 minutes before disconnecting.
– Decompress .gz Files
gunzip /usr/share/wordlists/rockyou.txt.gz
– Decompress .7z Files
7za e hashcat-2.00.7z -ohashcat2
– Edit SSH Config File
vim $HOME/.ssh/config
– Send a Message to All Users (wall)
wall "Nada mas jugando"
– Find Your Current Terminal
tty
– Send a Message Directly to Another Terminal
echo "message" > /dev/pts/<number>
– Disable wall Message Reception
mesg n
– Send Email From Command Line
echo "20 minutos para la junta" | /bin/mail -s "Meeting" micorreo@miservidor.com
– Change SSH User Temporarily
su -s /bin/bash - apache
Processes & System Monitoring
– Show All Processes (including other users)
ps -al
– Show Processes With Their Process Tree and Associated Crontab
ps -auxfw
– Show Processes Using the Most CPU Resources
top
Press q to exit the top interface.
– View Open Files and Network Connections
lsof -i -n
To view files opened by a specific PID:
lsof -p 8295
– View System CPU Usage for a Specific Core
grep 'cpu1 ' /proc/stat | awk '{usage=($2+$4)*100/($2+$4+$5)} END {print usage "%"}'
– CPU Usage for All Cores
grep 'cpu ' /proc/stat | awk '{usage=($2+$4)*100/($2+$4+$5)} END {print usage "%"}'
– CPU1, CPU2, CPU3 Individually
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)
last -f /var/log/btmp
– Secure btmp permissions (only root should read)
chown root:utmp /var/log/btmp && chmod 600 /var/log/btmp
– Check Which MTA (Mail Transfer Agent) Is Active
alternatives --config mta
– View History of Commands
history
– Show Commands 125 to 130 From History
fc -l 125 130
– View Command History With Timestamp
fc -li 100
– Set Date/Time Format for History
HISTTIMEFORMAT="%Y-%m-%d %T "
– Execute a Command From History (number n)
!n
– Clear Command History
history -c
Or manually edit:
~/.bash_history
– Send a Running Process to Background
ctrl+z
– Resume Background Process
bg
– Bring Background Job to Foreground
fg
– View Running Jobs
jobs
Package Management (RPM, YUM, DPKG, APT)
– Install an .rpm Package
rpm -ivh <nombre del archivo .rpm>
i = install
v = verbose
h = human-readable progress
– Example: Install Nessus
rpm -ivh nessus.rpm
– Check if a Package Is Installed
rpm -q "nombredelpaquete"
– List All Installed RPM Packages
rpm -qa
– Remove Packages (force if dependencies block uninstall)
rpm -e --nodeps php-pear-1.4.9-1.2
rpm -e php-5.1.6-1.2
– Find Which Package Provides a File
locate libdts.so.0
Then:
yum provides /etc/libdts.so.0
– Install a Package Using YUM
yum install <nombredelpaquete>
– Search for a Package With YUM
yum search <paquete>
– Get Detailed Info About a Package
yum info net-snmp-utils
– Remove Packages With YUM
yum remove <nombredelpaquete>
– Install a Package From a Specific Repository
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
wget http://dl.fedoraproject.org/pub/epel/epel-release-latest-7.noarch.rpm
rpm -ivh epel-release-latest-7.noarch.rpm
– Check Enabled Repositories
yum repolist
– Install Package From EPEL
yum --enablerepo=epel install zabbix
– Update the Entire System
yum update
– Install an Ubuntu/Debian Package (.deb)
dpkg -i nombredelarchivo.deb
If dependencies fail:
sudo apt-get install -f
Then run dpkg -i again.
– Example: Install TeamViewer
sudo dpkg -i teamviewer_linux.deb
When dependency errors appear, run:
sudo apt-get install -f
Then reinstall.
– Fix DPKG Overwrite Errors
sudo dpkg -i --force-overwrite <filename>
– Query Installed Packages in Ubuntu/Debian
yum list installed
(For rpm-based systems)
– Query Installed Packages With repoquery
repoquery -a --installed
– Install Packages on RedHat Using apt-rpm (legacy)
http://dag.wieers.com/rpm/FAQ.php#B
– Common Error With YUM Mirrors
[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
service iptables restart
– Block a Specific Host
iptables -I INPUT -s 192.168.16.8 -j DROP
– Allow SSH on Port 22 Only From a Specific IP Range
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
iptables -L
– Temporarily Allow an IP to Access FTP (port 21)
/sbin/iptables -I INPUT -s 200.52.66.116/32 -p tcp --dport 21 -j ACCEPT
– Remove the Rule After Testing
/sbin/iptables -t filter -D INPUT 1
– File With IPTables Custom Scripts
/etc/sysconfig/iptables
– View Open Ports Using netstat
netstat -pn -A inet
– View Listening Ports
netstat -lpn -A inet
– View All TCP Ports
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
lsof -iTCP -sTCP:LISTEN
– View All Open Ports (TCP/UDP)
lsof -i
– Scan Localhost Ports Using nmap
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
pgrep sendmail
– Advanced grep + perl for nmap OS detection (unchanged from original)
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
vncpasswd
– Edit VNC Server Configuration (RedHat/CentOS)
File to edit:
/etc/sysconfig/vncservers
– Enable VNC Server at Boot
chkconfig vncserver on
– Start VNC Server
service vncserver start
– Configure Advanced VNC Session (custom desktop)
Edit:
/home/username/.vnc/xstartup
– GUI Firewall Configuration Tool
system-config-securitylevel
– View or Change X11 Display Settings
Main configuration file:
/etc/X11/xorg.conf
– Launch GNOME Desktop Environment
yum groupinstall "gnome"
– Repair GRUB Bootloader (after Windows overwrites it)
chroot /mnt/
grub-install /dev/sda
– Edit GRUB Menu Entries (rename OS options)
vi /boot/grub/menu.lst
Edit names like:
- “Other” → “Windows XP”
- “Other” → “Windows Vista”
– Remove GNOME Keyring Password Prompt
Delete:
.gnome2/keyrings/default.keyring
– Install rdesktop (Remote Desktop Client for Windows)
yum install rdesktop
Usage example:
rdesktop -g 1024x768 windowssrv
– Hex Editor for Red Hat (GUI)
ghex
– View File in Hexadecimal (CLI)
hexdump -C <nombrearchivo>
– Change Display Resolution via X11 Config
Edit:
/etc/X11/xorg.conf
– Keyboard Shortcuts for iTerm2 Split Screen (macOS)
Horizontal split:
CMD + shift + D
Vertical split:
CMD + D
Crontab & Automation
– View Scheduled Cron Jobs
crontab -l
– Edit the Current User’s Crontab
crontab -e
– System Cron File (RedHat/CentOS)
Not recommended to edit directly, but located at:
`/var/spool/cron/root`
– System Cron File (Ubuntu/Debian)
/var/spool/cron/crontabs
– Cron Format Reference
* * * * * 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
split -b 200M nombredearchivo
– Fix dpkg Update Error (force overwrite)
sudo dpkg -i --force-overwrite <filename>
– Example Error Message
error processing /var/cache/apt/archives/python-apport_2.0.1-0ubuntu9_all.deb
Solution (example):
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)
fdisk /dev/hda
– Create a Filesystem on a Partition (ext2 example)
mkfs -t ext2 -c /dev/hda1
-t = filesystem type
-c = check for bad sectors
– Show Disk List / Partitions
fdisk -l
– Mount a Floppy Disk (MS-DOS format)
mount -t msdos /dev/fd0 /floppy
– Mount CD-ROM
mount cd-rom
mount -t iso9660 /dev/cdrom /media/cdrom/
– Mount USB or External Disk
mount /dev/sdb1 /media/usb
– Mount a Partition on a Specific Directory
-- Mount /dev/hda2 /home
– Mount NTFS Partition (read/write)
mount -t ntfs-3g /dev/sda2 /media/DiscoLocalC -o force
– Check Kernel Boot Messages (useful when attaching new disks)
dmesg
dmesg | grep sdb
– Extract a .zip File (incorrect command in original, preserved)
tar -xzf [filename]
– List Files Inside a .zip
unzip -l filename
– Create an ISO Image From a CD-ROM
dd if=/dev/hdc of=/home/username/cdcopy.iso
Unmount CD before using dd:
umount /dev/hdc
– Alternative ISO Creation With mkisofs
mkisofs -r -v -J -l -o /opt/isocopymkiso.iso /media/PIAE_6/
– Burn ISO to Disc
cdrecord -v -pad speed=1 dev=ATAPI:1,0,0 src.iso
– Create a Device File
mknod /dev/fd1 b 2 1
– Repair GRUB Bootloader (after Windows installation)
chroot /mnt/
grub-install /dev/sda
– Edit GRUB Menu (rename or modify boot entries)
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)
hostname nuevonombre
Edit file:
/etc/hostname
– Create File Filled With Zeros (useful for disk testing)
dd if=/dev/zero of=/test bs=1048576 count=1024
– View Disk Usage (human readable)
df -h
– View Folder Size
du -s /media/Nabucodonosor/data
– Summary of Subfolder Sizes (depth 1)
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
clear
– Reset Terminal Settings
reset
– Print a Message to the Screen
echo
– Home Directory Shortcut
~
– Background Execution Operator
&
– Input/Output Redirection
< << > >>
– Pipe Operator
|
– Wildcards
?[]*
– Quoting Characters
' " \
– Command Substitution
`
– Grouping Commands
() {}
– Cancel Running Command
CTRL+C
– Remove Comments (#) from Config Files
cat /etc/squid/squid.conf | egrep -v "^\s*(#|$)"
– Convert DOS Newlines to Unix Format
tr -d '\r' < archivoDOS > archivoUNIX-LINUX
– Convert Using dos2unix
dos2unix <nombredelarchivo>
– Convert Filename Encodings (Windows → UTF-8)
convmv -f latin1 -t utf-8 -r --notest *
– Convert ANSI/ASCII Text Files to UTF-8
iconv -f 8859_1 -t utf-8 2lista.lst > lista.lst
– View File Type of Many Files (example for .mp3)
find ./ -name "*.mp3" -print0 | while read -d $'\0' file; do file "$file"; done > /opt/paso/mp3list.txt
– Check Laptop Temperature (ACPI)
acpi -t
– Create an Alias
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)
vi /home/<nombredeusuario>/.bashrc
– Remove an Alias
unalias ll
– Delete Matching Lines in a File Using sed
sed -e '/string-aqui/d' /opt/archivo-origen.csv > archivodestino.csv
– Remove CRLF From Windows Files
sed -i 's/\r$//' nombredelarchivo.txt
– Delete From a Pattern to End of File
sed -i '/mfa/,$d' ~/.aws/credentials
– Edit sudoers File
vi /etc/sudoers
To allow full sudo for user:
lmoreno ALL=(ALL) ALL
– Extract Only Domain From Email List
cat lista.txt | cut -d"@" -f2 | sed 's/^/@/'
– Display Hexadecimal Output of a File
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:
CMD + shift + D
Vertical split:
CMD + D