<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Shravanth Gelli on Medium]]></title>
        <description><![CDATA[Stories by Shravanth Gelli on Medium]]></description>
        <link>https://medium.com/@kgelli?source=rss-95a5fd5f9cb2------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*_M8F60djVfO9RRAkN3i0Og.jpeg</url>
            <title>Stories by Shravanth Gelli on Medium</title>
            <link>https://medium.com/@kgelli?source=rss-95a5fd5f9cb2------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 07:23:56 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@kgelli/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Managing AWS EC2 Instances with Python Boto3: A Practical Guide]]></title>
            <link>https://medium.com/@kgelli/managing-aws-ec2-instances-with-python-boto3-a-practical-guide-5cd074926166?source=rss-95a5fd5f9cb2------2</link>
            <guid isPermaLink="false">https://medium.com/p/5cd074926166</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[automation]]></category>
            <dc:creator><![CDATA[Shravanth Gelli]]></dc:creator>
            <pubDate>Fri, 03 Jan 2025 21:59:34 GMT</pubDate>
            <atom:updated>2025-01-03T21:59:34.874Z</atom:updated>
            <content:encoded><![CDATA[<p>In today’s cloud-driven world, automation is key to efficient infrastructure management. As an AWS practitioner, I want to share how you can programmatically manage EC2 instances using Python and the Boto3 library through imperative automation. This guide will walk you through the essentials of creating and terminating EC2 instances programmatically using an imperative approach, where we explicitly define each step of the process.</p><p>Understanding Imperative Automation: Imperative automation involves writing step-by-step instructions that explicitly tell the system what to do and how to do it. This differs from declarative approaches (like using AWS CloudFormation or Terraform) where you specify the desired end state. With imperative automation, we have direct control over each action and can handle complex workflows, though it requires more detailed coding and explicit error handling.</p><h3>Prerequisites</h3><ul><li>An AWS account with appropriate IAM permissions</li><li>Python 3.x installed</li><li>Basic understanding of AWS EC2 service</li><li>Boto3 library (pip install boto3)</li><li>Configured AWS credentials</li></ul><h3>Setting Up Boto3</h3><p>First, let’s set up our Python environment with Boto3. Here’s how to create an EC2 client:</p><pre>import boto3<br><br># Create EC2 client<br>ec2_client = boto3.client(&#39;ec2&#39;,<br>    region_name=&#39;us-west-2&#39;,  # Specify your desired region<br>    aws_access_key_id=&#39;YOUR_ACCESS_KEY&#39;,      # Optional if using AWS CLI credentials<br>    aws_secret_access_key=&#39;YOUR_SECRET_KEY&#39;   # Optional if using AWS CLI credentials<br>)</pre><h3>Launching an EC2 Instance</h3><p>Here’s a comprehensive script to launch an EC2 instance:</p><pre>def launch_ec2_instance():<br>    try:<br>        # Launch an instance<br>        response = ec2_client.run_instances(<br>            ImageId=&#39;ami-0735c191cf914754d&#39;,  # Amazon Linux 2 AMI ID (update as needed)<br>            InstanceType=&#39;t2.micro&#39;,<br>            MinCount=1,<br>            MaxCount=1,<br>            SecurityGroupIds=[&#39;sg-xxxxxxxxxxxxxxxxx&#39;],  # Replace with your security group ID<br>            SubnetId=&#39;subnet-xxxxxxxxxxxxxxxxx&#39;,        # Replace with your subnet ID<br>            TagSpecifications=[<br>                {<br>                    &#39;ResourceType&#39;: &#39;instance&#39;,<br>                    &#39;Tags&#39;: [<br>                        {<br>                            &#39;Key&#39;: &#39;Name&#39;,<br>                            &#39;Value&#39;: &#39;MyPythonInstance&#39;<br>                        },<br>                        {<br>                            &#39;Key&#39;: &#39;Environment&#39;,<br>                            &#39;Value&#39;: &#39;Development&#39;<br>                        }<br>                    ]<br>                }<br>            ]<br>        )<br>        <br>        instance_id = response[&#39;Instances&#39;][0][&#39;InstanceId&#39;]<br>        print(f&quot;Successfully launched EC2 instance: {instance_id}&quot;)<br>        return instance_id<br>        <br>    except Exception as e:<br>        print(f&quot;Error launching EC2 instance: {str(e)}&quot;)<br>        return None</pre><p>Sample output when successfully launching an instance:</p><pre>Successfully launched EC2 instance: i-0a1b2c3d4e5f67890</pre><p>Sample output when encountering an error (e.g., insufficient permissions):</p><pre>Error launching EC2 instance: An error occurred (UnauthorizedOperation) when calling the RunInstances operation: You are not authorized to perform this operation.</pre><h3>Terminating an EC2 Instance</h3><p>Here’s how to safely terminate an EC2 instance:</p><pre>def terminate_ec2_instance(instance_id):<br>    try:<br>        # Terminate the instance<br>        response = ec2_client.terminate_instances(<br>            InstanceIds=[instance_id]<br>        )<br>        <br>        terminating_instances = response[&#39;TerminatingInstances&#39;]<br>        for instance in terminating_instances:<br>            print(f&quot;Terminating instance {instance[&#39;InstanceId&#39;]}&quot;)<br>            print(f&quot;Current state: {instance[&#39;CurrentState&#39;][&#39;Name&#39;]}&quot;)<br>            print(f&quot;Previous state: {instance[&#39;PreviousState&#39;][&#39;Name&#39;]}&quot;)<br>            <br>        return True<br>        <br>    except Exception as e:<br>        print(f&quot;Error terminating EC2 instance: {str(e)}&quot;)<br>        return False</pre><p>Sample output when successfully terminating an instance:</p><pre>Terminating instance i-0a1b2c3d4e5f67890<br>Current state: shutting-down<br>Previous state: running</pre><p>Sample output when instance doesn’t exist:</p><pre>Error terminating EC2 instance: An error occurred (InvalidInstanceID.NotFound) when calling the TerminateInstances operation: The instance ID &#39;i-0a1b2c3d4e5f67890&#39; does not exist</pre><h3>Best Practices and Considerations</h3><ol><li><strong>Resource Management</strong>: Always tag your instances appropriately for better resource tracking and cost allocation.</li><li><strong>Error Handling</strong>: Implement robust error handling to manage API failures and network issues gracefully.</li><li><strong>Security</strong>: Never hardcode AWS credentials in your scripts. Use AWS CLI profiles or environment variables instead.</li><li><strong>Cost Control</strong>: Remember to terminate instances when they’re no longer needed to avoid unnecessary charges.</li></ol><h3>Putting It All Together</h3><p>Here’s a complete example showing how to use these functions:</p><pre>if __name__ == &quot;__main__&quot;:<br>    # Launch a new instance<br>    instance_id = launch_ec2_instance()<br>    <br>    if instance_id:<br>        print(&quot;Waiting for 5 minutes while instance runs...&quot;)<br>        time.sleep(300)  # Wait for 5 minutes<br>        <br>        # Terminate the instance<br>        if terminate_ec2_instance(instance_id):<br>            print(&quot;Instance terminated successfully&quot;)<br>        else:<br>            print(&quot;Failed to terminate instance&quot;)</pre><p>Sample output of complete script execution:</p><pre>Successfully launched EC2 instance: i-0a1b2c3d4e5f67890<br>Waiting for 5 minutes while instance runs...<br>Terminating instance i-0a1b2c3d4e5f67890<br>Current state: shutting-down<br>Previous state: running<br>Instance terminated successfully</pre><h3>Monitoring Instance Status</h3><p>You can also check the status of your instances:</p><pre>def get_instance_status(instance_id):<br>    response = ec2_client.describe_instances(<br>        InstanceIds=[instance_id]<br>    )<br>    <br>    for reservation in response[&#39;Reservations&#39;]:<br>        for instance in reservation[&#39;Instances&#39;]:<br>            return instance[&#39;State&#39;][&#39;Name&#39;]</pre><h3>Advantages and Limitations of Imperative Automation</h3><h3>Advantages:</h3><ul><li>Fine-grained control over each step of the process</li><li>Ability to implement complex conditional logic</li><li>Real-time feedback and error handling</li><li>Flexibility to handle dynamic requirements</li><li>Direct interaction with AWS APIs</li></ul><h3>Limitations:</h3><ul><li>More verbose compared to declarative approaches</li><li>Requires maintaining state manually</li><li>Need for explicit error handling</li><li>Can be more challenging to scale across large infrastructures</li></ul><h3>Conclusion</h3><p>Automating EC2 instance management with Python and Boto3 using an imperative approach can significantly streamline your AWS operations. While this method requires more explicit coding compared to declarative tools like CloudFormation or Terraform, it offers greater control and flexibility. This approach is particularly valuable for tasks like:</p><ul><li>Automated testing environments</li><li>Development workspace management</li><li>Scheduled batch processing</li><li>Dynamic scaling operations</li></ul><p>Remember to always follow AWS best practices and keep your credentials secure. The power of automation comes with the responsibility of careful resource management.</p><p>Feel free to connect with me for more cloud automation insights and AWS best practices!</p><p>#AWS #Python #CloudComputing #DevOps #Automation #Boto3 #EC2 #CloudTechnology</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5cd074926166" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Hotstar’s AWS Cloud Success Story: Scaling for Cricket World Cup 2019]]></title>
            <link>https://medium.com/@kgelli/hotstars-aws-cloud-success-story-scaling-for-cricket-world-cup-2019-eea86b7acac5?source=rss-95a5fd5f9cb2------2</link>
            <guid isPermaLink="false">https://medium.com/p/eea86b7acac5</guid>
            <category><![CDATA[innovation]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[streaming]]></category>
            <category><![CDATA[scaling]]></category>
            <category><![CDATA[engineering]]></category>
            <dc:creator><![CDATA[Shravanth Gelli]]></dc:creator>
            <pubDate>Fri, 03 Jan 2025 21:32:00 GMT</pubDate>
            <atom:updated>2025-01-03T21:48:29.277Z</atom:updated>
            <content:encoded><![CDATA[<p>As a cloud engineer, I feel immensely proud to share this remarkable achievement in cloud computing. What Hotstar accomplished during the 2019 Cricket World Cup isn’t just a technical milestone — it’s a testament to how cloud technology is revolutionizing the way we experience digital content. This case study showcases the true potential of cloud architecture when pushed to its limits. 🚀 #CloudEngineering #AWS #TechInnovation</p><h3>Executive Summary</h3><p>In 2019, Hotstar achieved a remarkable feat by successfully streaming the Cricket World Cup to over 25 million concurrent viewers, setting a global record for concurrent video streaming. This case study examines how AWS Cloud infrastructure enabled this unprecedented scale and transformed Hotstar’s streaming capabilities.</p><h3>The Challenge</h3><p>The platform faced what can only be described as a “viewer tsunami” — an unprecedented surge that saw viewer numbers explode from 5 million to 25 million within minutes, creating massive waves of concurrent requests across the infrastructure.</p><ul><li>Handle massive concurrent viewership during high-stakes cricket matches</li><li>Ensure low latency and high-quality streaming across diverse network conditions</li><li>Scale infrastructure dynamically to manage unpredictable viewer spikes</li><li>Maintain platform stability during peak loads</li><li>Optimize costs while delivering premium streaming experience</li></ul><h3>AWS Solution Implementation</h3><h3>Infrastructure Setup</h3><p>Hotstar leveraged multiple AWS services to create a robust streaming architecture:</p><ul><li>Amazon EC2 for compute resources</li><li>Amazon CloudFront for content delivery</li><li>Amazon ElastiCache for session management</li><li>AWS Auto Scaling for dynamic resource allocation</li><li>Amazon DynamoDB for real-time data management</li></ul><h3>Key Technical Innovations</h3><p>The heart of Hotstar’s success lay in its innovative technical implementation. Their auto-scaling architecture incorporated predictive scaling based on historical patterns, while custom scaling policies were crafted for different microservices, complemented by AWS Lambda for serverless computing during peak loads. Content delivery was optimized through strategic deployment of CloudFront edge locations across India, coupled with adaptive bitrate streaming and video encoding optimized for various device types and network conditions. The platform’s sophisticated real-time analytics leveraged Amazon Kinesis for data processing, backed by comprehensive monitoring and alerting systems, while machine learning algorithms helped predict viewership patterns and optimize resource allocation. This technical foundation proved crucial in handling the massive scale of concurrent viewers while maintaining performance and user experience.</p><h3>Performance Metrics</h3><ul><li>Achieved 25.3 million concurrent viewers during India vs New Zealand match</li><li>Maintained video latency under 5 seconds</li><li>Achieved 99.99% platform availability</li><li>Handled 15,000 events per second at peak</li></ul><h3>Business Impact</h3><p>The AWS implementation delivered exceptional business results across multiple dimensions. The platform achieved substantial cost optimization, reducing infrastructure expenses by 50% compared to traditional setups, while the pay-as-you-go model eliminated the need for permanent infrastructure investment. User experience saw dramatic improvements, with buffering reduced by 97% and video start-up time decreased by 74%, alongside consistently higher stream quality across varying network conditions. These achievements significantly strengthened Hotstar’s position as India’s leading streaming platform, setting new global benchmarks for video streaming and enhancing its reputation for technical excellence.</p><h3>Key Learnings</h3><p>The World Cup streaming success yielded valuable insights that continue to shape the industry’s approach to large-scale video streaming. The implementation highlighted the critical importance of microservices architecture in achieving seamless scalability, alongside the fundamental value of automated scaling policies in managing unpredictable loads. Edge computing emerged as a crucial factor in video delivery optimization, while comprehensive real-time monitoring and analytics proved indispensable for maintaining service quality.</p><p>Experience from this implementation emphasized several essential best practices for similar large-scale streaming projects. Robust capacity planning proved to be the foundation of success, complemented by comprehensive testing strategies that anticipated various load scenarios. The team’s focus on end-user experience metrics guided technical decisions effectively, while maintaining a flexible architecture allowed for quick scaling when needed. These learnings have since become guiding principles for streaming platforms worldwide tackling similar scaling challenges.</p><h3>Industry Impact and Legacy</h3><p>This case study marked a turning point in the streaming industry, becoming a blueprint that transformed how platforms approach large-scale streaming events. Following Hotstar’s success, streaming services worldwide began adopting similar cloud architectures and scaling strategies. The impact reverberated throughout the industry, visible in subsequent Olympics broadcasts, FIFA World Cup streams, global eSports tournaments, and even major entertainment events like season finales and movie premieres.</p><p>The technical architecture pioneered by Hotstar — with its sophisticated auto-scaling, edge computing, and microservices approach — became a gold standard. Streaming platforms, both regional and global, studied and implemented these patterns for their own high-stakes broadcasts. The case demonstrated that with proper cloud architecture, concurrent viewership limits could be pushed far beyond what was previously thought possible.</p><p>Today, modern streaming platforms consider this architecture a foundational element when building scalable services. The lessons learned from this implementation continue to influence how streaming services approach infrastructure scaling, making this case study not just a historical milestone, but a living blueprint for future innovations in the streaming space.</p><h3>Conclusion</h3><p>The successful handling of Cricket World Cup 2019 demonstrated how cloud infrastructure can enable streaming platforms to achieve unprecedented scale while maintaining performance and cost-effectiveness. Hotstar’s implementation serves as a blueprint for other organizations looking to achieve similar results.</p><p><em>Note: This case study is based on publicly available information about Hotstar’s AWS implementation during the 2019 Cricket World Cup. For the most current information, please refer to official AWS and Hotstar sources.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eea86b7acac5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Monitoring System Memory Usage with Shell Script]]></title>
            <link>https://medium.com/@kgelli/monitoring-system-memory-usage-with-shell-script-683d950aecd6?source=rss-95a5fd5f9cb2------2</link>
            <guid isPermaLink="false">https://medium.com/p/683d950aecd6</guid>
            <category><![CDATA[linux]]></category>
            <category><![CDATA[bash]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[monitoring]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Shravanth Gelli]]></dc:creator>
            <pubDate>Mon, 23 Dec 2024 13:06:06 GMT</pubDate>
            <atom:updated>2024-12-23T14:14:57.259Z</atom:updated>
            <content:encoded><![CDATA[<p>Memory monitoring is crucial for maintaining system health and performance. In this tutorial, we’ll create a shell script to monitor memory usage percentage in Linux systems, including tracking top memory-consuming processes. This script will help you keep track of your system’s memory consumption and identify resource-intensive processes.</p><h3>Understanding Memory Usage in Linux</h3><p>Before diving into the script, let’s understand how Linux reports memory usage. The memory information in Linux is stored in the /proc/meminfo file, which contains detailed statistics about system memory usage, including:</p><ul><li>Total Memory (MemTotal): Total amount of physical RAM</li><li>Free Memory (MemFree): Completely unused memory</li><li>Available Memory (MemAvailable): Memory available for new applications</li><li>Buffers: Memory used for buffering file reads</li><li>Cached Memory: Memory used for caching file contents</li></ul><p>The percentage calculation in our script uses:</p><pre>Memory Usage % = ((Total Memory - Available Memory) / Total Memory) × 100</pre><p>We use Available Memory instead of Free Memory because it’s a more accurate representation of memory that could be used by applications. Available Memory includes Free Memory plus memory that can be reclaimed from buffers and cache.</p><h3>Configuration of the Script</h3><p>Update these values at the top of the script:</p><pre>EMAIL=&quot;your_email@example.com&quot;    # Your email address<br>THRESHOLD=90                      # Memory threshold percentage<br>LOG_FILE=&quot;mem_report.tsv&quot;        # Log file location</pre><p>These settings control:</p><ul><li>EMAIL: Where alerts will be sent</li><li>THRESHOLD: When alerts should be triggered (90% by default)</li><li>LOG_FILE: Where to store the monitoring history</li></ul><h3>Creating the Memory Monitoring Script</h3><p>Here’s our shell script that calculates and displays memory usage percentage and monitors top processes:</p><pre>#!/bin/bash<br><br># Configuration<br>EMAIL=&quot;your_email@example.com&quot;<br>THRESHOLD=90<br>LOG_FILE=&quot;mem_report.tsv&quot;<br><br># Ensure proper path for cron execution<br>PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin<br>export PATH<br><br># Create TSV header if file doesn&#39;t exist<br>if [ ! -f &quot;$LOG_FILE&quot; ]; then<br>    echo -e &quot;Timestamp\tMemory_Usage(%)\tAlert_Status&quot; &gt; &quot;$LOG_FILE&quot;<br>fi<br><br># Function to calculate memory usage percentage<br>get_memory_usage() {<br>    local mem_total=$(grep &#39;MemTotal&#39; /proc/meminfo | awk &#39;{print $2}&#39;)<br>    local mem_available=$(grep &#39;MemAvailable&#39; /proc/meminfo | awk &#39;{print $2}&#39;)<br>    local mem_used=$((mem_total - mem_available))<br>    local usage_percentage=$(awk &quot;BEGIN {printf \&quot;%.2f\&quot;, ($mem_used * 100)/$mem_total}&quot;)<br>    echo &quot;$usage_percentage&quot;<br>}<br><br># Function to get top memory consuming processes<br>get_top_processes() {<br>    ps aux --sort=-%mem | head -n 6 | tail -n 5 | awk &#39;{print $11&quot;:&quot;$4&quot;%&quot;}&#39; | tr &#39;\n&#39; &#39;|&#39;<br>}<br><br># Function to log to TSV<br>log_to_tsv() {<br>    local usage=$1<br>    local alert_status=$2<br>    local timestamp=$(date &#39;+%Y-%m-%d %H:%M:%S&#39;)<br>    echo -e &quot;${timestamp}\t${usage}\t${alert_status}&quot; &gt;&gt; &quot;$LOG_FILE&quot;<br>}<br><br># Function to speak alert<br>speak_alert() {<br>    local usage=$1<br>    if command -v espeak-ng &gt;/dev/null 2&gt;&amp;1; then<br>        espeak-ng &quot;Warning! Memory usage is at ${usage}percent&quot;<br>    else<br>        echo &quot;Please install espeak for audio alerts&quot;<br>    fi<br>}<br><br># Function to send email alert<br>send_email_alert() {<br>    local usage=$1<br>    local subject=&quot;Memory Alert: High Usage Detected&quot;<br>    local top_procs=$(get_top_processes)<br>    <br>    local message=&quot;Warning: Memory usage is at ${usage}%\n\n&quot;<br>    message+=&quot;Top Memory-Consuming Processes (Process:Memory%):\n&quot;<br>    message+=&quot;${top_procs}&quot;<br>    <br>    echo -e &quot;$message&quot; | mail -s &quot;$subject&quot; &quot;$EMAIL&quot;<br>}<br><br># Main script execution<br>memory_usage=$(get_memory_usage)<br><br># Check threshold and trigger alerts<br>if (( $(echo &quot;$memory_usage &gt; $THRESHOLD&quot; | bc -l) )); then<br>    alert_status=&quot;ALERT&quot;<br>    send_email_alert &quot;$memory_usage&quot;<br>    speak_alert &quot;$memory_usage&quot;<br>    echo &quot;Alert email sent! Memory usage: ${memory_usage}%&quot;<br>else<br>    alert_status=&quot;OK&quot;<br>    echo &quot;Memory usage: ${memory_usage}%&quot;<br>fi<br><br># Log to TSV file<br>log_to_tsv &quot;$memory_usage&quot; &quot;$alert_status&quot;<br>echo &quot;Memory usage logged to $LOG_FILE&quot;</pre><h3>How the Script Works</h3><p>Let’s break down the key components:</p><p><strong>Memory Usage Calculation</strong>: Uses /proc/meminfo to calculate total and available memory.</p><p><strong>Process Monitoring</strong>: The get_top_processes() function:</p><ul><li>Lists all processes sorted by memory usage</li><li>Extracts the top 5 memory consumers</li><li>Formats output as “process_name:memory_percentage”</li></ul><p><strong>Alert System</strong>:</p><ul><li>Email alerts with process information</li><li>Audio alerts using espeak-ng</li><li>TSV logging for historical tracking</li></ul><h3>Output Examples</h3><p>When running the script normally:</p><pre>$ ./memory_monitor.sh<br>Memory usage: 72.45%<br>Memory usage logged to mem_report.tsv</pre><p>When memory exceeds threshold:</p><pre>$ ./memory_monitor.sh<br>Alert email sent! Memory usage: 92.33%<br>Memory usage logged to mem_report.tsv<br>[Voice Alert]: &quot;Warning! Memory usage is at 92.33 percent&quot;</pre><p>Sample TSV log file content:</p><pre>$ cat mem_report.tsv<br>Timestamp               Memory_Usage(%)    Alert_Status<br>2024-12-23 14:00:00    72.45             OK<br>2024-12-23 15:00:00    92.33             ALERT<br>2024-12-23 16:00:00    85.67             OK</pre><p>Email alert example:</p><pre>Subject: Memory Alert: High Usage Detected<br>From: system@yourdomain.com<br>To: your_email@example.com<br><br>Warning: Memory usage is at 92.33%<br><br>Top Memory-Consuming Processes (Process:Memory%):<br>chrome:15.2%|firefox:8.5%|mysql:6.7%|nodejs:4.2%|python:3.8%|</pre><h3>Setting Up Automated Monitoring</h3><p>To automate the memory monitoring, set up a cron job:</p><ul><li>Open crontab in edit mode:</li></ul><pre>crontab -e</pre><ul><li>Add this line in the crontab editor:</li></ul><pre>0 * * * * /path/to/memory_monitor.sh</pre><ul><li>Save and exit the editor (usually :wq in vim or Ctrl+X in nano).</li><li>Verify the cron job:</li></ul><pre>$ crontab -l<br># Memory monitoring job<br>0 * * * * /path/to/memory_monitor.sh<br><br># Check if cron service is running<br>$ systemctl status cron<br>● cron.service - Regular background program processing daemon<br>     Loaded: loaded (/lib/systemd/system/cron.service; enabled)<br>     Active: active (running) since Mon 2024-12-23 12:00:00 UTC; 4h ago<br><br># Check cron logs<br>$ grep CRON /var/log/syslog | tail -n 3<br>Dec 23 14:00:01 hostname CRON[1234]: (user) CMD (/path/to/memory_monitor.sh)<br>Dec 23 15:00:01 hostname CRON[1235]: (user) CMD (/path/to/memory_monitor.sh)<br>Dec 23 16:00:01 hostname CRON[1236]: (user) CMD (/path/to/memory_monitor.sh)</pre><h3>Dependencies Installation</h3><p>Before running the script, ensure you have the required dependencies:</p><pre># For Debian/Ubuntu<br>sudo apt-get install sendmail espeak-ng bc<br><br># For Red Hat/CentOS<br>sudo yum install sendmail espeak-ng bc</pre><h3>Conclusion</h3><p>This shell script provides a comprehensive memory monitoring solution that not only tracks overall memory usage but also identifies the top memory-consuming processes. The combination of email alerts, audio notifications, and TSV logging makes it a powerful tool for system administrators and users who need to keep a close eye on their system’s memory usage.</p><p>The addition of process monitoring helps quickly identify which applications might be causing memory issues, allowing for faster problem resolution and better system management.</p><p>Feel free to modify and enhance the script according to your requirements!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=683d950aecd6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Essential Linux System Administration Projects: Infrastructure and Services (Part 2)]]></title>
            <link>https://medium.com/@kgelli/essential-linux-system-administration-projects-infrastructure-and-services-part-2-c0f8a35622d5?source=rss-95a5fd5f9cb2------2</link>
            <guid isPermaLink="false">https://medium.com/p/c0f8a35622d5</guid>
            <category><![CDATA[security]]></category>
            <category><![CDATA[linux]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Shravanth Gelli]]></dc:creator>
            <pubDate>Mon, 23 Dec 2024 09:18:39 GMT</pubDate>
            <atom:updated>2024-12-23T09:18:39.671Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>Building upon our security foundations from Part 1, this blog explores four critical infrastructure and service management projects. These projects focus on web server configuration, user privileges, group management, and system identification — essential skills for any Linux system administrator.</p><h3>Project 1: Basic HTTPD Web Server Configuration</h3><h3>Problem Statement</h3><p>Organizations need to deploy and secure web servers while ensuring proper access and configuration management.</p><h3>Detailed Solution</h3><p>Install and configure Apache HTTPD:</p><pre># Install Apache<br>$ sudo yum install httpd<br><br># Start and enable the service<br>$ sudo systemctl start httpd<br>$ sudo systemctl enable httpd</pre><p>Configure firewall:</p><pre># Allow HTTP traffic<br>$ sudo firewall-cmd --permanent --add-service=http<br>success<br>$ sudo firewall-cmd --reload<br>success</pre><p>Create a test webpage:</p><pre>$ sudo vi /var/www/html/index.html</pre><p>Content:</p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html&gt;<br>&lt;head&gt;<br>    &lt;title&gt;Test Page&lt;/title&gt;<br>&lt;/head&gt;<br>&lt;body&gt;<br>    &lt;h1&gt;HTTPD Server Test Page&lt;/h1&gt;<br>    &lt;p&gt;If you can see this, your HTTPD server is working!&lt;/p&gt;<br>&lt;/body&gt;<br>&lt;/html&gt;</pre><p>Expected Outputs:</p><pre># Check service status<br>$ sudo systemctl status httpd<br>● httpd.service - The Apache HTTP Server<br>     Loaded: loaded (/usr/lib/systemd/system/httpd.service; enabled)<br>     Active: active (running) since Thu 2024-12-21 09:00:15 EDT</pre><p>Testing:</p><pre># Test local access<br>$ curl http://localhost<br>&lt;html&gt;<br>&lt;head&gt;<br>    &lt;title&gt;Test Page&lt;/title&gt;<br>...<br><br># Check firewall configuration<br>$ sudo firewall-cmd --list-services<br>dhcpv6-client http ssh</pre><h3>Explanation</h3><p>The configuration:</p><ul><li>Installs and enables Apache HTTPD</li><li>Configures firewall rules for secure access</li><li>Sets up a basic test page</li><li>Enables service persistence across reboots</li></ul><h3>Project 2: Sudoer User for Limited Privileges</h3><h3>Problem Statement</h3><p>Organizations need to grant specific administrative privileges to users without providing full root access.</p><h3>Detailed Solution</h3><p>Create a new administrative user:</p><pre># Add new user<br>$ sudo useradd -m webadmin<br>$ sudo passwd webadmin</pre><p>Configure sudo privileges:</p><pre>$ sudo visudo -f /etc/sudoers.d/webadmin</pre><p>Content:</p><pre># Allow webadmin to manage HTTPD service<br>webadmin ALL=(ALL) /usr/bin/systemctl status httpd<br>webadmin ALL=(ALL) /usr/bin/systemctl restart httpd<br>webadmin ALL=(ALL) /usr/bin/systemctl start httpd<br>webadmin ALL=(ALL) /usr/bin/systemctl stop httpd</pre><p>Expected Output:</p><pre># Test as webadmin user<br>$ su - webadmin<br>$ sudo systemctl status httpd<br>● httpd.service - The Apache HTTP Server<br>     Active: active (running)<br>     <br># Test unauthorized command<br>$ sudo systemctl status firewalld<br>Sorry, user webadmin is not allowed to execute &#39;/usr/bin/systemctl status firewalld&#39; as root on localhost.</pre><h3>Explanation</h3><p>This setup:</p><ul><li>Creates a dedicated service management user</li><li>Limits sudo access to specific commands</li><li>Maintains security through restricted privileges</li><li>Enables service management without root access</li></ul><h3>Project 3: Group Management for Shared Files</h3><h3>Problem Statement</h3><p>Teams need shared access to specific files and directories with appropriate permissions.</p><h3>Detailed Solution</h3><p>Create group and shared directory:</p><pre># Create group<br>$ sudo groupadd webteam<br><br># Create shared directory<br>$ sudo mkdir -p /var/www/shared</pre><p>Configure permissions:</p><pre># Set ownership and permissions<br>$ sudo chown -R root:webteam /var/www/shared<br>$ sudo chmod 2775 /var/www/shared</pre><p>Add users to group:</p><pre># Add users to webteam<br>$ sudo usermod -aG webteam user1<br>$ sudo usermod -aG webteam user2</pre><p>Expected Output:</p><pre># Check directory permissions<br>$ ls -la /var/www/shared<br>drwxrwsr-x. 2 root webteam 4096 Dec 21 10:00 .<br><br># Verify group membership<br>$ groups user1<br>user1 : user1 webteam</pre><p>Testing:</p><pre># Test file creation as user1<br>$ su - user1<br>$ touch /var/www/shared/test.html<br>$ ls -l /var/www/shared/test.html<br>-rw-rw-r--. 1 user1 webteam 0 Dec 21 10:05 test.html</pre><h3>Explanation</h3><p>This configuration:</p><ul><li>Creates a shared group for web team members</li><li>Sets appropriate directory permissions</li><li>Maintains file ownership while enabling group collaboration</li><li>Implements SGID for consistent group ownership</li></ul><h3>Project 4: Static Hostname Configuration</h3><h3>Problem Statement</h3><p>Systems need consistent identification across network reboots and restarts.</p><h3>Detailed Solution</h3><p>Configure static hostname:</p><pre># Set hostname<br>$ sudo hostnamectl set-hostname webserver.example.com<br><br># Update hosts file<br>$ sudo vi /etc/hosts</pre><p>Add:</p><pre>127.0.0.1   webserver.example.com webserver</pre><p>Verify configuration:</p><pre># Check current settings<br>$ sudo hostnamectl</pre><p>Expected Output:</p><pre>$ hostnamectl<br>   Static hostname: webserver.example.com<br>         Icon name: computer-vm<br>           Chassis: vm<br>        Machine ID: 1234567890abcdef1234567890abcdef<br>           Boot ID: 0123456789abcdef0123456789abcdef<br>    Virtualization: kvm<br>  Operating System: Red Hat Enterprise Linux 8.5<br>       CPE OS Name: cpe:/o:redhat:enterprise_linux:8.5:GA<br>            Kernel: Linux 4.18.0-348.el8.x86_64</pre><p>Test persistence:</p><pre># Reboot system<br>$ sudo reboot<br><br># Verify hostname after reboot<br>$ hostname<br>webserver.example.com</pre><h3>Explanation</h3><p>This setup ensures:</p><ul><li>Consistent system identification</li><li>Proper DNS resolution</li><li>Persistence across system reboots</li><li>Standardized naming convention</li></ul><h3>Conclusion</h3><p>The four infrastructure projects covered in Part 2 showcase essential aspects of Linux system administration: web server deployment, privileged access management, collaborative resource sharing, and system identification. Each project addresses common challenges faced in enterprise environments while building upon the security foundations established in Part 1.</p><p>Through these implementations, we’ve explored:</p><ul><li>Systematic web server configuration with HTTPD</li><li>Granular privilege management through sudo</li><li>Effective group-based resource sharing</li><li>Robust system identification management</li></ul><p>Key takeaways include:</p><ul><li>The importance of proper service configuration and monitoring</li><li>Implementing principle of least privilege in user access</li><li>Effective resource sharing through group management</li><li>Maintaining consistent system identification across reboots</li></ul><p>Remember that these solutions serve as a foundation and should be adapted to your organization’s specific needs. Regular review and updates of these configurations ensure they continue to meet evolving infrastructure requirements.</p><p>Together with Part 1, these projects provide a comprehensive foundation for Linux system administration, preparing administrators for the challenges of modern IT environments.</p><blockquote><em>“The art of system administration lies not just in implementing solutions, but in creating sustainable, manageable, and secure infrastructures that support organizational goals.”</em></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c0f8a35622d5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Essential Linux System Administration Projects: Security and Access Control (Part 1)]]></title>
            <link>https://medium.com/@kgelli/essential-linux-system-administration-projects-security-and-access-control-part-1-cc6a6e1c57ed?source=rss-95a5fd5f9cb2------2</link>
            <guid isPermaLink="false">https://medium.com/p/cc6a6e1c57ed</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[linux]]></category>
            <category><![CDATA[security]]></category>
            <dc:creator><![CDATA[Shravanth Gelli]]></dc:creator>
            <pubDate>Mon, 23 Dec 2024 09:18:01 GMT</pubDate>
            <atom:updated>2024-12-23T09:18:01.457Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>In modern enterprise environments, Linux systems form the backbone of infrastructure, making robust security and access control critical. This blog post provides hands-on solutions with detailed explanations and expected outputs for essential security projects.</p><h3>Project 1: Configuring Secure SSH Access</h3><h3>Problem Statement</h3><p>In production environments, SSH access must be tightly controlled to prevent unauthorized access while maintaining efficiency for legitimate users.</p><h3>Detailed Solution</h3><p>First, let’s check SSHstatus and modify the SSH configuration:</p><pre>$ systemctl status sshd<br>● sshd.service - OpenSSH server daemon<br>   Loaded: loaded (/usr/lib/systemd/system/sshd.service; enabled)<br>   Active: active (running) since Mon 2024-12-20 09:00:15 UTC<br><br>$ sudo vi /etc/ssh/sshd_config</pre><p>Add these security-focused configurations:</p><pre># Allow only specific users<br>AllowUsers user1 user2<br><br># Disable root login<br>PermitRootLogin no<br><br># Use SSH protocol 2<br>Protocol 2<br><br># Set authentication preferences<br>PasswordAuthentication yes<br>PubkeyAuthentication yes</pre><p>Restart SSH and verify:</p><pre>$ sudo systemctl restart sshd<br>$ sudo systemctl status sshd<br>● sshd.service - OpenSSH server daemon<br>     Loaded: loaded (/usr/lib/systemd/system/sshd.service; enabled)<br>     Active: active (running) since Wed 2024-12-20 10:30:15 UTC</pre><p>Testing Access (expected outputs):</p><pre># Successful login attempt<br>$ ssh user1@hostname<br>user1@hostname&#39;s password: <br>Last login: Wed Dec 20 10:25:33 2024 from 192.168.1.100<br><br># Failed login attempt<br>$ ssh user3@hostname<br>user3@hostname&#39;s password: <br>Permission denied, please try again.</pre><h3>Explanation</h3><p>The configuration achieves multiple security objectives:</p><ul><li>Restricts SSH access to specific users (user1, user2)</li><li>Disables root login for enhanced security</li><li>Enforces SSH Protocol 2 for stronger encryption</li><li>Maintains password authentication while allowing future key-based auth implementation</li></ul><h3>Project 2: Centralized Logs Management</h3><h3>Problem Statement</h3><p>Organizations need a secure, centralized location for logs with proper access controls to maintain audit trails.</p><h3>Detailed Solution</h3><p>Creating and configuring the central logs directory:</p><pre>$ sudo mkdir /central_logs<br>$ sudo chmod 1777 /central_logs<br>$ sudo chown root:root /central_logs</pre><p>Test user setup and verification:</p><pre># Create test users<br>$ sudo useradd -m user1<br>$ sudo useradd -m user2<br><br># Set passwords<br>$ sudo passwd user1<br>$ sudo passwd user2</pre><p>Expected Directory Listing:</p><pre>$ ls -la /central_logs<br>total 12<br>drwxrwxrwt. 2 root  root  4096 Dec 20 11:00 .<br>drwxr-xr-x. 19 root  root  4096 Dec 20 11:00 ..<br>-rw-r--r--. 1 user1 user1   9 Dec 20 11:01 user1.log<br>-rw-r--r--. 1 user2 user2   10 Dec 20 11:02 user2.log</pre><p>Testing Access Controls:</p><pre># User1 creating a log<br>$ su - user1<br>$ echo &quot;test log&quot; &gt; /central_logs/user1.log<br>$ ls -l /central_logs/user1.log<br>-rw-r--r--. 1 user1 user1 9 Dec 20 11:01 user1.log<br><br># User2 attempting to delete user1&#39;s log<br>$ su - user2<br>$ rm /central_logs/user1.log<br>rm: cannot remove &#39;/central_logs/user1.log&#39;: Operation not permitted<br>$ echo &quot;Test log from user2&quot; &gt; /central_logs/user2.log</pre><p>Verify directory contents:</p><pre>$ ls -la /central_logs/<br>total 8<br>drwxrwxrwt 2 root  root   60 Dec 20 09:25 .<br>drwxr-xr-x 3 root  root   20 Dec 20 09:15 ..<br>-rw-r--r-- 1 user1 user1  24 Dec 20 09:20 user1.log<br>-rw-r--r-- 1 user2 user2  19 Dec 20 09:25 user2.log</pre><h3>Explanation</h3><p>The solution implements:</p><ul><li>Sticky bit (1777) prevents users from deleting others’ files</li><li>Universal write access allows all users to create logs</li><li>Root ownership ensures administrative control</li><li>File ownership retention maintains accountability</li></ul><h3>Project 3: ACL Implementation</h3><h3>Problem Statement</h3><p>Standard Unix permissions are often insufficient for complex access requirements. ACLs provide more granular control.</p><h3>Detailed Solution</h3><ol><li>Setting up ACLs:</li></ol><pre># Install ACL package<br>$ sudo yum install acl<br><br># Create test file<br>$ touch /shared/test_file<br>$ chmod 640 test_file<br><br># Set ACL permissions<br>$ setfacl -m u:user1:r /shared/test_file<br>$ setfacl -m u:user2:rw /shared/test_file</pre><p>Expected ACL Output:</p><pre>$ getfacl /shared/test_file<br># file: test_file<br># owner: root<br># group: root<br>user::rw-<br>user:user1:r--<br>user:user2:rw-<br>group::r--<br>mask::rw-<br>other::---</pre><p>Testing Access:</p><pre># User1 testing read access<br>$ su - user1<br>$ cat /shared/test_file<br>This is a test file<br>$ echo &quot;append test&quot; &gt;&gt; /shared/test_file<br>bash: /shared/test_file: Permission denied<br><br># User2 testing read/write access<br>$ su - user2<br>$ echo &quot;append test&quot; &gt;&gt; /shared/test_file<br>$ cat /shared/test_file<br>This is a test file<br>append test</pre><h3>Explanation</h3><p>The ACL configuration:</p><ul><li>Provides read-only access to user1</li><li>Grants read-write access to user2</li><li>Maintains base Unix permissions</li><li>Allows for granular permission management</li></ul><h3>Project 4: Automated System Backups</h3><h3>Problem Statement</h3><p>Regular system backups are crucial for disaster recovery and system maintenance.</p><h3>Detailed Solution</h3><ol><li>Create backup script:</li></ol><pre>$ sudo vi /usr/local/bin/backup.sh</pre><p>Script content:</p><pre>#!/bin/bash<br>BACKUP_DIR=&quot;/backup&quot;<br>DATE=$(date +%Y%m%d)<br>BACKUP_FILE=&quot;$BACKUP_DIR/system_backup_$DATE.tar.gz&quot;<br><br># Create backup directory if it doesn&#39;t exist<br>mkdir -p $BACKUP_DIR<br><br># Create backup<br>tar -czf $BACKUP_FILE /etc /var/log<br><br># Output backup status<br>echo &quot;Backup completed: $BACKUP_FILE&quot;<br>echo &quot;Size: $(du -h $BACKUP_FILE | cut -f1)&quot;</pre><ol><li>Configure automated execution:</li></ol><pre># Make script executable<br>$ sudo chmod +x /usr/local/bin/backup.sh<br><br># Add to crontab<br>$ sudo crontab -e<br>0 0 * * * /usr/local/bin/backup.sh</pre><p>Expected Output:</p><pre>$ sudo /usr/local/bin/backup.sh<br>Backup completed: /backup/system_backup_20241220.tar.gz<br>Size: 156M<br><br>$ ls -lh /backup<br>total 156M<br>-rw-r--r--. 1 root root 156M Dec 20 00:00 system_backup_20241220.tar.gz</pre><h3>Explanation</h3><p>The backup solution provides:</p><ul><li>Daily automated backups at midnight</li><li>Compression to save space</li><li>Date-stamped files for easy tracking</li><li>Status output for monitoring</li><li>Critical system files preservation</li></ul><h3>Conclusion</h3><p>These Linux system administration projects provide a solid foundation in security and access control management. The hands-on experience gained through implementing these solutions helps develop crucial skills needed in enterprise environments. The projects demonstrate the importance of:</p><ul><li>Systematic approach to security implementation</li><li>Proper documentation and testing</li><li>Balance between security and usability</li><li>Automated solutions for routine tasks</li></ul><p>Remember that security is an ongoing process, not a one-time implementation. Regular audits, updates, and improvements to these configurations should be part of your system administration routine. As you implement these solutions in your environment, always consider:</p><ol><li>The specific requirements of your organization</li><li>Compliance and regulatory requirements</li><li>Scalability of the solution</li><li>Maintenance overhead</li><li>Documentation and knowledge transfer</li></ol><p>The skills and knowledge gained from these projects serve as building blocks for more advanced system administration tasks and provide a strong foundation for enterprise-level Linux administration.</p><p>Stay tuned for Part 2 of this series, where we’ll explore infrastructure and service management projects that build upon these fundamental security concepts.</p><blockquote><strong>“Security is not a product, but a process.” — Bruce Schneier</strong></blockquote><p>This quote perfectly encapsulates the continuous nature of system administration and security management in modern IT environments.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cc6a6e1c57ed" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Linux Administration: Essential Commands and Solutions (Part 3 of 3)]]></title>
            <link>https://medium.com/@kgelli/mastering-linux-administration-essential-commands-and-solutions-part-3-of-3-e30f93cfc183?source=rss-95a5fd5f9cb2------2</link>
            <guid isPermaLink="false">https://medium.com/p/e30f93cfc183</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[linux]]></category>
            <category><![CDATA[monitoring]]></category>
            <category><![CDATA[security]]></category>
            <category><![CDATA[identity-management]]></category>
            <dc:creator><![CDATA[Shravanth Gelli]]></dc:creator>
            <pubDate>Sun, 22 Dec 2024 09:29:29 GMT</pubDate>
            <atom:updated>2024-12-22T09:29:29.348Z</atom:updated>
            <content:encoded><![CDATA[<p>Welcome to the final part of our Linux administration series! In this installment, we’ll cover five advanced Linux scenarios focusing on alias management, disk usage monitoring, repository configuration, log tracking, and file security.</p><h3>11. Alias Management and Recovery</h3><p><strong>Problem Statement:</strong><br> A Linux user accidentally deletes an alias and wants to restore it.</p><p><strong>Task:</strong><br> Remove the alias ll, verify it is removed, and then restore it by adding it permanently to the bash configuration file.</p><p><strong>Solution and Explanation:</strong><br> Alias management is crucial for productivity and command customization:</p><pre># First, check if the alias exists<br>$ alias ll<br>alias ll=&#39;ls -la&#39;<br><br># Remove the alias<br>$ unalias ll<br><br># Verify removal<br>$ alias ll<br>-bash: alias: ll: not found<br><br># Add alias permanently to .bashrc<br>$ echo &quot;alias ll=&#39;ls -la&#39;&quot; &gt;&gt; ~/.bashrc<br><br># Reload bash configuration<br>$ source ~/.bashrc<br><br># Verify the restored alias<br>$ alias ll<br>alias ll=&#39;ls -la&#39;<br><br># Test the alias<br>$ ll<br>total 32<br>drwxr-xr-x 4 user user 4096 Dec 20 13:00 .<br>drwxr-xr-x 3 user user 4096 Dec 20 13:00 ..<br>-rw-r--r-- 1 user user  220 Dec 20 12:55 .bash_logout<br>-rw-r--r-- 1 user user 3526 Dec 20 12:55 .bashrc<br>-rw-r--r-- 1 user user  807 Dec 20 12:55 .profile</pre><p><strong>Understanding alias management:</strong></p><ol><li>unalias removes temporary aliases</li><li>~/.bashrc stores permanent aliases</li><li>source reloads shell configuration</li><li>Changes to .bashrc persist across sessions</li></ol><p><strong>Best practices:</strong></p><ul><li>Back up important aliases</li><li>Document custom aliases</li><li>Use meaningful alias names</li><li>Avoid overriding system commands</li></ul><h3>12. Disk Usage Monitoring</h3><p><strong>Problem Statement:</strong><br> A system administrator wants to check disk usage.</p><p><strong>Task:</strong><br> Write a command to display the disk usage of all mounted filesystems in a human-readable format. Save the output to disk_usage_report.txt.</p><p><strong>Solution and Explanation:</strong><br> Monitoring disk usage is crucial for system maintenance:</p><pre># Display and save disk usage information<br>$ df -h | tee disk_usage_report.txt<br>Filesystem      Size  Used Avail Use% Mounted on<br>/dev/sda1        30G   15G   14G  52% /<br>/dev/sda2       100G   60G   35G  63% /home<br>tmpfs           4.0G  0.0G  4.0G   0% /tmp<br>/dev/sdb1       500G  200G  300G  40% /data<br><br># Get detailed directory usage<br>$ du -sh /* 2&gt;/dev/null | tee -a disk_usage_report.txt<br>1.2G    /bin<br>4.0K    /boot<br>128M    /etc<br>2.1G    /home<br>350M    /lib<br>...<br><br># Monitor disk space threshold<br>$ df -h | awk &#39;$5 &gt;= &quot;80&quot; {print $0}&#39;</pre><p><strong>Understanding disk monitoring commands:</strong></p><p>df -h options:</p><ul><li>-h for human-readable sizes</li><li>Shows filesystem-level usage</li></ul><p>du -sh options:</p><ul><li>-s for summary</li><li>-h for human-readable sizes</li></ul><p>tee allows viewing and saving output simultaneously</p><p><strong>Why this approach is effective:</strong></p><ul><li>Provides both overview and detailed information</li><li>Human-readable format makes reports accessible</li><li>Error redirection prevents clutter</li><li>Can be automated for regular monitoring</li></ul><h3>13. Repository Configuration</h3><p><strong>Problem Statement:</strong><br> A server requires a new repository configuration.</p><p><strong>Task:</strong><br> Create a YUM repository configuration file named custom.repo in /etc/yum.repos.d/ and configure it with a base URL of your choice. Verify that the repository is available.</p><p><strong>Solution and Explanation:</strong><br> Proper repository configuration ensures reliable package management:</p><pre># Create the repository configuration file<br>$ sudo tee /etc/yum.repos.d/custom.repo &lt;&lt; EOF<br>[custom-repo]<br>name=Custom Repository<br>baseurl=http://mirror.example.com/repo<br>enabled=1<br>gpgcheck=1<br>gpgkey=http://mirror.example.com/repo/RPM-GPG-KEY<br>EOF<br><br># Verify the configuration<br>$ cat /etc/yum.repos.d/custom.repo<br>[custom-repo]<br>name=Custom Repository<br>baseurl=http://mirror.example.com/repo<br>enabled=1<br>gpgcheck=1<br>gpgkey=http://mirror.example.com/repo/RPM-GPG-KEY<br><br># Clean and update repository cache<br>$ sudo dnf clean all<br>$ sudo dnf repolist<br>Repo ID      Name                      Status<br>custom-repo  Custom Repository         enabled<br>base         CentOS-9 - Base          enabled<br>updates      CentOS-9 - Updates       enabled<br><br># Test repository availability<br>$ sudo dnf repository-packages custom-repo list</pre><p><strong>Understanding repository configuration:</strong></p><p>Configuration file components:</p><ul><li>[repo-id]: Unique identifier</li><li>name: Description</li><li>baseurl: Package source</li><li>enabled: Repository status</li><li>gpgcheck: Security verification</li></ul><p><strong>Security considerations:</strong></p><ul><li>Always verify GPG keys</li><li>Use secure URLs (https)</li><li>Regular repository updates</li><li>Monitor for compromised mirrors</li></ul><h3>14. System Log Monitoring</h3><p><strong>Problem Statement:</strong><br> A user wants to track system logs for debugging.</p><p><strong>Task:</strong><br> Display the last 50 lines of the system log file /var/log/messages. Ensure the output updates in real-time as new logs are added.</p><p><strong>Solution and Explanation:</strong><br> Effective log monitoring is crucial for system troubleshooting:</p><pre># View last 50 lines and follow updates<br>$ sudo tail -n 50 -f /var/log/messages<br>Dec 20 14:00:01 hostname systemd: Started Daily tasks<br>Dec 20 14:00:05 hostname kernel: USB device detected<br>Dec 20 14:00:10 hostname sshd[1234]: Accepted publickey for user<br>Dec 20 14:00:15 hostname nginx: 192.168.1.100 - GET /index.html<br><br># Save logs with timestamp<br>$ sudo tail -n 50 -f /var/log/messages | while read line; do<br>    echo &quot;$(date &#39;+%Y-%m-%d %H:%M:%S&#39;) $line&quot; &gt;&gt; debug_logs.txt<br>done<br><br># Search for specific events<br>$ sudo grep &quot;error&quot; /var/log/messages | tail -n 20</pre><p><strong>Understanding log monitoring:</strong></p><p>tail -f options:</p><ul><li>-n specifies line count</li><li>-f follows file updates</li></ul><p>Real-time processing with while read</p><p>Timestamp addition for better tracking</p><p><strong>Best practices:</strong></p><ul><li>Regular log rotation</li><li>Pattern-based monitoring</li><li>Alert configuration</li><li>Log backup strategy</li></ul><h3>15. Sticky Bit Implementation</h3><p><strong>Problem Statement:</strong><br> A developer needs to secure a file with a sticky bit.</p><p><strong>Task:</strong><br> Create a directory named shared_docs and set the sticky bit so that only the owner of a file can delete it. Verify the sticky bit using ls -ld.</p><p><strong>Solution and Explanation:</strong><br> Sticky bit provides additional security for shared directories:</p><pre># Create directory<br>$ mkdir shared_docs<br><br># Set permissions and sticky bit<br>$ chmod 1777 shared_docs<br><br># Verify settings<br>$ ls -ld shared_docs<br>drwxrwxrwt 2 user user 4096 Dec 20 14:30 shared_docs<br><br># Test file creation and deletion<br>$ sudo -u user1 touch shared_docs/file1.txt<br>$ sudo -u user2 touch shared_docs/file2.txt<br><br># Try deletion as different user<br>$ sudo -u user2 rm shared_docs/file1.txt<br>rm: cannot remove &#39;shared_docs/file1.txt&#39;: Operation not permitted</pre><p><strong>Understanding sticky bit:</strong></p><p>Permission breakdown:</p><ul><li>1 sets sticky bit</li><li>777 gives full permissions</li></ul><p>t in permissions string indicates sticky bit</p><p>Prevents deletion by non-owners</p><p>Maintains file ownership integrity</p><p><strong>Security implications:</strong></p><ul><li>Protects against unauthorized deletion</li><li>Maintains file ownership control</li><li>Allows shared write access</li><li>Preserves directory structure</li></ul><h3>Best Practices and Tips</h3><ol><li>Regular log analysis and rotation</li><li>Repository security verification</li><li>Disk usage monitoring automation</li><li>Document custom configurations</li><li>Regular security audits</li></ol><h3>Series Conclusion</h3><p>Throughout this three-part series, we’ve covered essential Linux administration tasks ranging from basic user management to advanced security configurations. Remember that system administration is an ongoing learning process, and staying updated with best practices and security measures is crucial.</p><p>Key takeaways from the series:</p><ol><li>Always verify commands before execution</li><li>Document system changes</li><li>Implement proper security measures</li><li>Monitor system resources</li><li>Maintain regular backups</li></ol><p><em>Follow me for more Linux administration tips and best practices!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e30f93cfc183" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Linux Administration: Essential Commands and Solutions (Part 2 of 3)]]></title>
            <link>https://medium.com/@kgelli/mastering-linux-administration-essential-commands-and-solutions-part-2-of-3-d1e2f748a433?source=rss-95a5fd5f9cb2------2</link>
            <guid isPermaLink="false">https://medium.com/p/d1e2f748a433</guid>
            <category><![CDATA[data]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[identity-management]]></category>
            <category><![CDATA[security]]></category>
            <category><![CDATA[linux]]></category>
            <dc:creator><![CDATA[Shravanth Gelli]]></dc:creator>
            <pubDate>Sat, 21 Dec 2024 13:13:31 GMT</pubDate>
            <atom:updated>2024-12-21T13:13:31.237Z</atom:updated>
            <content:encoded><![CDATA[<p>Welcome back to our Linux administration series! In this second installment, we’ll explore five more essential Linux scenarios that system administrators commonly encounter. Let’s dive into shell management, data sharing, and file operations.</p><h3>6. Shell Management and Switching</h3><p><strong>Problem Statement:</strong><br> A developer needs to switch between multiple shells for testing purposes.</p><p><strong>Task:</strong><br> Switch to the bash shell, list the current shell, and then switch back to sh. Confirm the shell changes using appropriate commands.</p><p><strong>Solution and Explanation:</strong><br> Shell switching is important for testing scripts and ensuring compatibility. Here’s how to manage it:</p><pre># Check current shell<br>$ echo $SHELL<br>/bin/sh<br><br># Switch to bash<br>$ bash<br>$ echo $SHELL<br>/bin/bash<br><br># Verify bash version<br>$ bash --version<br>GNU bash, version 5.1.16(1)-release (x86_64-pc-linux-gnu)<br>Copyright (C) 2020 Free Software Foundation, Inc.<br>License GPLv3+: GNU GPL version 3 or later<br><br># Switch back to sh<br>$ exec sh<br>$ echo $SHELL<br>/bin/sh</pre><p><strong>Why this approach works:</strong></p><ol><li>echo $SHELL shows the current shell path</li><li>Using bash command starts a new bash shell instance</li><li>exec sh replaces the current shell with sh, rather than creating a subshell</li><li>The shell version information helps verify the environment</li></ol><p><strong>Best practices:</strong></p><ul><li>Use exec when completely switching shells to avoid nested shell sessions</li><li>Be aware of shell-specific features when switching</li><li>Document shell requirements for scripts and applications</li></ul><h3>7. Secure Team Data Sharing</h3><p><strong>Problem Statement:</strong><br> A company needs to ensure secure data sharing among team members.</p><p><strong>Task:</strong><br> Create a directory named team_share and set permissions so that all members of the group project_team can read, write, and execute files in the directory, but others have no access.</p><p><strong>Solution and Explanation:</strong><br> Secure group collaboration requires proper directory permissions:</p><pre># Create the directory<br>$ mkdir team_share<br><br># Set group ownership<br>$ sudo chown :project_team team_share<br><br># Set directory permissions (770)<br>$ chmod 770 team_share<br><br># Set the SGID bit to ensure new files inherit group ownership<br>$ chmod g+s team_share<br><br># Verify settings<br>$ ls -ld team_share<br>drwxrws--- 2 username project_team 4096 Dec 20 11:30 team_share<br><br># Create a test file<br>$ touch team_share/test.txt<br>$ ls -l team_share/test.txt<br>-rw-rw---- 1 username project_team 0 Dec 20 11:31 test.txt</pre><p><strong>Understanding the permissions:</strong></p><p>770 permissions breakdown:</p><ul><li>7 (rwx) for owner</li><li>7 (rwx) for group</li><li>0 ( — — — ) for others</li></ul><p>SGID bit (s) ensures:</p><ul><li>New files inherit the directory’s group</li><li>Maintains consistent group ownership</li></ul><p><strong>Security considerations:</strong></p><ul><li>Regular permission audits</li><li>Monitoring disk usage quotas</li><li>Backup strategies for shared data</li></ul><h3>8. Recent File Search</h3><p><strong>Problem Statement:</strong><br> A Linux user wants to find files modified within the last 7 days.</p><p><strong>Task:</strong><br> Write a command to search for all files in the /home directory that were modified in the last 7 days. Save the output to recent_files.txt.</p><p><strong>Solution and Explanation:</strong><br> Finding recently modified files helps track changes and manage backups:</p><pre># Search for recently modified files<br>$ find /home -type f -mtime -7 &gt; recent_files.txt<br><br># View the results<br>$ cat recent_files.txt<br>/home/user1/documents/report.doc<br>/home/user1/downloads/data.csv<br>/home/user2/projects/script.sh<br><br># Get detailed information about found files<br>$ find /home -type f -mtime -7 -ls &gt; recent_files_detailed.txt<br><br># Monitor changes in real-time<br>$ find /home -type f -mmin -60 -ls</pre><p><strong>Understanding the find command:</strong></p><ol><li>-type f specifies we want only regular files</li><li>-mtime -7 finds files modified less than 7 days ago</li><li>-mmin -60 finds files modified in the last hour</li><li>-ls provides detailed listing similar to ls -l</li></ol><p><strong>Why this approach is effective:</strong></p><ul><li>Searches recursively through directories</li><li>Handles different time ranges flexibly</li><li>Can combine with other criteria for precise searches</li><li>Output redirection creates permanent records</li></ul><h3>9. Package Management</h3><p><strong>Problem Statement:</strong><br> An administrator wants to install and manage software packages.</p><p><strong>Task:</strong><br> Install the httpd package using the dnf command. Start the service, enable it to run on boot, and verify its status.</p><p><strong>Solution and Explanation:</strong><br> Package management is crucial for system maintenance:</p><pre># Update package lists<br>$ sudo dnf update<br><br># Install httpd<br>$ sudo dnf install httpd<br>Last metadata expiration check: 0:02:38 ago<br>Dependencies resolved.<br>Installing:<br> httpd-2.4.53-7.el9.x86_64<br><br># Start the service<br>$ sudo systemctl start httpd<br><br># Enable on boot<br>$ sudo systemctl enable httpd<br>Created symlink /etc/systemd/system/multi-user.target.wants/httpd.service → /usr/lib/systemd/system/httpd.service<br><br># Check status<br>$ sudo systemctl status httpd<br>● httpd.service - The Apache HTTP Server<br>     Loaded: loaded (/usr/lib/systemd/system/httpd.service; enabled; vendor preset: disabled)<br>     Active: active (running) since Thu 2024-12-20 11:45:30 UTC;</pre><p><strong>Understanding system service management:</strong></p><ol><li>systemctl start immediately starts the service</li><li>systemctl enable configures automatic startup</li><li>systemctl status shows:</li></ol><ul><li>Service state</li><li>Process information</li><li>Recent logs</li><li>Load status</li></ul><p><strong>Best practices:</strong></p><ul><li>Always update package lists before installing</li><li>Check service logs for errors</li><li>Configure firewall rules as needed</li><li>Regular security updates</li></ul><h3>10. File Archiving and Compression</h3><p><strong>Problem Statement:</strong><br> A student is practicing file compression and archiving.</p><p><strong>Task:</strong><br> Create a tarball named project_archive.tar.gz that includes all files in the directory /home/projects. Verify the contents of the tarball without extracting it.</p><p><strong>Solution and Explanation:</strong><br> Efficient file archiving is essential for backup and distribution:</p><pre># Create the archive<br>$ tar -czvf project_archive.tar.gz /home/projects<br>/home/projects/<br>/home/projects/file1.txt<br>/home/projects/file2.txt<br>/home/projects/subfolder/<br>/home/projects/subfolder/file3.txt<br><br># List contents without extracting<br>$ tar -tvf project_archive.tar.gz<br>drwxr-xr-x user/group 0 2024-12-20 12:00 /home/projects/<br>-rw-r--r-- user/group 1234 2024-12-20 11:55 /home/projects/file1.txt<br>-rw-r--r-- user/group 5678 2024-12-20 11:56 /home/projects/file2.txt<br>drwxr-xr-x user/group 0 2024-12-20 11:57 /home/projects/subfolder/<br>-rw-r--r-- user/group 9012 2024-12-20 11:58 /home/projects/subfolder/file3.txt<br><br># Check archive integrity<br>$ gzip -t project_archive.tar.gz &amp;&amp; echo &quot;Archive is OK&quot;<br>Archive is OK</pre><p><strong>Understanding tar options:</strong></p><ol><li>-c: Create new archive</li><li>-z: Compress with gzip</li><li>-v: Verbose output</li><li>-f: Specify filename</li><li>-t: List contents</li><li>-x: Extract (when needed)</li><li>&amp;&amp; means &quot;run the next command only if this one succeeds&quot;</li></ol><p><strong>Best practices:</strong></p><ul><li>Use meaningful archive names</li><li>Include date in archive names for versioning</li><li>Verify archive integrity after creation</li><li>Document archive contents</li><li>Store archives in backed-up locations</li></ul><h3>Best Practices and Tips</h3><ol><li>Always use verbose output when creating archives</li><li>Test service configurations before enabling on boot</li><li>Document shared directory permissions</li><li>Regularly clean up old archives</li><li>Monitor service logs for issues</li></ol><h3>Coming Up Next</h3><p>In Part 3 of this series, we’ll explore the final set of Linux administration tasks, including repository management, log monitoring, and advanced file permissions. Stay tuned!</p><p><em>Follow me for more Linux administration tips and best practices!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d1e2f748a433" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Linux System Monitoring: A Comprehensive Guide to top and htop]]></title>
            <link>https://medium.com/@kgelli/linux-system-monitoring-a-comprehensive-guide-to-top-and-htop-9363b1c39d98?source=rss-95a5fd5f9cb2------2</link>
            <guid isPermaLink="false">https://medium.com/p/9363b1c39d98</guid>
            <category><![CDATA[engineering]]></category>
            <category><![CDATA[monitoring]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[linux]]></category>
            <category><![CDATA[performance]]></category>
            <dc:creator><![CDATA[Shravanth Gelli]]></dc:creator>
            <pubDate>Sat, 21 Dec 2024 13:06:59 GMT</pubDate>
            <atom:updated>2024-12-21T13:08:16.464Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>Linux system monitoring is crucial for maintaining server health and troubleshooting performance issues. In this guide, we’ll explore two essential monitoring tools: the traditional ‘top’ command and its modern successor ‘htop’.</p><h3>Part 1: Understanding top — The Traditional System Monitor</h3><h3>What is top?</h3><p>The top command is a fundamental Linux tool that provides a dynamic real-time view of system processes. It comes pre-installed on virtually every Linux distribution and has been a staple of system administration for decades.</p><h3>Basic Usage of top</h3><p>Simply type ‘top’ in your terminal:</p><pre>$ top</pre><p>Sample output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LMsqqqK8sfmwsNHvvvgpYA.png" /></figure><h3>Understanding top’s Display</h3><p>Header Information</p><ul><li>System uptime and load averages</li><li>Task summary (total, running, sleeping, stopped, zombie)</li><li>CPU usage breakdown</li><li>Memory and swap usage</li></ul><p>Process List</p><ul><li>PID: Process ID</li><li>USER: Process owner</li><li>PR: Priority</li><li>NI: Nice value</li><li>VIRT: Virtual memory</li><li>RES: Physical memory</li><li>SHR: Shared memory</li><li>%CPU: CPU usage</li><li>%MEM: Memory usage</li><li>TIME+: CPU time used</li><li>COMMAND: Command name</li></ul><h3>Essential top Commands</h3><p>Process Management</p><pre># Monitor specific process<br>top -p 1234<br><br># Monitor user&#39;s processes<br>top -u username</pre><p>Display Control</p><pre># Update every 5 seconds<br>top -d 5<br><br># Run 10 iterations<br>top -n 10<br><br># Batch mode output<br>top -b &gt; top_output.txt</pre><h3>Real-World Examples with top</h3><p>CPU Usage Monitoring</p><pre># Sort by CPU usage<br>$ top -o %CPU<br><br>Output:<br>  PID USER      PR  NI    VIRT    RES    SHR S  %CPU  %MEM     TIME+ COMMAND<br>15532 user1     20   0 4236948 346108  89988 S  98.0   4.3   85:23.76 firefox</pre><p>Memory Leak Detection</p><pre># Monitor memory usage over time<br>$ top -b -n 5 -d 10 | grep &quot;chrome&quot;<br><br>Output shows increasing memory:<br>3521 user1  20  0 3521520 285716 S  5.3  3.5  chrome<br>3521 user1  20  0 3721520 485716 S  5.3  5.5  chrome</pre><h3>Top 10 Options for top</h3><ol><li>-b: Run in batch mode (useful for sending output to other programs or files)</li><li>-n [number]: Number of iterations before exiting</li><li>-p [pid]: Monitor specific process IDs</li><li>-u [username]: Display only processes of a specific user</li><li>-d [seconds]: Set update interval</li><li>-i: Ignore idle and zombie processes</li><li>-H: Show individual threads</li><li>-o [fieldname]: Sort by specific field</li><li>-c: Show command line instead of just command name</li><li>-w: Wide output mode for larger displays</li></ol><h3>Interactive top Commands</h3><ul><li>‘k’: Kill a process</li><li>‘r’: Renice process</li><li>‘f’: Select fields</li><li>‘o’: Sort field</li><li>‘q’: Quit</li></ul><h3>Part 2: Exploring htop — The Modern Alternative</h3><h3>What is htop?</h3><p>htop is a modern, enhanced alternative to top that provides a more user-friendly interface with additional features and visual improvements.</p><h3>Installing htop</h3><pre># Ubuntu/Debian<br>sudo apt install htop<br><br># RedHat/CentOS<br>sudo yum install htop<br><br># Fedora<br>sudo dnf install htop</pre><h3>Enhanced Features in htop</h3><p>Visual Improvements</p><ul><li>Color-coded output</li><li>Per-CPU usage bars</li><li>Memory and swap meters</li><li>Process tree view</li></ul><p>User Interface</p><ul><li>Mouse support</li><li>Horizontal and vertical scrolling</li><li>Sortable columns</li><li>Visual process tree</li></ul><h3>Basic htop Usage</h3><pre># Launch htop<br>htop<br><br># Show process tree<br>htop -t<br><br># Monitor specific user<br>htop -u username</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4P3lr5mCdyJA6WvPUEgsIg.png" /></figure><h3>Real-World Examples with htop</h3><p>Process Tree Analysis</p><pre>$ htop -t<br><br>Output (Tree View):<br>  ├─ nginx (master)<br>  │  ├─ nginx (worker)<br>  │  ├─ nginx (worker)<br>  │  └─ nginx (worker)</pre><p>Resource Usage Investigation</p><pre>$ htop -s PERCENT_MEM<br><br>Visual Display:<br>[|||||||||||||||   45.7%] CPU<br>[||||||||||||||||  56.3%] Memory<br>[|||||||||        28.1%] Swap</pre><h3>Top 10 Options for htop</h3><ol><li>-d [seconds]: Set update delay</li><li>-u [username]: Show only processes of a specific user</li><li>-p [pid]: Show only specified processes</li><li>-s [column]: Sort by specified column</li><li>-t: Enable tree view by default</li><li>-C: Enable monochrome mode</li><li>-h: Display help message</li><li>-v: Print version information</li><li>-n [number]: Update specified number of times, then exit</li><li>-P: Show processes in a pure ASCII way</li></ol><h3>Interactive htop Commands</h3><p>Function Keys:</p><ul><li>F1: Help</li><li>F2: Setup</li><li>F3: Search</li><li>F4: Filter</li><li>F5: Tree view</li><li>F6: Sort by</li><li>F7/F8: Nice ±</li><li>F9: Kill</li><li>F10: Quit</li></ul><h3>Practical Troubleshooting with htop</h3><p>High CPU Usage</p><pre># Launch htop sorted by CPU<br>$ htop -s CPU%<br><br># Visual indication of CPU-intensive processes:<br>[|||||||||||||||||| 90%] Firefox<br>[|||||||           35%] Chrome</pre><p>Memory Issues</p><pre># Sort by memory usage<br>$ htop -s MEM%<br><br>Output shows memory hogs:<br>8532 user1  5.2G  25.3%  chrome<br>7832 user1  4.1G  22.1%  firefox</pre><h3>Choosing Between top and htop</h3><h3>When to Use top</h3><ul><li>Systems without htop installed</li><li>Scripting and automation</li><li>Basic system checks</li><li>Minimal resource usage</li><li>Legacy system compatibility</li></ul><h3>When to Use htop</h3><ul><li>Interactive process management</li><li>Visual resource monitoring</li><li>Complex system analysis</li><li>Multi-threaded application monitoring</li><li>User-friendly interface needs</li></ul><h3>Best Practices</h3><h3>System Monitoring Tips</h3><p>Regular Monitoring</p><ul><li>Schedule routine checks</li><li>Document baseline metrics</li><li>Track performance patterns</li></ul><p>Resource Management</p><ul><li>Set usage thresholds</li><li>Monitor critical processes</li><li>Plan for resource constraints</li></ul><p>Troubleshooting</p><ul><li>Identify abnormal patterns</li><li>Track process relationships</li><li>Document unusual behavior</li></ul><h3>Conclusion</h3><p>While top remains a reliable and essential tool for basic system monitoring, htop provides an enhanced experience with modern features and better visualization. Understanding both tools gives you the flexibility to choose the right one for your specific needs.</p><p>Whether you’re managing a single server or a large infrastructure, mastery of these tools will strengthen your ability to maintain system health and troubleshoot performance issues effectively.</p><p><em>#Linux #SystemAdministration #DevOps #TechTools #Performance #Monitoring #SysAdmin #Engineering #Technology #Programming</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9363b1c39d98" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Linux Administration: Essential Commands and Solutions (Part 1 of 3)]]></title>
            <link>https://medium.com/@kgelli/mastering-linux-administration-essential-commands-and-solutions-part-1-of-3-c17145a84f08?source=rss-95a5fd5f9cb2------2</link>
            <guid isPermaLink="false">https://medium.com/p/c17145a84f08</guid>
            <category><![CDATA[systemsecurity]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[shellscripting]]></category>
            <category><![CDATA[system-monitoring-tools]]></category>
            <category><![CDATA[linux-administration]]></category>
            <dc:creator><![CDATA[Shravanth Gelli]]></dc:creator>
            <pubDate>Sat, 21 Dec 2024 06:22:04 GMT</pubDate>
            <atom:updated>2024-12-21T06:22:04.374Z</atom:updated>
            <content:encoded><![CDATA[<p>As a Linux system administrator or DevOps engineer, mastering command-line operations is crucial for efficient system management. In this three-part series, I’ll walk you through 15 practical Linux scenarios and their solutions. Each example represents real-world challenges you might face in your daily work.</p><h3>1. Group Management for Project Collaboration</h3><p><strong>Problem Statement:</strong><br> An organization wants to create a group for project collaboration.</p><p><strong>Task:</strong><br> Create a group named project_team and add two existing users to the group. Verify the group membership using the appropriate command.</p><p><strong>Solution and Explanation:</strong><br> Group management in Linux is essential for controlling access to resources and enabling collaboration. Here’s the step-by-step solution:</p><pre># Create the new group<br>$ sudo groupadd project_team<br><br># Add users to the group (example with user1 and user2)<br>$ sudo usermod -aG project_team user1<br>$ sudo usermod -aG project_team user2<br><br># Verify group membership<br>$ getent group project_team<br>project_team:x:1001:user1,user2<br><br># Alternative verification<br>$ groups user1<br>user1 : user1 project_team<br>$ groups user2<br>user2 : user2 project_team</pre><p><strong>Why this approach works:</strong></p><ol><li>groupadd: This command creates a new group in the system. The group information is stored in /etc/group.</li><li>usermod -aG: The -a flag means &quot;append&quot; and -G specifies supplementary groups. Using them together ensures we add the group without removing existing group memberships.</li><li>getent group: This command reads the group database directly, providing reliable information about group membership.</li></ol><p><strong>Security considerations:</strong></p><ul><li>Always use usermod -aG instead of just -G to prevent accidentally removing users from other groups</li><li>Group names should be descriptive and follow your organization’s naming conventions</li><li>Regular audit of group memberships is recommended for security</li></ul><h3>2. Securing Sensitive Files</h3><p><strong>Problem Statement:</strong><br> A system administrator wants to secure sensitive files.</p><p><strong>Task:</strong><br> Create a file named confidential.txt and set permissions so that only the owner can read and write to the file, while others have no access. Verify the permissions using ls -l.</p><p><strong>Solution and Explanation:</strong><br>File permission management is crucial for data security. Here’s how we implement it:</p><pre># Create the file<br>$ touch confidential.txt<br><br># Set permissions (600 = owner read/write only)<br>$ chmod 600 confidential.txt<br><br># Verify permissions<br>$ ls -l confidential.txt<br>-rw------- 1 username username 0 Dec 20 10:15 confidential.txt<br><br># Try accessing as another user (for demonstration)<br>$ sudo -u anotheruser cat confidential.txt<br>cat: confidential.txt: Permission denied</pre><p><strong>Understanding the permission system:</strong></p><p><strong><em>The permission ‘600’ breaks down as:</em></strong></p><ul><li>6 (110 in binary) = read (4) + write (2) for owner</li><li>0 (000 in binary) = no permissions for group</li><li>0 (000 in binary) = no permissions for others</li></ul><p><strong><em>In the ls -l output:</em></strong></p><ul><li>First character (-) indicates a regular file</li><li>Next three characters (rw-) show owner permissions</li><li>Middle three ( — — — ) show group permissions</li><li>Last three ( — — — ) show other permissions</li></ul><p><strong><em>Why this is secure:</em></strong></p><ul><li>Only the file owner can read or write the file</li><li>Even users in the same group cannot access the file</li><li>System administrators (root) can still access the file if needed for backup/recovery</li></ul><h3>3. Symbolic Links for Backup Management</h3><p><strong>Problem Statement:</strong><br> A company wants to automate backups using symbolic links.</p><p><strong>Task:</strong><br> Create a symbolic link named backup_link that points to a directory named backup_folder. Verify the link using ls -l.</p><p><strong>Solution and Explanation:</strong><br> Symbolic links provide flexible file system management. Here’s how we implement it:</p><pre># First, create the backup directory if it doesn&#39;t exist<br>$ mkdir -p backup_folder<br><br># Create some sample files in backup_folder<br>$ touch backup_folder/file1.txt backup_folder/file2.txt<br><br># Create the symbolic link<br>$ ln -s backup_folder backup_link<br><br># Verify the link<br>$ ls -l backup_link<br>lrwxrwxrwx 1 username username 13 Dec 20 10:20 backup_link -&gt; backup_folder<br><br># View contents through the symbolic link<br>$ ls -l backup_link/<br>total 0<br>-rw-r--r-- 1 username username 0 Dec 20 10:20 file1.txt<br>-rw-r--r-- 1 username username 0 Dec 20 10:20 file2.txt</pre><p><strong>Why symbolic links are useful:</strong></p><ol><li>They provide flexible file system organization without duplicating data</li><li>Unlike hard links, they can span file systems and link to directories</li><li>The link target is clearly visible, making system administration more transparent</li></ol><p><strong>Best practices:</strong></p><ul><li>Use relative paths when creating links within the same file system</li><li>Regularly verify link validity to prevent broken links</li><li>Document the purpose and relationships of symbolic links</li></ul><h3>4. Network Connectivity Monitoring</h3><p><strong>Problem Statement:</strong><br> A user wants to monitor network connectivity to a remote server.</p><p><strong>Task:</strong><br> Write a command to continuously ping google.com and save the output to a file named ping_results.txt. Ensure the process runs in the background.</p><p><strong>Solution and Explanation:</strong><br> Continuous network monitoring helps identify connectivity issues. Here’s our implementation:</p><pre># Start continuous ping and redirect output to file<br>$ ping google.com &gt; ping_results.txt 2&gt;&amp;1 &amp;<br>[1] 12345<br><br># Verify the background process<br>$ jobs<br>[1]+  Running    ping google.com &gt; ping_results.txt 2&gt;&amp;1 &amp;<br><br># View the ping results<br>$ tail -f ping_results.txt<br>PING google.com (142.250.190.78) 56(84) bytes of data.<br>64 bytes from lga25s71-in-f14.1e100.net (142.250.190.78): icmp_seq=1 ttl=56 time=15.6 ms<br>64 bytes from lga25s71-in-f14.1e100.net (142.250.190.78): icmp_seq=2 ttl=56 time=14.8 ms<br>64 bytes from lga25s71-in-f14.1e100.net (142.250.190.78): icmp_seq=3 ttl=56 time=15.2 ms<br><br># Find the process ID<br>$ pgrep ping<br>12345<br><br># Stop the ping<br>$ kill $(pgrep ping)<br>[1]+  Terminated    ping google.com &gt; ping_results.txt 2&gt;&amp;1</pre><p><strong>Understanding the command components:</strong></p><ol><li>&gt; redirects standard output to our file</li><li>2&gt;&amp;1 redirects standard error to the same place as standard output</li><li>&amp; at the end runs the process in the background</li><li>tail -f allows real-time monitoring of the file</li></ol><p><strong>Why this approach is effective:</strong></p><ul><li>Background processing allows the user to continue working</li><li>File output provides a record for later analysis</li><li>Standard error redirection ensures we capture all relevant information</li><li>Process management tools (jobs, pgrep, kill) give us control over the monitoring</li></ul><h3>5. User Creation and Management</h3><p><strong>Problem Statement:</strong><br> A Linux system requires multiple users with individual home directories.</p><p><strong>Task:</strong><br> Create a user named developer1 with the default home directory /home/developer1. Set a password for the user and ensure it follows password policies.</p><p><strong>Solution and Explanation:</strong><br> Proper user management is fundamental to system security and organization. Here’s how we implement it:</p><pre># Create new user with home directory<br>$ sudo useradd -m -d /home/developer1 developer1<br><br># Set password with policy enforcement<br>$ sudo passwd developer1<br>New password: <br>Retype new password: <br>passwd: password updated successfully<br><br># Verify user creation and home directory<br>$ id developer1<br>uid=1001(developer1) gid=1001(developer1) groups=1001(developer1)<br><br>$ ls -l /home/developer1<br>total 16<br>-rw-r--r-- 1 developer1 developer1  220 Dec 20 10:25 .bash_logout<br>-rw-r--r-- 1 developer1 developer1 3526 Dec 20 10:25 .bashrc<br>-rw-r--r-- 1 developer1 developer1  807 Dec 20 10:25 .profile<br><br># Verify user can log in<br>$ su - developer1<br>Password: <br>developer1@hostname:~$ pwd<br>/home/developer1</pre><p><strong>Understanding the user creation process:</strong></p><p>useradd options:</p><ul><li>-m creates the home directory</li><li>-d specifies the home directory path</li></ul><p>passwd command:</p><ul><li>Enforces system password policies</li><li>Handles password encryption automatically</li></ul><p>Default files:</p><ul><li>.bashrc for shell configuration</li><li>.profile for login session settings</li><li>.bash_logout for cleanup on logout</li></ul><p><strong>Security considerations:</strong></p><ul><li>Home directory permissions are set correctly by default</li><li>Password policies ensure strong passwords</li><li>User IDs are assigned automatically in a safe range</li><li>Default shell configuration provides secure baseline settings</li></ul><h3>Best Practices and Tips</h3><ol><li>Always verify your commands’ results using appropriate checking commands</li><li>Use sudo only when necessary to maintain system security</li><li>Keep track of group memberships and permissions for audit purposes</li><li>Document your commands and configurations for future reference</li><li>Regularly backup important configuration changes</li></ol><h3>Coming Up Next</h3><p>In Part 2 of this series, we’ll explore more advanced Linux administration tasks, including shell management, secure data sharing, and file search operations. Stay tuned!</p><p><em>Follow me for more Linux administration tips and best practices!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c17145a84f08" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Python Programming Challenges: Data Processing, Automation, and Visualization (Part 3/3)]]></title>
            <link>https://medium.com/@kgelli/python-programming-challenges-data-processing-automation-and-visualization-part-3-3-4fb1dd0c481f?source=rss-95a5fd5f9cb2------2</link>
            <guid isPermaLink="false">https://medium.com/p/4fb1dd0c481f</guid>
            <dc:creator><![CDATA[Shravanth Gelli]]></dc:creator>
            <pubDate>Fri, 20 Dec 2024 08:43:12 GMT</pubDate>
            <atom:updated>2024-12-20T08:43:12.335Z</atom:updated>
            <content:encoded><![CDATA[<p>Welcome to the final part of our Python programming challenge series! After covering basic concepts, data structures, and user interaction in parts 1 and 2, we’ll now explore data processing, automation, and visualization challenges.</p><h3>11. Customer Feedback Analysis</h3><h3>Problem Statement</h3><p>A data scientist wants to process and clean customer feedback data.</p><h3>Task</h3><p>Write a Python program to read a list of customer feedback strings. Remove whitespace, convert all text to lowercase, and count the occurrences of a specific word.</p><h3>Solution</h3><pre>from collections import Counter<br>import re<br><br>def analyze_feedback():<br>    # Sample feedback data<br>    feedback_data = [<br>        &quot;Great product, would RECOMMEND to others!&quot;,<br>        &quot;  Service was okay, but delivery was slow  &quot;,<br>        &quot;Not satisfied with the Quality of the product&quot;,<br>        &quot;Amazing service, great quality, would recommend&quot;,<br>        &quot;POOR customer service experience!&quot;<br>    ]<br>    <br>    def clean_text(text):<br>        # Remove special characters and extra whitespace<br>        text = re.sub(r&#39;[^\w\s]&#39;, &#39;&#39;, text)<br>        text = text.strip().lower()<br>        return text<br>    <br>    def process_feedback():<br>        # Clean and process all feedback<br>        cleaned_feedback = [clean_text(text) for text in feedback_data]<br>        <br>        # Split into words and count occurrences<br>        all_words = []<br>        for feedback in cleaned_feedback:<br>            all_words.extend(feedback.split())<br>        <br>        word_counts = Counter(all_words)<br>        <br>        # Print original and cleaned feedback<br>        print(&quot;\nOriginal vs Cleaned Feedback:&quot;)<br>        print(&quot;-&quot; * 50)<br>        for original, cleaned in zip(feedback_data, cleaned_feedback):<br>            print(f&quot;\nOriginal: {original}&quot;)<br>            print(f&quot;Cleaned:  {cleaned}&quot;)<br>        <br>        # Print word statistics<br>        print(&quot;\nWord Statistics:&quot;)<br>        print(&quot;-&quot; * 20)<br>        print(f&quot;Total words: {len(all_words)}&quot;)<br>        print(&quot;\nMost common words:&quot;)<br>        for word, count in word_counts.most_common(5):<br>            print(f&quot;{word}: {count} times&quot;)<br>        <br>        # Search for specific word<br>        search_word = input(&quot;\nEnter a word to search: &quot;).lower()<br>        count = word_counts.get(search_word, 0)<br>        print(f&quot;\nThe word &#39;{search_word}&#39; appears {count} times in the feedback.&quot;)<br><br>    # Run the analysis<br>    process_feedback()<br><br>if __name__ == &quot;__main__&quot;:<br>    analyze_feedback()</pre><h3>Sample Output</h3><pre>Original vs Cleaned Feedback:<br>--------------------------------------------------<br><br>Original: Great product, would RECOMMEND to others!<br>Cleaned:  great product would recommend to others<br><br>Original:   Service was okay, but delivery was slow  <br>Cleaned:  service was okay but delivery was slow<br><br>Original: Not satisfied with the Quality of the product<br>Cleaned:  not satisfied with the quality of the product<br><br>Word Statistics:<br>--------------------<br>Total words: 35<br><br>Most common words:<br>product: 3 times<br>was: 2 times<br>the: 2 times<br>quality: 2 times<br>recommend: 2 times<br><br>Enter a word to search: quality<br><br>The word &#39;quality&#39; appears 2 times in the feedback.</pre><h3>12. Temperature Analysis System</h3><h3>Problem Statement</h3><p>A weather station wants to store and analyze temperature readings for a week.</p><h3>Task</h3><p>Write a Python program to input daily temperatures for 7 days. Calculate the average, maximum, and minimum temperatures and display them.</p><h3>Solution</h3><pre>from datetime import datetime, timedelta<br>import matplotlib.pyplot as plt<br><br>def temperature_analysis():<br>    # Initialize data structures<br>    temperatures = []<br>    dates = []<br>    <br>    # Get start date<br>    start_date = datetime.now()<br>    <br>    # Input temperatures for each day<br>    print(&quot;Enter daily temperatures for the past week:&quot;)<br>    for i in range(7):<br>        current_date = start_date - timedelta(days=6-i)<br>        date_str = current_date.strftime(&quot;%A, %B %d&quot;)<br>        dates.append(date_str)<br>        <br>        while True:<br>            try:<br>                temp = float(input(f&quot;Temperature for {date_str}: &quot;))<br>                temperatures.append(temp)<br>                break<br>            except ValueError:<br>                print(&quot;Please enter a valid temperature!&quot;)<br>    <br>    # Calculate statistics<br>    avg_temp = sum(temperatures) / len(temperatures)<br>    max_temp = max(temperatures)<br>    max_day = dates[temperatures.index(max_temp)]<br>    min_temp = min(temperatures)<br>    min_day = dates[temperatures.index(min_temp)]<br>    <br>    # Print analysis<br>    print(&quot;\nTemperature Analysis&quot;)<br>    print(&quot;-&quot; * 30)<br>    print(f&quot;Average Temperature: {avg_temp:.1f}°C&quot;)<br>    print(f&quot;Maximum Temperature: {max_temp}°C on {max_day}&quot;)<br>    print(f&quot;Minimum Temperature: {min_temp}°C on {min_day}&quot;)<br>    <br>    # Create visualization<br>    plt.figure(figsize=(10, 6))<br>    plt.plot(dates, temperatures, marker=&#39;o&#39;)<br>    plt.title(&quot;Weekly Temperature Variation&quot;)<br>    plt.xlabel(&quot;Date&quot;)<br>    plt.ylabel(&quot;Temperature (°C)&quot;)<br>    plt.xticks(rotation=45)<br>    plt.grid(True)<br>    <br>    # Add annotations for max and min<br>    plt.annotate(f&#39;Max: {max_temp}°C&#39;, <br>                xy=(temperatures.index(max_temp), max_temp),<br>                xytext=(10, 10), textcoords=&#39;offset points&#39;)<br>    plt.annotate(f&#39;Min: {min_temp}°C&#39;,<br>                xy=(temperatures.index(min_temp), min_temp),<br>                xytext=(10, -15), textcoords=&#39;offset points&#39;)<br>    <br>    plt.tight_layout()<br>    plt.show()<br><br>if __name__ == &quot;__main__&quot;:<br>    temperature_analysis()</pre><h3>Sample Output</h3><pre>Enter daily temperatures for the past week:<br>Temperature for Saturday, December 14: 24.0<br>Temperature for Sunday, December 15: 21.5<br>Temperature for Monday, December 16: 23.0<br>Temperature for Tuesday, December 17: 25.5<br>Temperature for Wednesday, December 18: 20.5<br>Temperature for Thursday, December 19: 22.0<br>Temperature for Friday, December 20: 23<br><br>Temperature Analysis<br>------------------------------<br>Average Temperature: 22.8°C<br>Maximum Temperature: 25.5°C on Tuesday, December 17<br>Minimum Temperature: 20.5°C on Wednesday, December 18<br><br>[A matplotlib graph will be displayed showing the temperature trend]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-gKo0GRRX9mZqjfJIC3cjA.png" /></figure><h3>13. WhatsApp Message Automation</h3><h3>Problem Statement</h3><p>A user wants to automate sending WhatsApp messages using Python.</p><h3>Task</h3><p>Use the pywhatkit module to send a predefined WhatsApp message to a specific number at a scheduled time.</p><h3>Solution</h3><pre>import pywhatkit<br>from datetime import datetime, timedelta<br>import time<br><br>def whatsapp_automation():<br>    def validate_phone(phone):<br>        # Remove any non-digit characters<br>        phone = &#39;&#39;.join(filter(str.isdigit, phone))<br>        if len(phone) &lt; 10:<br>            return False<br>        return phone<br>    <br>    def schedule_message():<br>        try:<br>            # Get user input<br>            phone = input(&quot;Enter recipient&#39;s phone number (with country code): &quot;)<br>            phone = validate_phone(phone)<br>            if not phone:<br>                print(&quot;Invalid phone number!&quot;)<br>                return<br>            <br>            message = input(&quot;Enter your message: &quot;)<br>            <br>            # Get current time and add 2 minutes for scheduling<br>            now = datetime.now() + timedelta(minutes=2)<br>            hour = now.hour<br>            minute = now.minute<br>            <br>            print(f&quot;\nScheduling message for {hour:02d}:{minute:02d}&quot;)<br>            print(&quot;Please ensure WhatsApp Web is connected!&quot;)<br>            <br>            # Schedule the message<br>            pywhatkit.sendwhatmsg(phone, message, hour, minute)<br>            print(&quot;\nMessage scheduled successfully!&quot;)<br>            <br>            # Wait for confirmation<br>            time.sleep(20)<br>            print(&quot;Message sent!&quot;)<br>            <br>        except Exception as e:<br>            print(f&quot;An error occurred: {str(e)}&quot;)<br>    <br>    def show_instructions():<br>        print(&quot;\nWhatsApp Automation Instructions:&quot;)<br>        print(&quot;1. Make sure you have WhatsApp Web set up&quot;)<br>        print(&quot;2. Keep your phone connected to the internet&quot;)<br>        print(&quot;3. The message will be scheduled 2 minutes from now&quot;)<br>        print(&quot;4. Don&#39;t close the browser window that opens&quot;)<br>    <br>    # Main program loop<br>    while True:<br>        print(&quot;\nWhatsApp Message Automation&quot;)<br>        print(&quot;1. Schedule a message&quot;)<br>        print(&quot;2. View instructions&quot;)<br>        print(&quot;3. Exit&quot;)<br>        <br>        choice = input(&quot;\nEnter choice (1-3): &quot;)<br>        <br>        if choice == &quot;1&quot;:<br>            schedule_message()<br>        elif choice == &quot;2&quot;:<br>            show_instructions()<br>        elif choice == &quot;3&quot;:<br>            print(&quot;Goodbye!&quot;)<br>            break<br>        else:<br>            print(&quot;Invalid choice!&quot;)<br><br>if __name__ == &quot;__main__&quot;:<br>    whatsapp_automation()</pre><h3>Sample Output</h3><pre>WhatsApp Message Automation<br>1. Schedule a message<br>2. View instructions<br>3. Exit<br><br>Enter choice (1-3): 2<br><br>WhatsApp Automation Instructions:<br>1. Make sure you have WhatsApp Web set up<br>2. Keep your phone connected to the internet<br>3. The message will be scheduled 2 minutes from now<br>4. Don&#39;t close the browser window that opens<br><br>Enter choice (1-3): 1<br>Enter recipient&#39;s phone number (with country code): +1234567890<br>Enter your message: Hello! This is an automated message.<br><br>Scheduling message for 15:30<br>Please ensure WhatsApp Web is connected!<br>In 51 Seconds WhatsApp will open and after 15 Seconds Message will be Delivered!<br><br>Message scheduled successfully!<br>Message sent!</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8-xy3iO_sxjwK1HnvfO7BA.png" /></figure><h3>14. Monthly Expenses Visualization</h3><h3>Problem Statement</h3><p>A mathematician wants to visualize data using bar charts.</p><h3>Task</h3><p>Write a Python program to use Matplotlib to plot a bar chart of monthly expenses. Label the bars and add titles to the chart.</p><h3>Solution</h3><pre>import matplotlib.pyplot as plt<br>import numpy as np<br><br>def visualize_expenses():<br>    # Initialize expense categories and data<br>    categories = {<br>        &#39;Housing&#39;: [],<br>        &#39;Transportation&#39;: [],<br>        &#39;Food&#39;: [],<br>        &#39;Utilities&#39;: [],<br>        &#39;Entertainment&#39;: []<br>    }<br>    <br>    def input_expenses():<br>        print(&quot;Enter monthly expenses for each category:&quot;)<br>        for category in categories:<br>            while True:<br>                try:<br>                    amount = float(input(f&quot;{category}: $&quot;))<br>                    if amount &gt;= 0:<br>                        categories[category] = amount<br>                        break<br>                    else:<br>                        print(&quot;Please enter a positive amount!&quot;)<br>                except ValueError:<br>                    print(&quot;Please enter a valid number!&quot;)<br>    <br>    def create_chart():<br>        # Prepare data for visualization<br>        expenses = list(categories.values())<br>        labels = list(categories.keys())<br>        <br>        # Create bar chart<br>        plt.figure(figsize=(12, 6))<br>        bars = plt.bar(labels, expenses)<br>        <br>        # Customize chart<br>        plt.title(&quot;Monthly Expenses Breakdown&quot;, pad=20)<br>        plt.xlabel(&quot;Categories&quot;)<br>        plt.ylabel(&quot;Amount ($)&quot;)<br>        <br>        # Rotate x-axis labels for better readability<br>        plt.xticks(rotation=45)<br>        <br>        # Add value labels on top of bars<br>        for bar in bars:<br>            height = bar.get_height()<br>            plt.text(bar.get_x() + bar.get_width()/2., height,<br>                    f&#39;${height:,.2f}&#39;,<br>                    ha=&#39;center&#39;, va=&#39;bottom&#39;)<br>        <br>        # Add total expenses<br>        total = sum(expenses)<br>        plt.text(0.5, 1.1, f&#39;Total Expenses: ${total:,.2f}&#39;,<br>                ha=&#39;center&#39;, va=&#39;bottom&#39;,<br>                transform=plt.gca().transAxes)<br>        <br>        # Adjust layout and display<br>        plt.tight_layout()<br>        plt.show()<br>        <br>        # Print numerical summary<br>        print(&quot;\nExpense Summary:&quot;)<br>        print(&quot;-&quot; * 30)<br>        for category, amount in categories.items():<br>            print(f&quot;{category}: ${amount:,.2f}&quot;)<br>        print(&quot;-&quot; * 30)<br>        print(f&quot;Total: ${total:,.2f}&quot;)<br>    <br>    # Run the visualization<br>    input_expenses()<br>    create_chart()<br><br>if __name__ == &quot;__main__&quot;:<br>    visualize_expenses()</pre><h3>Sample Output</h3><pre>Enter monthly expenses for each category:<br>Housing: $1200<br>Transportation: $300<br>Food: $500<br>Utilities: $150<br>Entertainment: $200<br><br>Expense Summary:<br>------------------------------<br>Housing: $1,200.00<br>Transportation: $300.00<br>Food: $500.00<br>Utilities: $150.00<br>Entertainment: $200.00<br>------------------------------<br>Total: $2,350.00<br><br>[A matplotlib bar chart will be displayed showing the expense breakdown]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TK1Zq_nrJ_cmhiy4mIJXvA.png" /></figure><h3>15. Number Sequence Generator</h3><h3>Problem Statement</h3><p>A student wants to learn about Python generators and lazy evaluation.</p><h3>Task</h3><p>Write a Python program to create a generator that yields the squares of numbers from 1 to 10. Print each value using a for loop.</p><h3>Solution</h3><pre>def number_sequence():<br>    def square_generator(start, end):<br>        &quot;&quot;&quot;Generator function that yields squares of numbers&quot;&quot;&quot;<br>        for num in range(start, end + 1):<br>            # Calculate square and yield additional information<br>            yield {<br>                &#39;number&#39;: num,<br>                &#39;square&#39;: num ** 2,<br>                &#39;is_even&#39;: num % 2 == 0<br>            }<br>    <br>    def demonstrate_generator():<br>        print(&quot;Number Sequence Analysis&quot;)<br>        print(&quot;-&quot; * 30)<br>        <br>        # Create generator object<br>        squares = square_generator(1, 10)<br>        <br>        # Initialize counters<br>        even_squares = 0<br>        odd_squares = 0<br>        <br>        # Process and display each number<br>        print(&quot;\nSequence Details:&quot;)<br>        for item in squares:<br>            num = item[&#39;number&#39;]<br>            square = item[&#39;square&#39;]<br>            is_even = item[&#39;is_even&#39;]<br>            <br>            # Update counters<br>            if is_even:<br>                even_squares += 1<br>            else:<br>                odd_squares += 1<br>            <br>            # Display formatted output<br>            print(f&quot;\nNumber: {num}&quot;)<br>            print(f&quot;Square: {square}&quot;)<br>            print(f&quot;{&#39;Even&#39; if is_even else &#39;Odd&#39;} number&quot;)<br>        <br>        # Display summary<br>        print(&quot;\nSequence Summary:&quot;)<br>        print(&quot;-&quot; * 30)<br>        print(f&quot;Even numbers: {even_squares}&quot;)<br>        print(f&quot;Odd numbers: {odd_squares}&quot;)<br>        print(f&quot;Largest square: {10 ** 2}&quot;)<br>        <br>        # Demonstrate generator reusability<br>        print(&quot;\nNote: Generator has been exhausted.&quot;)<br>        print(&quot;Creating new generator for demonstration...&quot;)<br>        <br>        new_squares = square_generator(1, 10)<br>        print(&quot;\nFirst 3 squares from new generator:&quot;)<br>        for i, item in enumerate(new_squares, 1):<br>            if i &gt; 3:<br>                break<br>            print(f&quot;{item[&#39;number&#39;]} → {item[&#39;square&#39;]}&quot;)<br><br>if __name__ == &quot;__main__&quot;:<br>    number_sequence()</pre><h3>Sample Output</h3><pre>Number Sequence Analysis<br>------------------------------<br><br>Sequence Details:<br><br>Number: 1<br>Square: 1<br>Odd number<br><br>Number: 2<br>Square: 4<br>Even number<br><br>[... output continues for numbers 3-10 ...]<br><br>Sequence Summary:<br>------------------------------<br>Even numbers: 5<br>Odd numbers: 5<br>Largest square: 100<br><br>Note: Generator has been exhausted.<br>Creating new generator for demonstration...<br><br>First 3 squares from new generator:<br>1 → 1<br>2 → 4<br>3 → 9</pre><h3>Conclusion</h3><p>In this final part of our Python programming series, we’ve explored:</p><ol><li>Text processing and analysis with regular expressions and Counter</li><li>Temperature data analysis and visualization</li><li>Task automation with WhatsApp messaging</li><li>Data visualization with Matplotlib</li><li>Generator functions and lazy evaluation</li></ol><p>Key concepts covered in this section include:</p><ul><li>Text cleaning and processing</li><li>Data visualization techniques</li><li>Task automation</li><li>Error handling and input validation</li><li>Generator functions and memory efficiency</li></ul><p>Throughout this three-part series, we’ve covered a wide range of Python programming concepts and practical applications:</p><p>Part 1:</p><ul><li>Memory management</li><li>Data structures</li><li>Scientific computing</li><li>Image processing</li><li>Matrix operations</li></ul><p>Part 2:</p><ul><li>Employee management systems</li><li>Statistical analysis</li><li>Secure login systems</li><li>Sales tracking</li><li>Graphics programming</li></ul><p>Part 3:</p><ul><li>Text analysis</li><li>Data visualization</li><li>Automation</li><li>Advanced Python features</li><li>Real-world applications</li></ul><p>These exercises provide a solid foundation for Python programming and demonstrate how Python can be used to solve real-world problems efficiently.</p><p><em>Thank you for following this Python programming series! If you found these tutorials helpful, please clap and share. Follow me for more programming tutorials and tips!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4fb1dd0c481f" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>