Miscellaneous Linux commands

by Cover Tower - Updated June 28, 2021

Below you can find a list with miscellaneous Linux commands that are not as frequently used as the essential Linux commands listed in this article, but are still very useful in various situations. All commands will work on the latest version of Debian, the majority of them will work on Debian-based distributions such as Ubuntu, Mint, Knoppix, PureOS, Kali, Tails, etc., and some of them will work on all distributions. These commands can be run in a terminal, on a laptop or desktop, but also on a remote VPS or dedicated server, while connected to it via SSH. When you run them, replace the strings in red with your own values.

➤ Show details about the current Linux kernel
cat /proc/version

The output of this command will show the exact version of the kernel, the name and version of the compiler used, the date of compilation, etc.:

Linux version 4.19.0-14-amd64 (debian-kernel@lists.debian.org) (gcc version 8.3.0 (Debian 8.3.0-6)) #1 SMP Debian 4.19.171-2 (2021-01-30)
➤ Kill a process directly

First find the PID of the process that you want to kill by using the top command and looking at the PID column, on the row of the process. If you know the name of the process, you can list its PID by running pgrep processname. Let’s say that the process has the PID 9524. To kill it run:

kill 9524
➤ Kill a process telling it to finish what it is doing, then exit

First find the PID of the process that you want to kill by using the top command, or by running pgrep processname. If the process has the PID for example 11526, to tell the process to finish what it is doing and then exit, run:

kill -SIGTERM 11526
➤ Mount a remote directory to a local directory using SSHFS (SSH Filesystem)

SSHFS is a filesystem client that allows mounting remote directories and files over a SSH connection.. First install SSHFS by running apt-get install sshfs. Then, create a new directory on your local laptop/desktop:

mkdir /mnt/newdir

Next, mount the /path/to/dir remote directory to the newly created directory:

sshfs -p 6354 username@123.123.123.123:/path/to/dir /mnt/newdir -o allow_other

where 6354 is the SSH port, username is the name of the user, 123.123.123.123 is the public IP of the remote server and /path/to/dir is the remote directory.

If you want to mount the remote directory as read only, add the ro option, like this:

sshfs -p 6354 username@123.123.123.123:/path/to/dir /mnt/newdir -o allow_other -o ro

Please note that if you mount the remote directory as a regular user, you won’t have permission to access all the directories and files of the remote server. If you want to mount the remote directory using the root user, so as to have permission to see and edit all the remote directories and files, you have to make sure that temporarily, the PermitRootLogin parameter in the /etc/ssh/sshd_config file is set to yes, then restart the SSH service with systemctl restart ssh.

➤ Send a file via SCP (Secure Copy Protocol) to a remote server
scp -P 6582 /path/to/local/file username@123.123.123.123:/path/to/remote-directory

The -P option is used to specify the SSH port when it’s different from the default 22. Change 6582 to your actual SSH port. username is the user that can log in via SSH to the remote server, 123.123.123.123 is the public IP of the remote server, and /path/to/remote-directory is the remote directory where you want to transfer the file.

➤ Override systemd service files without modifying them directly

If you want to modify a systemd service without editing it directly, in order to avoid loosing your changes on future updates, you can create a service file that will override the original service file. To do so, run:

systemctl edit servicename.service

This command creates the /etc/systemd/system/servicename.service.d directory and the override.conf file inside that directory. The settings inside override.conf override the settings in the original servicename.service file located in the /lib/systemd/system directory or in the /etc/systemd/system directory.

➤ Generate HTTP authentication passwords

First install the apache2-utils package, which contains the htpasswd tool:

apt-get install apache2-utils

Then, create the directory to hold the password files (it’s assumed that you use Nginx as a web server, and not Apache):

mkdir /etc/nginx/htpass

Next, if you want to generate a password for HTTP authentication for the user john, run:

htpasswd -c /etc/nginx/htpass/passwd john

Change passwd with your desired name for the password file, and john with the username for which you want to generate the password. The command from above will prompt you to type and retype a password for the user john and will create a file called passwd in which it will store the username followed by the password, hashed with the default MD5 algorithm. The content of the file will look similar to this:

