Skip to content

Instantly share code, notes, and snippets.

@shakeeb91
Last active August 26, 2021 22:18
Show Gist options
  • Save shakeeb91/39ec503932ddf521257ff70b56658d3c to your computer and use it in GitHub Desktop.
Save shakeeb91/39ec503932ddf521257ff70b56658d3c to your computer and use it in GitHub Desktop.
Linux Cheat Sheet

Linux Cheat Sheet

Below are the commands tested and verfied over Linux ( Debian / Ubuntu ) Based OS.

.htaccess

Deny or Allow
<Limit GET POST>
order allow,deny
deny from 1.2.3.4
deny from 1.2.3.5
deny from 10.1.2.1/24
allow from all
</Limit>   

For single IP

deny from 1.1.1.1
If you want to block the access directly without login on wordoress
<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteCond %{HTTP_COOKIE} !.*wordpress_logged_in.*$ [NC]
#   RewriteCond %{REQUEST_URI} ^(.*?/?)wp-content/uploads/.*\.(?:pdf|jpeg|txt)$ [NC]
    RewriteCond %{REQUEST_URI} ^(.*?/?)wp-content/uploads/.* [NC]
    RewriteRule . http://%{HTTP_HOST}%1/wp-login.php?redirect_to=%{REQUEST_URI} [L,QSA]
</IfModule>
If redirect domain to https
RewriteCond %{HTTP_HOST} ^example\.com  [NC]
RewriteRule ^(.*) https://www.example.com/$1 [L,R=301]

Also

RewriteEngine On
RewriteCond %{HTTP_HOST} ^\.exampledomain\.legal [NC,OR]
RewriteCond %{HTTP:X-Forwarded-Proto} !https
RewriteRule ^(.*)$ https://www.exampledomain.legal/$1 [R=301,L]
Redirect root domain to subfolder
RewriteEngine On
RewriteRule ^$ /foldername [L]
Subdomain to Subfolder
RewriteCond %{HTTP_HOST} ^seller.domain.com
RewriteRule ^(.*)$ https://www.domain.com/seller/$1 [L,NC,QSA]
Redirect traffic to Port
RewriteEngine On
RewriteBase /express
RewriteRule ^(.*)?$ http://127.0.0.1:3000/$1 [P,L]
HTPASSWD

Create a .htpasswd file in specific folder

root@hostname:~# htpasswd -c .htpasswd name-of-user
New password:
Re-type new password:
Adding password for user name-of-user

Now Edit the .htaccess file and put below code

AuthUserFile /path/to/.htpasswd
AuthType Basic
AuthName "My restricted Area"
require user name-of-user
CSP and SECURITY
<IfModule mod_headers.c>
Header set X-Content-Type-Options: nosniff
Header set Strict-Transport-Security "max-age=31536000; includeSubDomains; preload" env=HTTPS
Header set Content-Security-Policy "default-src 'self'; child-src *; frame-src *; img-src * data:; media-src *;script-src 'self' 'unsafe-inline' 'unsafe-eval' *;style-src 'self' 'unsafe-inline' http: https: fonts.googleapis.com; font-src 'self' data: http: https: fonts.googleapis.com themes.googleusercontent.com;"
Header set Feature-Policy "geolocation 'self'; vibrate 'none'"
Header set X-Permitted-Cross-Domain-Policies "self"
Header set X-Frame-Options "SAMEORIGIN"
Header set Referrer-Policy "same-origin"
Header set X-XSS-Protection "1; mode=block"
</IfModule>

Package Installation

Composer 1 Installation
cd /home/master/  &&  wget https://getcomposer.org/download/1.10.17/composer.phar
chmod +x  composer.phar
mv composer.phar  composer

> or 

composer self-update --1
Composer 2
cd /home/master/  &&  wget https://getcomposer.org/download/2.0.0/composer.phar
chmod +x composer.phar
mv composer.phar composer

> or 

composer self-update --2
pdftk
sudo apt install snapd
sudo snap install pdftk
cd /usr/local/bin/
ln -s /snap/bin/pdftk .

To verify

whereis pdftk
pdftk --version
NODE
curl -sL https://nodejs.org/download/release/v14.14.0/node-v14.14.0-linux-x64.tar.gz | tar -xzf -
cd node-v14.14.0-linux-x64/bin/
ls -la
cp node /usr/bin/
cd ../lib/node_modules/npm/bin/
rm /usr/bin/npm
rm /usr/bin/npx
ln -s ~/node-v14.14.0-linux-x64/lib/node_modules/npm/bin/npx-cli.js /usr/bin/npx
ln -s ~/node-v14.14.0-linux-x64/lib/node_modules/npm/bin/npm-cli.js /usr/bin/npm
npm -v
npm install npm@latest -g
npm install npm@latest -g --force
npm -v

