Tuesday, August 29, 2023

Creating an SSH tunnel in Linux | how to create ssh tunnel in Linux


Creating an SSH tunnel in Linux allows you to securely forward traffic between your local machine and a remote server. This can be useful for a variety of purposes, such as encrypting your connection or accessing services on a remote server that are not directly accessible from your local machine. There are two main types of SSH tunnels: local and remote.


Here's how you can create both types of SSH tunnels using the `ssh` command in Linux:


1. Local Port Forwarding:

   Local port forwarding allows you to forward traffic from a port on your local machine to a port on a
   remote server.


     ssh -L  local_port:remote_host:remote_port  user@ssh_server

   

   - local_port: The port on your local machine where you want to receive the forwarded
                           traffic.

   - remote_host: The hostname or IP address of the remote server.

   - remote_port: The port on the remote server to which the traffic will be forwarded.

   - user: Your username on the remote server.

   - ssh_server: The hostname or IP address of the SSH server you're connecting to.


   Example:

   To forward traffic from a remote server's port 80 to your local machine's port 8080 :

     ssh -L 8080:192.168.1.100:80 user@192.168.1.100

   

2. Remote Port Forwarding:

   Remote port forwarding allows you to forward traffic from a port on a remote server to a
   port on your local machine.


   ssh -R remote_port:local_host:local_port user@ssh_server

   

   - remote_port: The port on the remote server where you want to receive the forwarded
                              traffic.

   - local_host: The hostname or IP address of your local machine as seen from the remote
                           server (usually `localhost` or `127.0.0.1`).

   - local_port: The port on your local machine to which the traffic will be forwarded.

   - user: Your username on the remote server.

   - ssh_server: The hostname or IP address of the SSH server you're connecting to.


   Example:

   To forward traffic from a local machine's port 80 to remote server's port 8080:

   ssh -R 8080:localhost:80 user@192.168.1.100

Remember to replace placeholders like `local_port`, `remote_host`, etc., with the appropriate values for your setup. Also, make sure that you have SSH access to the remote server and that the necessary ports are allowed through any firewalls.

Monday, August 28, 2023

Exploring Firewall Examples on RHEL 7/8: Enhancing Network Security | Firewall Examples in RedHat


Introduction


In the modern age of computing, where data flows freely across networks, the importance of network security cannot be overstated. Firewalls play a pivotal role in safeguarding systems from unauthorized access and potential threats. Red Hat Enterprise Linux (RHEL), a widely-used enterprise-level operating system, provides robust firewall solutions to secure your networked systems. In this blog, we'll delve into firewall examples on both RHEL 7 and RHEL 8, showcasing how to implement and configure firewalls to fortify your network.


Firewall Basics


A firewall acts as a barrier between a trusted internal network and untrusted external networks, controlling incoming and outgoing traffic based on predefined rules. RHEL uses a firewall management tool called `firewalld` to configure and manage firewalls. This tool provides a dynamic and user-friendly interface for defining rules, zones, and services.


1. Basic Configuration:

   By default, RHEL 7 and 8 have a default zone called 'public.' Here's how you can get started with configuring basic firewall settings:


   - View Firewall Status:

     You can use the following command to check the current firewall status:

     sudo systemctl status firewalld

     

   - Enable and Start Firewall:

     To enable and start the firewall service, use:

     sudo systemctl enable firewalld

     sudo systemctl start firewalld

     

   - View Available Zones:

     Check the available firewall zones with:

     sudo firewall-cmd --get-zones

    sudo firewall-cmd --get-default-zone

     

2. Zone Configuration:

   Firewalld categorizes networks into zones, each with specific security settings. Here are some examples:


   - Public Zone:

     sudo firewall-cmd --zone=public --add-service=http --permanent

     sudo firewall-cmd --zone=public --add-service=https --permanent

     sudo firewall-cmd --reload

     

   - Home Zone:

     sudo firewall-cmd --zone=home --add-service=ssh --permanent

     sudo firewall-cmd --reload

     