john:$dae1$dNqvAUPd$JBOs/szkb5MAkN94/sNGm2

Don’t forget to restrict permissions for the password file (400 permissions should be enough).

To add the credentials for a new user tom to the /etc/nginx/htpass/passwd file, you should run a similar command but without the -c option, because the file has been already created:

htpasswd /etc/nginx/htpass/passwd tom
➤ Find all the files with the setUID bit set, inside a specific directory and its subdirectories
find /path/to/directory -type f -perm /4000
➤ Find all the directories with the setGID bit set, inside a specific directory and its subdirectories
find /path/to/directory -type d -perm /2000
➤ Find all the directories with the sticky bit set, inside a specific directory and its subdirectories
find /path/to/directory -type d -perm /1000
➤ Mark a package as ‘automatically installed’
apt-mark auto packagename

When a package is marked as ‘automatically installed’, this will cause the package to be removed with the apt-get autoremove command, if there are no other packages that depend on it. This command can be used for example if you accidentally reinstall a package that has been already installed as a dependency, by other package. When you reinstall it accidentally, it will be marked as ‘manually installed’ and because of this, it will be left behind when you will uninstall the package that needs it as a dependancy and you will use the apt-get autoremove command. To be able to remove it with the apt-get autoremove command when no other packges depend on it, you can mark it as ‘automatically installed’ with the command from above.

➤ Mark a package as ‘manually installed’
apt-mark manual packagename

When a package is marked as being ‘manually installed’, this will prevent the package from being automatically removed with the apt-get autoremove command when no other packages depend on it. When a package is installed as a dependancy by other package, it is marked as ‘automatically installed’. This means that when you uninstall the package that needs it as a dependancy, you can use the apt-get autoremove command to uninstall it automatically. However, if you want it to remain installed even after uninstalling the package that depends on it and after running apt-get autoremove, you can mark it as ‘manually installed’ with the command from above.

➤ Verify the integrity of the /etc/passwd file and its corresponding shadow file
pwck

This command verifies the integrity of the users and authentication information. It checks that all the entries in the /etc/passwd and /etc/shadow files have the proper format and contain valid data. The user is prompted to correct the entries that are improperly formatted or have other errors.

Please note that the pwck command complains about a series of home directories that it can’t find. Ignore the following messages, because they don’t indicate real problems:

user 'lp': directory '/var/spool/lpd' does not exist
user 'news': directory '/var/spool/news' does not exist
user 'uucp': directory '/var/spool/uucp' does not exist
user 'list': directory '/var/list' does not exist
user 'irc': directory '/var/run/ircd' does not exist
user 'gnats': directory '/var/lib/gnats' does not exist
user 'nobody': directory '/nonexistent' does not exist
user '_apt': directory '/nonexistent' does not exist
user 'messagebus': directory '/nonexistent' does not exist
user 'openvpn_server': directory '/home/openvpn_server' does not exist
user 'mysql': directory '/nonexistent' does not exist
user 'memcache': directory '/nonexistent' does not exist
user 'dovenull': directory '/nonexistent' does not exist
user 'policyd-spf': directory '/nonexistent' does not exist
user 'spamass-milter': directory '/var/lib/spamass-milter' does not exist
user 'lool': directory '/home/lool' does not exist
pwck: no changes
➤ Verify the integrity of the /etc/group file and its corresponding gshadow file
grpck
➤ Remove the deb archives of packages that are no longer installed on the system, from the package cache
apt-get autoclean

This command removes all the deb archives of the packages that are no longer installed on the system, from the /var/cache/apt/archives directory.

➤ Remove all the packages from the package cache
apt-get clean

This command removes all the packages from the package cache, which means all the packages saved in the /var/cache/apt/archives and /var/cache/apt/archives/partial directories. It only leaves the /var/cache/apt/archives/lock file in place.

➤ Restart the networking service
systemctl restart networking
➤ Find the default gateway of the system
route -n

The output of this command will look similar to this:

Kernel IP routing table
Destination     Gateway         Genmask         Flags Metric Ref    Use Iface
0.0.0.0         123.123.123.1    0.0.0.0         UG    0      0        0 ens3
123.123.123.1    0.0.0.0         255.255.255.255 UH    0      0        0 ens3