odbc and pdosql_srv
apt-get install unixodbc-dev
sudo pecl install sqlsrv
sudo pecl install pdo_sqlsrv

Check PHP version and then switch to that specific php.ini

php -v
vim /etc/php/7.4/fpm/php.ini -C

Edit the lines with

extension=sqlsrv.so
extension=pdo_sqlsrv.so

And then restart the service

/etc/init.d/php7.4-fpm restart

printf "; priority=20\nextension=sqlsrv.so\n" > /etc/php/7.4/mods-available/sqlsrv.ini
printf "; priority=30\nextension=pdo_sqlsrv.so\n" > /etc/php/7.4/mods-available/pdo_sqlsrv.ini

phpenmod sqlsrv
phpenmod pdo_sqlsrv
/etc/init.d/php7.4-fpm restart
OAUTH CURL PHP
sudo apt-get install build-essential libtool autoconf unzip wget libpcre++-dev libcurl4-gnutls-dev
phpize

wget http://pecl.php.net/get/oauth-2.0.5.tgz
tar xzf oauth-2.0.5.tar.gz
ls -la
tar -xvzf oauth-2.0.5.tgz 
cd oauth-2.0.5/
ls -la
phpize
./configure
make
sudo make install
php -v
/opt/bitnami/ctlscript.sh restart php_oauth.h

Check PHP Version and Restart Service

sudo systemctl restart php7.4-fpm.service

SWAP MEMORY INCREASE

Note: Below If you want to add 1GiB of SWAP space then use count=1M if you want to set 2GiB then set the count=2M

dd if=/dev/zero of=/tmp/swapfile.img bs=4096 count=1M
mkswap /tmp/swapfile.img
cp /etc/fstab  /tmp/fstab-org

vim /etc/fstab 

Add Below at the bottom of the file

/var/swap.1 swap swap sw 0 0

Then