3. Port and Service Management:

   You can allow specific ports or services through the firewall:

    - List open Ports:


     sudo firewall-cmd  --list-all

  sudo firewall-cmd --list-services

   sudo firewall-cmd --list-ports

   - Allow a Port:

     sudo firewall-cmd --zone=public --add-port=8080/tcp --permanent

     sudo firewall-cmd --reload

     

   - Remove a Port:

     sudo firewall-cmd --zone=public --remove-port=8080/tcp --permanent

     sudo firewall-cmd --reload

     

4. Rich Rules:

   Rich rules provide more advanced firewall control:


   - Allow by Source IP:

     sudo firewall-cmd --zone=public --add-rich-rule='rule family="ipv4" source address="192.168.1.100" accept' --permanent

     sudo firewall-cmd --reload

     

   - Block an IP:

     sudo firewall-cmd --zone=public --add-rich-rule='rule family="ipv4" source address="10.0.0.5" reject' --permanent

     sudo firewall-cmd --reload

     

Conclusion


Network security is paramount in today's digital landscape, and RHEL provides robust tools to help you fortify your systems against potential threats. Firewalld simplifies the process of managing firewalls, allowing you to create rules, manage zones, and ensure that only authorized traffic reaches your networked systems. Whether you're dealing with basic configurations, zone setups, port allowances, or advanced rich rules, RHEL 7 and 8 offer a comprehensive range of options to enhance your network security posture.


Remember, effective network security is an ongoing process. Regularly reviewing and updating your firewall rules will help you adapt to new threats and ensure that your systems remain well-protected. So, dive into the world of RHEL firewalls, implement best practices, and take control of your network security.

Sunday, August 27, 2023

Linux Permissions: Understanding the Heart of Security in Linux


Introduction

In the field of operating systems, Linux stands out not only for its open-source nature but also for its robust security model. At the core of this security lies the intricate web of Linux permissions. If you've ever found yourself bewildered by the strings of letters and numbers attached to files and directories, fear not! In this blog, we will unravel the mystery behind Linux permissions, helping you grasp their significance and master their management.


Understanding the Basics

At its essence, Linux permissions govern the access rights that users and groups have over files and directories. These permissions are pivotal in maintaining the security and integrity of the system. Every file and directory is associated with three key permission categories: read, write, and execute, denoted by the letters r, w, and x, respectively.


1. Read (r): Allows the user to view the content of a file or the names of files within a directory.

2. Write (w): Grants the user the authority to modify the content of a file or create, delete, and rename files within a directory.

3. Execute (x): Enables the user to execute a file or traverse through a directory. For directories, execute permission is crucial for accessing its contents.


Permission Groups

Linux categorizes permissions into three groups: owner, group, and others.


1. Owner: The user who created the file or directory becomes its owner. The owner's permissions determine what actions they can perform on the file.

2. Group: Files and directories can belong to a specific group. Users within that group inherit the group's permissions.

3. Others: This group encompasses all other users who are neither the owner nor part of the group associated with the file or directory.


Permission Notation


When listing permissions, Linux employs a notation that combines letters and symbols:

- rwx: Indicates that read, write, and execute permissions are granted.

- r--: Denotes that only read permission is granted.

- -wx: Implies that write and execute permissions are granted, but not read.

Moreover, numerical values are used to represent these permissions:

R = 4: Read permission

W = 2: Write permission

X = 1: Execute permission

By summing these values, you can represent different combinations of permissions. For instance, 7 signifies read (4) + write (2) + execute (1) permissions.

  • Owner: rwx = 4+2+1 = 7
  • Group:  r--   = 4+0+0 = 4
  • Others: r--   = 4+0+0 = 4


Viewing Permissions

ls -l  test 

ls -ld /home


Changing Permissions

Linux offers two main methods to alter permissions: symbolic notation and octal notation.


1. Symbolic Notation: This approach involves using commands like `chmod` followed by symbols like `+` or `-` to add or remove permissions, respectively. For example, `chmod u+w file.txt` grants the owner (`u`) write permission.

Command examples 

chmod u+x /filename                # to give execute permission to user on file  

chmod  g+rwx /foldername      # to give read,write,execute permission to group on folder 

chmod  o+w  -R /foldername   # to give write permission to others on folder 

chmod  ugo-x /filename          # to remove execute permission from user,group,others on file            

-R is used to for recursive 


2. Octal Notation: With this method, you assign a three-digit octal number to represent the permissions for owner, group, and others. For instance, `chmod 755 script.sh` sets read, write, and execute permissions for the owner, and read and execute permissions for the group and others.


Command examples 


chmod 755 /filename 

chmod 755 /foldername 

chmod 775 -R /foldername 


-R is used to for recursive 


Conclusion


Linux permissions are the bedrock of system security, ensuring that only authorized users can access, modify, and execute files and directories. By understanding the three permission categories, the permission groups, and the notation systems, you're equipped to navigate and manage Linux permissions effectively. Remember, a solid grasp of permissions not only empowers you as a user but also reinforces the security of your Linux environment. So, dive in, explore, and elevate your Linux expertise!

Saturday, August 26, 2023

10 rsync command examples in Linux | rsync command in Linux

10 examples of  `rsync` commands in Linux that cover a range of use cases:


1. Basic Local Copy:

   Copy files and directories from one location to another on the same machine.

   rsync -av /source/path/ /destination/path/

   

2. Local Copy with Progress:

   Copy with progress indicator showing the transfer progress.

   rsync -av --progress /source/path/ /destination/path/

   

3. Copy to Remote Servers (SSH):

   Copy files to remote servers using SSH.

   rsync -avz  /source/path/ user@destination:/destination/path/

   

4. Exclude Files/Directories:

   Copy while excluding specific files or directories.

   rsync -av --exclude='file.txt' --exclude='dir/' /source/path/ /destination/path/

   

5. Sync Two Directories:

   Synchronize two directories, making the destination an exact copy of the source.

   rsync -av --delete /source/path/  /destination/path/

   

   

6. Copy from Remote with SSH and Port:

   Copy from remote servers using SSH and specifying a custom SSH port.

   rsync -avz -e "ssh -p 2222" user@source:/source/path/   /destination/path/

   

7. Dry Run (Simulation):

   Perform a dry run to see what would be transferred without actually copying.

   rsync -av --dry-run /source/path/ /destination/path/

   

8. Copy Only Newer Files:

   Copy only newer or updated files.

   rsync -av --update /source/path/ /destination/path/

   

9. Bandwidth Limitation:

    Copy with a specific bandwidth limit to avoid overloading the network.

    rsync -avz --bwlimit=1000 /source/path/ user@destination:/destination/path/

    

10 - Copying with a specific SSH key 

rsync -avz -e "ssh -i id_rsa.pem" user@source:/source/path/   /destination/path/


Options 

-a  or --archive : archive mode; equals -rlptgoD (no -H,-A,-X) 

-v or --verbose : increase verbosity

-p  or --perms   : This option causes the receiving rsync to set                  the destination permissions to be the same as
                the source permissions

-u or --update  : skip files that are newer on the receiver

-P is equivalent to --partial --progress

Remember to adapt these commands to your specific paths, usernames, and hostnames as needed. Always exercise caution, especially when working with commands that involve deletions or remote transfers.

10 scp command example in Linux | How to copy files from remote server in Linux

10 examples of `scp` (secure copy) commands in Linux, along with explanations for each:


1. Copy a local file to a remote server:

scp /path/to/local/file.txt  user@remote-server:/path/on/remote/

This command copies the local `file.txt` to the remote server at the specified path.


2. Copy a remote file to a local directory:

scp user@remote-server:/path/to/remote/file.txt /path/on/local/

This command copies the remote `file.txt` to the local directory at the specified path.


3. Copy an entire directory to a remote server:

scp -r /path/to/local/directory/ user@remote-server:/path/on/remote/

The `-r` flag indicates recursive copying, allowing you to copy the entire local directory to the remote server.


4. Copy a remote directory to a local directory:

scp -r user@remote-server:/path/to/remote/directory/ /path/on/local/

Similar to the previous example, this command copies a remote directory to a local directory using the `-r` flag.


5. Copying with a specific SSH key:

scp -i /path/to/private/key.pem /path/to/local/file.txt user@remote-server:/path/on/remote/

If you want to use a specific private key for the SSH connection, you can use the `-i` flag followed by the path to the private key.


6. Copying using a specific port:

scp -P 2222 /path/to/local/file.txt user@remote-server:/path/on/remote/

The `-P` flag specifies the port to be used for the SSH connection. In this example, the port is set to `2222`.


7. Copying multiple files with a wildcard:

scp /path/to/local/*.txt user@remote-server:/path/on/remote/

You can use wildcards like `*` to match multiple files and copy them to the remote server.


8. Copying with progress information:

scp -r /path/to/local/directory/ user@remote-server:/path/on/remote/ -v

The `-v` flag adds verbose output, showing the progress of the copy operation.


9. Copying between two remote servers:

scp user@source-server:/path/to/source/file.txt user@destination-server:/path/on/destination/

You can use `scp` to directly transfer files between two remote servers.


10. Copying with compression:

scp -rC /path/to/local/directory/ user@remote-server:/path/on/remote/

The `-C` flag enables compression during the copy process, which can speed up the transfer of large files or directories.


Remember to replace `/path/to/local` and similar placeholders with the actual paths you want to use in your specific scenarios, and replace `user`, `remote-server`, and other placeholders with your actual remote server details.

Monday, August 14, 2023

How to create swap file in Linux | How to increase swap partition in RHEL/CentOS

 To create a swap file in Red Hat Enterprise Linux 8 (RHEL 8) or any other
  Linux 
distribution, you can follow these steps:

  • Check Current Swap Usage (Optional): Before creating a new swap file, you might want to check your current swap usage. You can use the free or swapon command to do this:
    bash

    free -h 

    swapon -s

  • Determine Swap File Size: Decide on the size of the swap file you want to create. The size of the swap file depends on factors such as the amount of RAM you have and your specific needs. A common recommendation is to set the swap size to be equal to or slightly larger than your system's RAM.

  • Create the Swap File: Open a terminal and use the following commands to create a swap file. Replace <swapfile_path> with the actual path where you want to create the swap file (e.g., /mnt/swapfile), and <swapfile_size> with the desired size in megabytes (e.g., 2048M for 2GB):
    bash
     
    dd if=/dev/zero of=<swapfile_path> bs=1M count=<swapfile_size>

    Example:

    dd if=/dev/zero of=/mnt/swapfile bs=1M count=2048

  • Adjust Permissions: Set appropriate permissions on the swap file to ensure it's accessible only by the root user:
    bash

    sudo chmod 600 <swapfile_path>

    Example:

    sudo chmod 600 /mnt/swapfile

  • Configure the Swap File: Set up the swap file using the mkswap command:
    bash

    sudo mkswap <swapfile_path>

    Example:

    sudo mkswap /mnt/swapfile

  • Enable the Swap File: Activate the swap file using the swapon command:
    bash

    sudo swapon <swapfile_path>

    Example:

    sudo swapon /mnt/swapfile

  • Make Swap Permanent (Optional): To ensure that the swap file is enabled after system reboots, you need to add an entry to the /etc/fstab file. Open the file in a text editor:
    bash

    sudo nano /etc/fstab


    Add the following line to the file, where <swapfile_path> is the path of your swap file:
    php

    <swapfile_path> swap swap defaults 0 0

    Example:

    /mnt/swapfile swap swap defaults 0 0


    Save and close the file.

  • Verify Swap: You can verify that the swap file is being used by checking the output of the free or swapon command again:
    bash

    free -h

    swapon -s

That's it! You have successfully created a swap file on your Red Hat Enterprise Linux 8 or any Linux flavoured system. Remember that using swap space can impact performance, so it's recommended to have an appropriate balance of RAM and swap based on your system's needs.

Saturday, August 12, 2023

Head Command Example in Linux | How to Use Head Command in Linux

The `head` command in Linux is used to display the beginning lines of a text file. By default, it displays the first 10 lines of a file, but you can specify the number of lines you want to display using the `-n` option. Here are some examples:


1. Display the first 10 lines of a file (default behavior):
   
   head filename.txt
   
2. Display a specific number of lines (e.g., first 20 lines):
   
    head -n 20 filename.txt
   
3. Display the first few lines of multiple files:
   
     head file1.txt file2.txt
   
4. Display the first 5 lines of all `.log` files in a directory:
   
      head -n 5 *.log
   
5. Display the first 15 lines of a remote file using SSH:
   
      ssh user@hostname "head -n 15 /path/to/remote/file.txt"
   
Remember that the `head` command is used to display the beginning lines of a file. If you want to view the ending lines, you can use the `tail` command.


Friday, August 11, 2023

Tail Command Example in Linux | How to Use Tail Command in Linux


The tail command in Linux is used to display the last few lines of a text file. By default, it displays the last 10 lines of a file, but you can specify the number of lines you want to display using the `-n` option. Here are some examples:

1. Display the last 10 lines of a file (default behavior):
   
 tail filename.txt
   
2. Display a specific number of lines from the end of a file (e.g., last 20 lines):
   
tail -n 20 filename.txt
   
3. Display the last few lines of multiple files:
   
tail file1.txt file2.txt
   
4. Display the last 5 lines of all .log files in a directory:
   
tail -n 5 *.log
   
5. Display the last 15 lines of a remote file using SSH:
  
 ssh user@hostname "tail -n 15 /path/to/remote/file.txt"
   
6. Display the last lines of a file and continuously update as new lines are added (useful for log files):
   
tail -f filename.log
   
Remember that the tail command is used to display the ending lines of a file. If you want to view the beginning lines, you can use the `head` command.

Thursday, August 10, 2023

AWS CLI Examples on Linux | AWS CLI



  1. List all S3 buckets:

    aws s3 ls

  2. Upload a file to an S3 bucket:

    aws s3 cp local-file.txt s3://bucket-name/

  3. Download a file from an S3 bucket:
    aws s3 cp s3://bucket-name/remote-file.txt local-file.txt
  4. Sync local directory to an S3 bucket (upload only changed files): aws s3 sync local-dir s3://bucket-name/
  5. Delete a file from an S3 bucket:
    aws s3 rm s3://bucket-name/remote-file.txt
  6. List all EC2 instances:
    aws ec2 describe-instances
  7. Start an EC2 instance:
    aws ec2 start-instances --instance-ids i-1234567890abcdef0
  8. Stop an EC2 instance:
    aws ec2 stop-instances --instance-ids i-1234567890abcdef0
  9. Create an RDS database instance: 
    aws rds create-db-instance --db-instance-identifier mydbinstance --engine mysql --db-instance-class db.t2.micro --allocated-storage 20 --master-username admin --master-user-password mysecretpassword
  10. List all Lambda functions:

    aws lambda list-functions

  11. Invoke a Lambda function:

    aws lambda invoke --function-name my-function --payload '{"key": "value"}' output.json


  12. Create a new SNS topic:
    aws sns create-topic --name my-topic aws sns subscribe --topic-arn arn:aws:sns:us-west-2:123456789012:my-topic --protocol email --notification-endpoint my-email@example.com
  13. List all SQS queues:
    aws sqs send-message --queue-url https://sqs.us-west-2.amazonaws.com/123456789012/my-queue --message-body "Hello, AWS!"

  14. Create a new DynamoDB table:
    aws dynamodb create-table --table-name my-table --attribute-definitions AttributeName=id,AttributeType=S --key-schema AttributeName=id,KeyType=HASH --provisioned-throughput ReadCapacityUnits=5,WriteCapacityUnits=5
  15. List all CloudFront distributions:
    aws cloudfront list-distributions
  16. Create a CloudFront invalidation:
    aws cloudfront create-invalidation --distribution-id E1A2B3C4D5E6F7 --paths /path1/* /path2/*
  17. List all IAM users:
    aws iam list-users
  18. Create a new IAM user: aws iam create-user --user-name my-user



Tuesday, August 8, 2023

How to Optimize PostgreSQL database server | Optimizing of a PostgreSQL database server

Optimizing a PostgreSQL database server involves several aspects, including database design, configuration settings, query optimization, and performance monitoring. Here are some steps you can take to optimize your PostgreSQL database server:


1. Database Design:

   - Ensure your database schema is well-designed with appropriate normalization and
      indexing to minimize redundant data and improve query performance.

   - Use appropriate data types for columns to minimise storage and improve query efficiency.


2. Hardware and System Resources:

   - Choose hardware that meets the performance requirements of your workload, including
     CPU, memory, and storage.

   - Use fast and reliable storage solutions (SSDs are generally preferred over HDDs) to
      reduce I/O latency.


3. Configuration Settings:

   - Adjust PostgreSQL's configuration settings in the `postgresql.conf` file to match your
     hardware and workload. Key parameters to consider include `shared_buffers`,
     `work_mem`, `effective_cache_size`, and `maintenance_work_mem`.

   - Regularly review and adjust these parameters based on your database's usage patterns and
      performance metrics.


4. Indexing:

   - Create indexes on columns that are frequently used in WHERE clauses, JOINs, and
     ORDER BY clauses.

   - Be cautious with over-indexing, as it can slow down write operations.


5. Query Optimization:

   - Write efficient queries that utilize indexes and minimize unnecessary joins and subqueries.

   - Use the `EXPLAIN` command to analyze query execution plans and identify performance
      bottlenecks.

   - Optimize slow queries by adding appropriate indexes, rewriting queries, or partitioning
     large tables.


6. Vacuum and Analyze:

   - PostgreSQL's automatic vacuum process helps manage table bloat and maintains index
      performance.

   - Regularly monitor and analyze the need for manual vacuuming based on the
      `pg_stat_user_tables` and
 `pg_stat_user_indexes` system views.


7. Connection Pooling:

   - Use a connection pooling solution to efficiently manage database connections and reduce
     the overhead of establishing new connections for each query.


8. Caching:

   - Implement caching mechanisms, such as using the built-in `pgBouncer`, to reduce the load
     on the database server and improve response times for frequently accessed data.


9. Monitoring and Tuning:

   - Use monitoring tools like `pg_stat_activity`, `pg_stat_statements`, and third-party tools like
     PgHero or pgAdmin to track database performance and identify bottlenecks.

   - Regularly analyze query performance and server metrics to make informed tuning
     decisions.


10. Backup and Maintenance:

    - Implement regular backups and test the restore process to ensure data integrity and disaster
      recovery readiness.

    - Schedule routine maintenance tasks like vacuuming, analyze, and index rebuilds during
      off-peak hours.


11. Version Updates:

    - Keep your PostgreSQL version up to date to take advantage of performance
      improvements, bug fixes, and new features.


Remember that database optimization is an ongoing process that requires continuous monitoring, analysis, and adjustments based on changing workloads and usage patterns. It's also recommended to thoroughly test any changes in a non-production environment before applying them to a live database.

Saturday, August 5, 2023

What is Linux Operating System | What is Linux

Linux is a free and open-source operating system (OS) based on the Unix family of operating systems. It was initially created by Linus Torvalds in 1991 and has since become one of the most widely used operating systems, especially in the server and embedded systems domains.



The key features of Linux include:


Open Source: Linux is distributed under various open-source licenses, which means that its source code is freely available for anyone to view, modify, and distribute. This fosters a collaborative community of developers who continuously contribute to its development and improvement.


Kernel: The Linux kernel is the core component of the operating system. It manages hardware resources and provides essential services that enable other programs to run on the system.


Distributions: Linux comes in various distributions or "distros," which are different packaged versions of the operating system. Each distribution includes the Linux kernel along with various software packages, utilities, and a package manager for easy software installation and updates. Some popular Linux distributions include Ubuntu, Debian, Fedora, CentOS, and Arch Linux.


Multiuser and Multitasking: Linux is designed to support multiple users simultaneously and enables multitasking, allowing users to run multiple applications concurrently.


Command Line Interface (CLI) and Graphical User Interface (GUI): Linux provides both a command-line interface and a graphical user interface, giving users the flexibility to choose the method they prefer for interacting with the system.


Security: Linux is known for its robust security features. It has a strong permission-based model that controls access to files and resources, reducing the risk of unauthorized access and malicious attacks.


Stability and Performance: Linux is known for its stability and performance, making it a popular choice for servers, supercomputers, and other high-performance computing systems.


Device Support: Linux has extensive hardware support, making it compatible with a wide range of devices, including computers, smartphones, servers, routers, and IoT devices.


Overall, Linux's open-source nature, versatility, and community-driven development model have made it a powerful and reliable choice for various computing needs, ranging from personal computers to enterprise-level servers.




Mastering Cron Jobs in Linux: A Comprehensive Guide with Examples

Introduction: Cron jobs are an indispensable tool in the world of system administration and automation. They allow users to schedule tasks t...