The default gateway will be listed in the ‘Gateway’ column, on the row with the ‘Destination’ 0.0.0.0 . In this case it’s 123.123.123.1 .

➤ Enable mouse support in nano, so that you can place the cursor where you click

To enable mouse support press Alt + m . To disable it, press Alt + m again.

Please note that while the mouse support is enabled, you cannot select text by clicking and then dragging with the mouse.

➤ Get a list with all the installed systemd units together with their status
systemctl list-unit-files
➤ Get the list with the installed kernels
dpkg --list | grep linux-image
➤ Check the version of an installed package
dpkg -s packagename | grep Version
➤ Get hardware information from the BIOS
dmidecode
➤ Get hardware information with the lshw command

First install the lshw utility with apt-get install lshw, then run:

lshw
➤ Get information about the CPU with the lscpu command
lscpu
➤ Get the current CPU frequency
watch -n 0 "lscpu | grep 'MHz'"

To get out of the command’s output window, press Ctrl + c .

➤ Get the CPU average load
uptime

The output of this command will look similar to this:

15:56:28 up 82 days, 10:20,  1 user,  load average: 0.00, 0.03, 0.00

15:56:28 – this is the system’s current time displayed as hour:minute:second.
up 82 days, 10:20 – this shows how long the system has been running (the ‘uptime’) in days, hours and minutes.
1 user – this shows how many users are currently logged on.
load average: 0.00, 0.03, 0.00 – this indicates the system’s load averages for the past 1, 5, and 15 minutes respectively.

➤ Get the available storage space
df -h

The output of this command will look similar to this:

Filesystem      Size  Used Avail Use% Mounted on
udev            3.8G     0  3.8G   0% /dev
tmpfs           779M   81M  699M  11% /run
/dev/sda1        49G  3.8G   42G   8% /
tmpfs           3.9G     0  3.9G   0% /dev/shm
tmpfs           5.0M     0  5.0M   0% /run/lock
tmpfs           3.9G     0  3.9G   0% /sys/fs/cgroup

The available storage space is listed on the lines beginning with /dev , in the Avail column. The total space is listed in the Size column. In the example from above, the total storage space is 49 GiB, of which 42 GiB is free.

➤ Get the current RAM usage
vmstat -s

The output of this command will look similar to this:

      7975668 K total memory
      1934832 K used memory
      2765744 K active memory
      1044088 K inactive memory
      3621604 K free memory
       132400 K buffer memory
      2286832 K swap cache
      ...

The most important data is the ‘total memory’ (7975668 KiB) and the ‘used memory’ (1934832 KiB).

➤ Test SSD/hard disk read speed

First, get the name of the storage device that you want to test, by running the df -h command. The storage device can be /dev/sda1, /dev/sda2, /dev/sdb1, etc. If the device is /dev/sda1, to test its read spead, run:

hdparm -tT /dev/sda1

The result of this command will be similar to this:

/dev/sda1:
 Timing cached reads:   15620 MB in  1.99 seconds = 7849.76 MB/sec
 Timing buffered disk reads: 894 MB in  3.01 seconds = 297.44 MB/sec

The actual read speed is the one listed in ‘Timing buffered disk reads’. In this example the read speed is 297.44 MB/sec.

➤ Test SSD/hard disk write speed

First, get the name of the storage device that you want to test, by running the df -h command. The storage device can be /dev/sda1, /dev/sda2, /dev/sdb1, etc. If the device is /dev/sda1, to test its write spead, run:

sync ; time sh -c "dd if=/dev/sda1 of=/tmp/testfile bs=10k count=1k  && sync" ; rm /tmp/testfile

The output of this command will look similar to this:

1024+0 records in
1024+0 records out
10485760 bytes (10 MB, 10 MiB) copied, 0.0241044 s, 435 MB/s

real	0m0.055s
user	0m0.006s
sys	0m0.020s

The actual write speed is the one listed at the end of the third line of the output, 435 MB/s in this example.

The command shown above writes a file called testfile in the /tmp directory and measures that time needed to complete this task, then removes the /tmp/testfile file. If your system has multiple storage devices, let’s say two storage devices: /dev/sda1 and /dev/sdb1, for the command to succeed, you have to make sure that the test file is written on the storage device that you are testing. If you want to test the /dev/sdb1 device and the operating system (with the /tmp directory) is installed on /dev/sda1, the command from above won’t succeed, because the /tmp/testfile file will be written on the /dev/sda1 device. Therefore, you will have to run the command so that it will write the test file on the second storage device, like this:

sync ; time sh -c "dd if=/dev/sdb1 of=/path/to/testfile bs=10k count=1k  && sync" ; rm /path/to/testfile
➤ Check the file system type
df -T -h

The output of this command will look like this:

Filesystem     Type      Size  Used Avail Use% Mounted on
udev           devtmpfs  3.8G     0  3.8G   0% /dev
tmpfs          tmpfs     779M   81M  699M  11% /run
/dev/sda1      ext4       49G  3.8G   42G   8% /
tmpfs          tmpfs     3.9G     0  3.9G   0% /dev/shm
tmpfs          tmpfs     5.0M     0  5.0M   0% /run/lock
tmpfs          tmpfs     3.9G     0  3.9G   0% /sys/fs/cgroup

The file system type is listed in the Type column.

➤ Update the ClamAV virus definitions
freshclam
Scan all the files and subdirectories inside a directory with the clamdscan command and save the scan report to a file
clamdscan --fdpass --quiet /path/to/directory -l /path/to/report.txt

--fdpass – pass the file descriptor permissions to clamd so as to avoid errors if clamd is running as a different user than the owner of the directories that are scanned.
--quiet – run in quiet mode. Only show the error messages.
/path/to/directory – this is the path to the directory to be scanned.
-l /path/to/report
– write the scan report to the /path/to/report.txt file.

To scan multiple directories, add them one after the other, separated by a single space.

If you want to also remove the files that are found, you can add --remove after --fdpass, but this is dangerous. You won’t be able to check if the detected files are false positives, because they will be deleted the very moment they will be found.

➤ Scan all the files and subdirectories inside a directory with the clamscan command and list all the scanned files
clamscan -r /path/to/directory

To scan multiple directories, add them one after the other separated by a single space.

➤ Scan all the files and subdirectories inside a directory with the clamscan command and list only the infected files
clamscan -ir /path/to/directory
➤ Scan all the files and subdirectories inside a directory with the clamscan command and generate a report with the paths to all infected files
clamscan -r /path/to/directory | grep FOUND >> /path/to/report.txt
➤ Test the Internet speed

First download the speedtest.py script, whose official GitHub repository is here, to the /tmp directory, saving it as speedtest:

cd /tmp
wget -O speedtest https://raw.githubusercontent.com/sivel/speedtest-cli/master/speedtest.py

Then move the script to the /usr/local/bin directory:

mv speedtest /usr/local/bin

Change ownership and permissions:

chown root:root /usr/local/bin/speedtest
chmod 755 /usr/local/bin/speedtest

From now on, you can test the Internet data transfer speed by running:

speedtest

The output of the command will be similar to this:

Retrieving speedtest.net configuration...
Testing from ... (123.123.123.123)...
Retrieving speedtest.net server list...
Selecting best server based on ping...
Hosted by ... [152.54 km]: 32.489 ms
Testing download speed................................................................................
Download: 100.64 Mbit/s
Testing upload speed................................................................................................
Upload: 102.78 Mbit/s

In this example, the download speed is 100.64 Mbit/s and the upload speed is 102.78 Mbit/s. As you can see, to test the Internet speed, the speedtest script uses the servers offered by speedtest.net, a well-known provider of network speed testing services.

Once you have the speedtest script installed as described above, you can get the list of all the available speedtest.net servers around the world, by running:

speedtest --list | more

This command will output a long list of servers located in different regions of the world, each server on a new line. Each line begins with a number associated with that respective server. You can use a server’s number to test the Internet speed to that server. For example, if you want to test the speed to the server that is listed as:

3156) Plexicomm, LLC (Binghamton, NY, United States) [1256.84 km]

you have to run:

speedtest --server 3156
➤ List the content of iptables

If for whatever reason, you don’t want to manage the firewall using UFW (Uncomplicated Firewall), you can modify the iptables directly.

iptables is a firewall utility that is preinstalled in all major Linux distributions. It allows users to configure specific rules that are enforced by the kernel’s netfilter framework. Network traffic is made up of data packets. iptables tries to match each data packet crossing the network interface against a set of rules, to decide what to do with them. iptables uses several tables (files containing similar actions), which are made up of chains (sets of rules). A rule is a statement that tells the system what to do with a data packet. A target is a decision of what to do with a data packet. The target can be:

  • ACCEPT – the packet that comes through the iptables firewall is accepted.
  • DROP – the packet is dropped and is not matched against any further rule. When the packet is dropped, the system trying to connect will not receive any error message.
  • RETURN – the packet is sent back to the originating chain, so that it can be matched against other rules.
  • REJECT – the packet is rejected and an error message is sent to the connecting device.

The most frequently used table is the filter table which has 3 default chains: Input, Output, Forward. New chains can be added to the default ones.

To list all the chains and rules of the filter table of iptables, run:

iptables -L

You can list all the chains and rules of the filter table of ip6tables similarly:

ip6tables -L

If you want to list all the rules with line numbers, run:

iptables -L --line-numbers
➤ Open a port in the firewall for incoming traffic, using the iptables command

To open the 3415 port in the firewall for incoming traffic over TCP, run:

iptables -A INPUT -p tcp --dport 3415 -j ACCEPT

A similar command can be run for ip6tables (you just replace iptables with ip6tables).

Please note that the -A option stands for append and it adds the rule at the end of the specified chain (the INPUT chain in this example). If you want to insert the rule in the specified chain at a given position, let’s say at line number 8, you should use the -I option, which stands for insert, like this:

iptables -I INPUT 8 -p tcp --dport 3415 -j ACCEPT

If you use the -I option and you don’t specify a line number, the rule will be inserted at the top of the chain.

➤ Open a port in the firewall for outgoing traffic, using the iptables command
iptables -A OUTPUT -p tcp --dport 4625 -j ACCEPT

where 4625 is the port that you want to open. A similar command can be run for ip6tables.

➤ Block incoming traffic on a port, using the iptables command
iptables -A INPUT -p tcp --dport 3962 -j DROP

where 3962 is the port for which you want to block incoming TCP traffic. A similar command can be run for ip6tables.

If you want to block the connections and also send an error message to the connecting devices, you will have to replace DROP with REJECT.

➤ Block outgoing traffic on a port, using the iptables command
iptables -A OUTPUT -p tcp --dport 4837 -j DROP

where 4837 is the port for which you want to block outgoing TCP traffic. A similar command can be run for ip6tables.

➤ Block all incoming connections from a specific IP address, using the iptables command
iptables -A INPUT -s 123.123.123.123 -j DROP

This command will block all incoming connections from 123.123.123.123. A similar command can be run for ip6tables and an IPv6 address.

➤ Block all incoming connections over TCP from a specific IP address, on a specific port, using the iptables command
iptables -A INPUT -p tcp --dport 3624 -s 123.123.123.123 -j DROP

This command will block all incoming connections over TCP from 123.123.123.123, on port 3624. A similar command can be run for ip6tables and an IPv6 address.

➤ Block all outgoing connections to a specific IP address, using the iptables command
iptables -A OUTPUT -d 123.123.123.123 -j DROP

This command will block all outgoing connections to 123.123.123.123. A similar command can be run for ip6tables and an IPv6 address.

➤ Block all incoming connections from a range of IP addresses, using the iptables command
iptables -A INPUT -m iprange --src-range 123.123.123.100-123.123.123.200 -j DROP

This command will block all incoming connections from the IPs in the range 123.123.123.100-123.123.123.200. A similar command can be run for ip6tables and an IPv6 address.

➤ Accept all incoming connections from a specific IP address, using the iptables command
iptables -A INPUT -s 123.123.123.123 -j ACCEPT