swapon /tmp/swapfile.img
swapoff /tmp/swapfile.img
How to check which service is using highest swap memory?
for file in /proc/*/status ; do awk '/VmSwap|Name/{printf $2 " " $3}END{ print ""}' $file; done | sort -nrk 2

FIND COMMANDS

Change all folder permission to 775
find . -type d -exec chmod 775 {} \;
Change all files permission to 664
find . -type f -exec chmod 664 {} \;
Change all folder ownership
find . -type d -exec chown -R www-data:www-data {} \;
Find all directories
find . -type d
find all files
find . -type f
find with specific depth
So maxdepth 2 shows till 2 folders inside it.
find . -maxdepth 2 -type d

Output

/abc/
/abc/bcd
So maxdepth 5 shows all 5 folders inside it
find . -maxdepth 5 -type d

Output:

/abc/
/abc/bcd/
/abc/bcd/efg/
/abc/bcd/efg/hij
/abc/bcd/efg/hij/klm
Min depth 2 will give output from a min depth of 2
find . -mindepth 2 -type d

Output

./abc/bcd
./abc/bcd/efg
./abc/bcd/efg/hij
./abc/bcd/efg/hij/klm
Min depth 4 will give output from a min depth of 4
find . -mindepth 4 -type d

Output

./abc/bcd/efg/hij
./abc/bcd/efg/hij/klm
Use min and max both
find . -mindepth 2 -maxdepth 3 -type d

Output

./abc/bcd
./abc/bcd/efg
Check file size greater then
find / -type f -size +100M
Delete files older then 30days
find /var/php/sessions -mtime +30 -exec rm {} \;

SSH

If you want to give specific command access to SUDO users
shakeeb  ALL=(ALL:ALL) ALL
USER1   ALL=(ALL:ALL) ALL
DEV      ALL=(ALL) NOPASSWD: /usr/bin/git
SUPERDEV    ALL=(ALL) NOPASSWD: /usr/bin/git, /usr/bin/screen

IPTABLES / SECURITY

1) By Default all is ALLOW and Three Chains are there ( INPUT/FORWARD/OUTPUT )
2) Three Connection Response ( ACCEPT, DENY, DROP )
ACCEPT: Allow all connection
DROP: Shows that HOST is not EXIST give ( Request timeout Error )
DENY: Shows that HOST is present but blocked by firewall ( Destination host unreacheable )

list all tables

iptables -L -v

Flush all tables

iptables -F

DROP SPECIFIC IP

iptables -A INPUT -s 10.10.10.12 -j DROP

DROP RANGE of IP

iptables -A INPUT -s 10.10.10.1/24 -j DROP

DROP SPECIFIC IP PORT

iptables -A INPUT -p tcp --dport ssh -s 10.10.10.120 -j DROP

#!/bin/bash
iptables -C FORWARD -m string --string "$1" --algo bm --to 65535 -j DROP
RESULT=$?
if [ $RESULT == 0 ]; then
  echo "The Rule is already Exist for the domain $1"
else
  iptables -I FORWARD -m string --string "www.$1" --algo bm --to 65535 -j DROP
  iptables -I FORWARD -m string --string "$1" --algo bm --to 65535 -j DROP
  echo " iptables rule added for the $1 Domain "
fi
root@shakeeb:/home/shakeeb# cat removeblockdomain.sh
#!/bin/bash
echo "Iptable Rule for the domain $1 has been successfuly Deleted"
iptables -D FORWARD -m string --string "www.$1" --algo bm --to 65535 -j DROP
iptables -D FORWARD -m string --string "$1" --algo bm --to 65535 -j DROP

MYSQL

Basic

InnoDB MyISAM
InnoDB implements row-level. MyISAM can do only a table-level lock.
InnoDB has better crash recovery option.
FULLTEXT Search indexes doesn’t support until v5.6. FULLTEXT Search is supported.
ACID Properties is supported ACID Properties is not supported.
It has Buffer Pool to cache data and index pages. The main mechanism used is the key cache. It only caches index pages from .MYI files.
You can take backup of InnoDB tables using just a snapshot of the filesystem. You require mysqldump to take backup of MyIsam table.
Implemented transactions, foreign keys and relationship constraints. Doesn't
InnoDB is a transaction-safe (ACID compliant) storage engine for MySQL that has commit, rollback, and crash-recovery capabilities to protect user data. MyISAM doesn't
Less COUNT(X) performance is very fast.
Less Supported high level table compression.

Installation


Basic MySQL Commands
To create database
MariaDB [(none)]> create database DBNAME;
To delete database
MariaDB [(none)]> drop database DBNAME;
To show tables
MariaDB [(none)]> show databases;
To use tables and show tables
MariaDB [(none)]> use axsbapqrxz;

MariaDB [axsbapqrxz]> show tables;
To check database size
MariaDB [(none)]> SELECT table_schema AS "Database",
ROUND(SUM(data_length + index_length) / 1024 / 1024, 2) AS "Size (MB)"
FROM information_schema.TABLES
GROUP BY table_schema;
To check tables size of specific DB
MariaDB [(none)]> SELECT table_name AS "Table",
ROUND(((data_length + index_length) / 1024 / 1024), 2) AS "Size (MB)"
FROM information_schema.TABLES
WHERE table_schema = "axsbapqrxz"
ORDER BY (data_length + index_length) DESC;
List of DB Users
mysql> select user,host from mysql.user;
Basics:
  1. localhost means user can access the db locally
  2. % means user can access the db from anywhere
  3. 1.1.1.1 ( Any specific IP ) means user can access it from one IP.
To Add User to Specific DB
mysql> GRANT ALL PRIVILEGES ON DBNAME.* TO 'db_user'@'localhost' IDENTIFIED BY 'P@s$w0rd';

To Alter Password of DB User
mysql> ALTER USER 'DBUSER'@'%' IDENTIFIED BY 'NEWPASSWORD';
To Check Access / Grants
mysql> show grants for bilal@'localhost';
+----------------------------------------------------------+
| Grants for DBUSER@localhost                               |
+----------------------------------------------------------+
| GRANT USAGE ON *.* TO 'DBUSER'@'localhost'                |
| GRANT ALL PRIVILEGES ON `DBNAME`.* TO 'DBUSER'@'localhost' |
+----------------------------------------------------------+
2 rows in set (0.00 sec)

Repair DB
root@hostname:~# mysqlcheck dbname
root@hostname:~# mysqlcheck --auto-repair -A

MAIL

To Check mail Queue

mailq

To Delete all mails in Mail Queue

postsuper -d ALL

Basic Cheats

To Check Concurrent User
watch -xtn 1 awk '$2 ~ /:01BB/ || $2 ~ /:0050/ {count +=1;} END {print count}' /proc/net/tcp
To Check Current Login User on Server
w
To Check last login users
last
To check disk and inodes
df -hT
df -i
Block and Allow Access to Edit files/folder

List the Permission

lsattr foldername

To Block/Restrict

chattr -R +ia public_html/

To Allow

chattr -R -ia public_html/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment