Linux Potpourri

Purpose:

The purpose of this article is to display a set of commonly used Linux Commands.

"LAMP" is an acronym that stands for Linux, Apache, MySQL, and PHP/Perl/Python. It refers to a popular and widely used stack of open-source software components that are often used together to create and deploy dynamic websites and web applications. Each component of the LAMP stack serves a specific purpose:

  1. Linux: This is the operating system on which the LAMP stack runs. Linux is chosen for its stability, security, and open-source nature. It provides the foundation for the other components to operate.
  2. Apache: Apache HTTP Server (commonly referred to as just "Apache") is a web server software that's used to serve web pages to users' browsers. It handles incoming HTTP requests and serves the appropriate web content, such as HTML files, images, and other assets.
  3. MySQL: MySQL is a popular open-source relational database management system (RDBMS). It's used to store and manage the data for web applications. MySQL is known for its performance, reliability, and ease of use.
  4. PHP/Perl/Python: This component refers to the scripting languages that are used to develop the dynamic web content and interact with the database. Typically, PHP (Hypertext Preprocessor) is the most commonly used language in the LAMP stack, but alternatives like Perl and Python can also be used.

Together, the LAMP stack provides a complete environment for developing, deploying, and hosting web applications. It's important to note that while the term "LAMP" originally stood for Linux, Apache, MySQL, and PHP/Perl/Python, variations have emerged over time, such as "LEMP" (replacing Apache with Nginx as the web server), and different programming languages for the dynamic content.

Additionally, technologies and trends have evolved since the conception of the LAMP stack, and developers now have a wider range of options and alternatives for building web applications, including different web servers (like Nginx), alternative databases, and various programming languages and frameworks.

Install LAMP - Linux, Apache, MySQL, PHP

Services

Get all running services
systemctl --type=service --state=running

Sample Output:

UNIT LOAD ACTIVE SUB DESCRIPTION
accounts-daemon.service loaded active running Accounts Service
atd.service loaded active running Deferred execution scheduler
cron.service loaded active running Regular background program processing daemon
LOAD = Reflects whether the unit definition was properly loaded.
ACTIVE = The high-level unit activation state, i.e. generalization of SUB.
SUB = The low-level unit activation state, values depend on unit type

Alternate view all services
sudo service --status-all
Restart using systemctl
sudo systemctl restart apache2
Stop Apache2 service options are {start|stop|graceful-stop|restart|reload|force-reload}
sudo service apache2 graceful-stop
sudo service apache2 stop

Apache CLI Commands

Update the package manager cache
sudo apt update
Install Apache
sudo apt install apache2

You can do a spot check right away to verify that everything went as planned by visiting your server’s public IP address in your web browser (view the note under the next heading to find out what your public IP address is if you do not have this information already):  http://{your IP Address}

The default Ubuntu 2X.04 Apache web page is there for informational and testing purposes.

Disable default Apache Site
sudo a2dissite 000-default.conf
Enable new Site
sudo a2ensite your_domain.conf

UFW CLI Commands (Uncomplicated Firewall for Ubuntu)

View Uncomplicated Firewall (UFW) Application Profiles
sudo ufw app list
Allow Apache on Port 80
sudo ufw allow in "Apache"
Get UFW status
sudo ufw status
Get your servers public IP
ip addr show ens3 | grep inet | awk '{ print $2; }' | sed 's/\/.*$//'
Alternative method using Curl
curl http://icanhazip.com

MySQL CLI Commands

Install MySQL
sudo apt install mysql-server
Open mysql
sudo mysql
Alter the root user's auth method
ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'password';
Secure MySQL install
sudo mysql_secure_installation

More MySql commands can be found Here on MySQL Potpourri Page

PHP CLI Commands

Install PHP
sudo apt install php libapache2-mod-php php-mysql
Intall PHP Extensions
sudo apt-get install php8.x libapache2-mod-php8.x php8.x-common php8.x-curl php8.x-mbstring php8.x-xmlrpc php8.x-mysql php8.x-gd php8.x-xml php8.x-intl php8.x-ldap php8.x-imagick php8.x-json php8.x-cli
Check PHP version
php -v
Remove old versions of PHP if needed
sudo apt-get purge php7.*

Testing PHP

Now that you have a custom location to host your website’s files and folders, create a PHP test script to confirm that Apache is able to handle and process requests for PHP files.

Create a new file named info.php inside your custom web root folder:

Use Nano editor to create a new info.php file in the default location /var/www/html/info.php
nano /var/www/html/info.php

In the Nano Editor type:
<?php
phpinfo();

Ctrl + O = Will write out the file

Ctrl + X = Will exit Nano

Navigate to http://server_domain_or_IP/info.php

To view a info about PHP to verify it is working properly.

Example image below:

PHP small

System Information

Show operating system information such as distribution name and version
cat /etc/os-release
Display Linux system information
uname -a
Display kernel release information
uname -r
Show how long the system has been running + load
uptime
Show system reboot history
last reboot
Show system host name
hostname
Display all local IP addresses of the host.
hostname -I
Show the current date and time
date
Show this month's calendar
cal
Display who is online
w
Who you are logged in as
whoami

Hardware Information

Display messages in kernel ring buffer
dmesg
Display CPU information
cat /proc/cpuinfo
Display memory information
cat /proc/meminfo
Display free and used memory ( -h for human readable, -m for MB, -g for GB.)
free -h
Display PCI devices
lspci -tv
Display USB devices
lsusb -tv
Display DMI/SMBIOS (hardware info) from the BIOS
dmidecode
Show info about disk sda
hdparm -tT /dev/sda
Test for unreadable blocks on disk sda
badblocks -s /dev/sda

PERFORMANCE MONITORING AND STATISTICS

Display and manage the top processes
top
Interactive process viewer (top alternative)
htop
Display processor related statistics
mpstat 1
Display virtual memory statistics
vmstat 1
Display I/O statistics
iostat 1
Display the last 100 syslog messages (Use /var/log/syslog for Debian based systems.)
tail -100 /var/log/messages
Capture and display all packets on interface eth0
tcpdump -i eth0
Monitor all traffic on port 80 ( HTTP )
tcpdump -i eth0 'port 80'
List all open files on the system
lsof
List files opened by user
lsof -u user
Display free and used memory ( -h for human readable, -m for MB, -g for GB.)
free -h
Execute "df -h", showing periodic updates
watch df -h

USER INFORMATION AND MANAGEMENT

Display the user and group ids of your current user.
id
Display the last users who have logged onto the system.
last
Show who is logged into the system.
who
Show who is logged in and what they are doing.
w
Create a group named "test".
groupadd test
Create an account named john, with a comment of "John Smith" and create the user's home directory.
useradd -c "John Smith" -m john
Delete the john account.
userdel john
Add the john account to the sales group
usermod -aG sales john

FILE AND DIRECTORY COMMANDS

List all files in a long listing (detailed) format
ls -al
Display the present working directory
pwd
Create a directory
mkdir directoryname
Remove (delete) file - Single file
rm file
Remove the directory and its contents recursively
rm -r directoryname
Force removal of file without prompting for confirmation
rm -f directoryname
Forcefully remove directory and all files within recursively
rm -rf directoryname
Copy file1 to file2
cp file1 file2
Copy source_directory recursively to destination. If destination exists, copy source_directory into destination, otherwise create destination with the contents of source_directory.
cp -r source_directory destination
Rename or move file1 to file2. If file2 is an existing directory, move file1 into directory file2
mv file1 file2
Create symbolic link to linkname
ln -s /path/to/file linkname
Create an empty file or update the access and modification times of file.
touch file
View the contents of file
cat file
Browse through a text file
less file
Display the first 10 lines of file
head file
Display the last 10 lines of file
tail file
Display the last 10 lines of file and "follow" the file as it grows.
tail -f file

PROCESS MANAGEMENT

Display your currently running processes
ps
Display all the currently running processes on the system.
ps -ef
Display process information for processname
ps -ef | grep processname
Display and manage the top processes
top
Interactive process viewer (top alternative)
htop
Kill process with process ID of pid
kill pid
Kill all processes named processname
killall processname
Start program in the background
program &
Display stopped or background jobs
bg
Brings the most recent background job to foreground
fg
Brings job n to the foreground
fg n

There are several common signals that can be used with the "kill" command, each serving a specific purpose. Some of the more commonly used signals include −

  • TERM (15) − This is the default signal used by the "kill" command. It requests that the process terminate gracefully, allowing it to clean up any resources or save any data before exiting.
  • HUP (1) − This signal is used to hang up or disconnect a process. It's often used to restart a process or to refresh its configuration.
  • INT (2) − This signal is used to interrupt a process, and is similar to pressing the "CTRL+C" keys on the keyboard.
  • KILL (9) − This signal is used to immediately terminate a process, without allowing it to clean up or save any data. This signal cannot be ignored by the process.
  • STOP (19) − This signal is used to stop a process temporarily, allowing it to be resumed later.

FILE PERMISSIONS

        PERMISSION      EXAMPLE
         U   G   W
        rwx rwx rwx     chmod 777 filename
        rwx rwx r-x     chmod 775 filename
        rwx r-x r-x     chmod 755 filename
        rw- rw- r--     chmod 664 filename
        rw- r-- r--     chmod 644 filename
# NOTE: Use 777 sparingly!
        LEGEND
        U = User
        G = Group
        W = World
        r = Read
        w = write
        x = execute
        - = no access
Linuxfilepermissions

NETWORKING

Display all network interfaces and IP address
ip addr
Display eth0 address and details
ip addr show dev eth0
Query or control network driver and hardware settings
ethtool eth0
Send ICMP echo request to host
ping host
Display whois information for domain
whois domain
Display DNS information for domain
dig domain
Reverse lookup of IP_ADDRESS
dig -x IP_ADDRESS
Display DNS IP address for domain
host domain
Display the network address of the host name.
hostname -i
Display all local IP addresses of the host.
hostname -I
Download a file at http://domain.com/file
wget http://domain.com/file
Display listening tcp and udp ports and corresponding programs
netstat -nutlp

ARCHIVES (TAR FILES)

Create tar named archive.tar containing directory.
tar cf archive.tar directory
Extract the contents from archive.tar.
tar xf archive.tar
Create a gzip compressed tar file name archive.tar.gz.
tar czf archive.tar.gz directory
Extract a gzip compressed tar file.
tar xzf archive.tar.gz
Create a tar file with bzip2 compression
tar cjf archive.tar.bz2 directory
Extract a bzip2 compressed tar file.
tar xjf archive.tar.bz2

INSTALLING PACKAGES

Search for a package by keyword.
yum search keyword
Install package.
yum install package
Display description and summary information about package.
yum info package
Install package from local file named package.rpm
rpm -i package.rpm
Remove/uninstall package.
yum remove package
Install software from source code
tar zxvf sourcecode.tar.gz
cd sourcecode
./configure
make
make install

SEARCH

Search for pattern in file
grep pattern file
Search recursively for pattern in directory
grep -r pattern directory
Find files and directories by name
locate name
Find files in /home/john that start with "prefix".
find /home/john -name 'prefix*'
Find files larger than 100MB in /home
find /home -size +100M

SSH LOGINS

Connect to host as your local username.
ssh host
Connect to host as user
ssh user@host
Connect to host using port
ssh -p port user@host

FILE TRANSFERS

Secure copy file.txt to the /tmp folder on server
scp file.txt server:/tmp
Copy *.html files from server to the local /tmp folder.
scp server:/var/www/*.html /tmp
Copy all files and directories recursively from server to the current system's /tmp folder.
scp -r server:/var/www /tmp
Synchronize /home to /backups/home
rsync -a /home /backups/
Synchronize files/directories between the local and remote system with compression enabled
rsync -avz /home server:/backups/

DISK USAGE

Show free and used space on mounted filesystems
df -h
Show free and used inodes on mounted filesystems
df -i
Display disks partitions sizes and types
fdisk -l
Display disk usage for all files and directories in human readable format
du -ah
Display total disk usage off the current directory
du -sh

DIRECTORY NAVIGATION

To go up one level of the directory tree. (Change into the parent directory.)
cd ..
Go to the $HOME directory
cd ~
Change to the /etc directory
cd /etc

SECURITY

Change the current user's password.
passwd
Switch to the root account with root's environment. (Login shell.)
sudo -i
Execute your current shell as root. (Non-login shell.)
sudo -s
List sudo privileges for the current user.
sudo -l
Edit the sudoers configuration file
visudo
Display the current SELinux mode.
getenforce
Display SELinux details such as the current SELinux mode, the configured mode, and the loaded policy.
sestatus
Change the current SELinux mode to Permissive. (Does not survive a reboot.)
setenforce 0
Change the current SELinux mode to Enforcing. (Does not survive a reboot.)
setenforce 1
Set the SELinux mode to enforcing on boot by using this setting in the /etc/selinux/config file.
SELINUX=enforcing
Set the SELinux mode to permissive on boot by using this setting in the /etc/selinux/config file.
SELINUX=permissive
Set the SELinux mode to disabled on boot by using this setting in the /etc/selinux/config file.
SELINUX=disabled

LOGGING AND AUDITING

Display messages in kernel ring buffer.
dmesg
Display logs stored in the systemd journal.
journalctl
Display logs for a specific unit (service).
journalctl -u servicename