This command will accept all incoming connections from 123.123.123.123. A similar command can be run for ip6tables and an IPv6 address.

➤ Remove iptables rules

To delete an iptables rule using the chain name and line number, first list all the rules with line numbers, by adding the --line-numbers option:

iptables -L --line-numbers

The output of this command will look similar to this:

Chain INPUT (policy DROP)
num  target     prot opt source               destination         
1    f2b-postfix  tcp  --  anywhere             anywhere             multiport dports smtp,submissions,submission
2    f2b-named-refused  tcp  --  anywhere             anywhere             multiport dports domain,domain,953
3    f2b-postfix-sasl  tcp  --  anywhere             anywhere             multiport dports smtp,submissions,imap2,imaps,pop3,pop3s,submission
4    ufw-before-logging-input  all  --  anywhere             anywhere            
5    ufw-before-input  all  --  anywhere             anywhere            
6    ufw-after-input  all  --  anywhere             anywhere            
7    ufw-after-logging-input  all  --  anywhere             anywhere            
8    ufw-reject-input  all  --  anywhere             anywhere            
9    ufw-track-input  all  --  anywhere             anywhere
...

Each rule, under each chain, will be preceded by a number. To delete, for example the 5th rule in the INPUT chain, run:

iptables -D INPUT 5

where INPUT is the name of the chain and 5 is the rule’s line number. A similar command can be run for ip6tables.

Another method to delete an iptables rule is by rule specification. For example, to delete the rule added with the command:

iptables -A INPUT -s 123.123.123.123 -j DROP

you run:

iptables -D INPUT -s 123.123.123.123 -j DROP

Please note the -D option added after the iptables command. -D stands for delete. A similar command can be run for ip6tables.

➤ Make the changes applied to iptables/ip6tables persist after reboot

After you have added or removed firewall rules by modifying the iptables or ip6tables directly, to make them persist after reboot, run:

/sbin/iptables-save
/sbin/ip6tables-save
➤ Get the last line of the output of a command
command | tail -1
➤ Split a long command on multiple lines, in a script

Add a backslash at the end of each line, like this

first part of command \
second part of command \
third part of command \
fourth part of command
➤ Check if any packages are in a half installed state
dpkg --audit
➤ Check if any packages are on hold
dpkg --get-selections | grep hold
➤ Find all the obsolete packages installed on the system

If a software package is installed on the system but it can no longer be found in any of the current configured repositories, that package is considered ‘obsolete’. You can find all the obsolete packages on the system by running:

apt search '~o'

If this command returns any packages and you don’t need them anymore, you can remove them with the apt-get purge packagename command.

➤ Generate 16 bytes of random hexadecimal characters, with the openssl command
openssl rand -hex 16

This command will generate 32 characters, because 32 hexadecimal characters can be encoded in 16 bytes.

➤ Generate 24 bytes of random base64 characters, with the openssl command
openssl rand -base64 24
➤ Log in to MariaDB on localhost
mariadb -u username -p

This command will prompt you to enter username‘s password, and after you enter it, you will be logged in to MariaDB:

Welcome to the MariaDB monitor.  Commands end with ; or \g.
Your MariaDB connection id is 4767
Server version: 10.3.29-MariaDB-0+deb10u1 Debian 10

Copyright (c) 2000, 2018, Oracle, MariaDB Corporation Ab and others.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

MariaDB [(none)]> 

After you run your SQL commands, to exit just type exit and press Enter.

You can also log in to MariaDB by running mysql -u username -p . Even if you have MariaDB installed on your system and not MySQL, since MariaDB is a fork of MySQL and very similar, all the commands that contain the term mariadb can be also run using the term mysql instead.

➤ Change the password of a MariaDB user

Once you log in to MariaDB with mariadb -u username -p , you can change username‘s password with:

MariaDB [(none)]> alter user 'username'@'localhost' identified by 'newpassword';
➤ Create a new MariaDB user
MariaDB [(none)]> create user 'username'@'localhost' identified by 'password';
➤ Grant all privileges (including GRANT) on a database to a specific user
MariaDB [(none)]> grant all privileges on databasename to 'username'@'localhost' with grant option;
➤ Grant all privileges (including GRANT) on any database on localhost to a specific user
MariaDB [(none)]> grant all privileges on *.* to 'username'@'localhost' with grant option;
MariaDB [(none)]> flush privileges;
➤ Grant specific privileges on a database to a specific user
MariaDB [(none)]> grant select,insert,update,delete,create,drop on databasename to 'username'@'localhost';
➤ List all the privileges of a user
MariaDB [(none)]> show grants for 'username'@'localhost';
➤ Revoke all the privileges on a database for a specific user
MariaDB [(none)]> revoke all privileges on databasename from 'username'@'localhost';

➤ Delete a MariaDB user

MariaDB [(none)]> drop user 'username'@'localhost';

➤ Create a MariaDB database

MariaDB [(none)]> create database newdatabasename;
➤ Delete a MariaDB database
MariaDB [fruit]> drop database databasename;
➤ List all the MariaDB databases on localhost

Once you log in to MariaDB, to list all the databases, run:

MariaDB [(none)]> show databases;

To log in to a particular database, run:

MariaDB [(none)]> use databasename;
➤ List all the tables in the current MariaDB database
MariaDB [databasename]> show tables;
➤ Show information about all the columns of a table
MariaDB [databasename]> describe tablename;
➤ Delete a table in a database
MariaDB [databasename]> drop table tablename;
➤ Export a MySQL/MariaDB database located on localhost, with the mysqldump command
mysqldump -u username -p databasename > /path/to/directory/saveddatabase.sql

After you run this command, you will be asked for username‘s password. This command will save the databasename database as an sql file in the /path/to/directory directory.

➤ Export a MySQL/MariaDB database located on a host different from localhost, with the mysqldump command
mysqldump -h hostname -u username -p databasename > /path/to/directory/saveddatabase.sql

hostname can be the hostname of the remote host (like data.example.com), or the IP address of the remote host (like 123.123.123.123).

➤ Export a table from a MySQL/MariaDB database located on localhost
mysqldump -u username -p databasename tablename > /path/to/example.sql
➤ Import a MySQL/MariaDB database from an sql file

First create a new empty database with the same name as the database you want to import:

mariadb -u username -p
Enter password:
MariaDB [(none)]> create database databasename;

Then run:

mysql -u username -p  databasename  < /path/to/databasename.sql

The databasename.sql file can have any name, although in general, it has the same name as the database that has been exported to it.

➤ Import a table in a MySQL/MariaDB database from an sql file
mysql -u username -p  databasename  < /path/to/table/example.sql
➤ List the kernel modules that are currently loaded
lsmod
➤ Load a kernel module manually
modprobe module-name
➤ Unload a kernel module manually
rmmod module-name
➤ Generate a new RSA private key with the openssl command
openssl genrsa -out /path/to/server.key 2048

2048 is the number of bits for the key. You can replace it with 4096 for a stronger encryption key. The private key file can have the name of a domain or any other name, and a different termination, such as pem.

➤ Generate a new Certificate Signing Request (CSR) with the openssl command

If the private key is /path/to/myserver.key, you can generate the CSR file by running:

openssl req -new -key /path/to/myserver.key -out /path/to/csr/file/server.csr

The CSR file can have the name of a domain or any other name, and a different termination, such as txt.

➤ Generate a new RSA private key and a Certificate Signing Request (CSR) in one command, with the openssl command
openssl req -newkey rsa:2048 -nodes -keyout myserver.key -out server.csr

2048 is the number of bits for the key. You can replace it with a larger value. You will be asked to enter a few details, such as Country Name, Organization Name, Common Name etc. If you want to leave a field empty, just press Enter.

The -nodes option stands for ‘no DES’, which means ‘do not encrypt the private key in a PKCS#12 file’. Without this option, the private key will be encrypted and you will be prompted to enter a passphrase for this encryption step.

The command from above will create the myserver.key file containing the private key and the server.csr file containing the Certificate Signing Request (CSR). Don’t forget to restrict access to the private key file.

➤ Generate a self-signed SSL certificate while having the private key and using a self-generated Certificate Signing Request (CSR), with the openssl command

If the private key is /path/to/privatekey/myserver.key, run:

openssl req -x509 -days 73000 -in /path/to/server.csr -signkey /path/to/privatekey/myserver.key -out /path/to/certificate/cert.crt

You can change the number of days the SSL certificate will be valid for, from 73000 (200 years) to other value. However, if you enter a short period of time, you will have to remember to manually regenerate the certificate before it expires. The certificate file can have a different termination, such as pem.

X.509 is a format standard for digital certificates.

➤ Generate a self-signed SSL certificate, having a private key but without using a self-generated Certificate Signing Request (CSR), with the openssl command
openssl req -x509 -days 73000 -new -nodes -key /path/to/privatekey/myserver.key -out /path/to/certificate/cert.crt
➤ Generate a private key and a self-signed SSL certificate without using a self-generated Certificate Signing Request (CSR), with the openssl command
openssl req -x509 -days 73000 -newkey rsa:2048 -nodes -keyout /path/to/privatekey/myserver.key -out /path/to/certificate/cert.crt
➤ Find the expiration date of a SSL certificate
openssl x509 -in /path/to/certificate/cert.crt -noout -enddate
➤ Generate a Diffie-Hellman parameter with the openssl command
openssl dhparam -out /path/to/dhparam.pem 2048

2048 is the number of bits for the parameter and you can replace it with a larger value.

➤ Regenerate the self-signed snakeoil certificate and key

On Debian, when the ssl-cert package is installed, a private key (/etc/ssl/private/ssl-cert-snakeoil.key) and a self-signed certificate (/etc/ssl/certs/ssl-cert-snakeoil.pem) are automatically created. They can be regenerated by running:

make-ssl-cert generate-default-snakeoil --force-overwrite
➤ Recover a RSA public key in OpenPGP format from the private key with the gpg command

If you don’t have the private key, first import it from a file by running:

gpg --import private_key_file

Then export the public key to a file by running:

gpg --armor --export 0xD504264E > pubkey.asc

where D504264E is the key ID (the last 8 digits of the key’s fingerprint, that can be found with the gpg --list-keys command). The --export option will export the public key of the RSA key with the ID D504264E, to the pubkey.asc file, in ASCII armored format. The command will also work if you don’t prepend 0x to the key ID.

Instead of the key ID, you can use the email address associated with the key (which can be found with the gpg --list-keys command), like this:

gpg --armor --export email@example.com > pubkey.asc
➤ Use ApacheBench to assess the number of requests per second a web server can serve

First install the apache2-utils package, which contains the ApacheBench tool:

apt-get install apache2-utils

If https://www.example.com is a website hosted on the server whose performance you want to test, run:

ab -c 100 -n 1000 https://www.example.com/

Where -c specifies the number of concurent users and -n specifies the number of requests that will be sent to the web server. Don’t forget to add the slash at the end of the URL, otherwise the command will fail.

You can also add the -t option to specify the maximum number of seconds in which the test will be performed. If the number of requests specified with the -n option has been sent and the total amount of time is not over, additional requests will be sent, until the specified period of time will be over. The following command will perform the test within 60 seconds:

ab -c 100 -n 1000 -t 60 https://www.example.com/
➤ Working with Git

If you need to use Git, you can find a complete list with the essential Git commands here.

➤ Delete the content of a file but not the file itself
cat /dev/null > /path/to/filename
➤ Decompress a gz file and keep the original file
gunzip -k filename.gz
➤ Remove a file securely by overwriting it 7 times before deleting it
shred -n 7 -u /path/to/filename

You can choose a different number of overwrites than 7. If you run it without adding the -n 7 option, the shred command will overwrite the file 3 times (which is the default number), and then delete it.

➤ Send a POST request to a URL using the curl command

First install curl by running apt-get install curl. Then run:

curl --data "param1=value1&param2=value2" https://example.com/script.php

The command from above sends two parameters, param1 and param2, having the values value1 and value2 respectively, in a POST request, to the script.php script, that can be accessed at the URL: https://example.com/script.php .

➤ List the manual page of a Linux command
man command





You can send your questions and comments to: