Day 3 of #30DaysOfDevOps — Post 2 Knowing Python syntax is one thing. Using Python to automate real infrastructure tasks is another. Here's where it gets practical. 1. Managing Packages with pip pip is Python's package manager. It connects you to thousands of libraries built for every DevOps task imaginable. Install a library: pip install boto3 Install a specific version: pip install boto3==1.26.0 Save all dependencies to a file: pip freeze > requirements.txt Restore them on another machine: pip install -r requirements.txt Always pin versions in requirements.txt for reproducible environments. 2. Working with the os Module The os module lets your Python scripts interact directly with the operating system. import os # Create a directory if it doesn't exist if not os.path.exists("/var/app/releases"): os.makedirs("/var/app/releases") # List all files in a directory for f in os.listdir("/etc/nginx/conf.d"): print(f) # Get an environment variable db_url = os.getenv("DATABASE_URL", "localhost:5432") 3. Automation Scripting This is where Python earns its place in DevOps. A few lines can replace hours of manual work. Rename all .log files to .log.bak for archiving: import os for filename in os.listdir("/var/log/app"): if filename.endswith(".log"): os.rename( f"/var/log/app/{filename}", f"/var/log/app/{filename}.bak" ) print(f"Archived: {filename}") 4. Running System Commands with subprocess Need to run shell commands from Python? Use subprocess. import subprocess result = subprocess.run( ["systemctl", "status", "nginx"], capture_output=True, text=True ) print(result.stdout) This lets you build scripts that check service health, restart processes, or run deployments. 5. Scheduling Scripts Once your script is ready, automate it with cron. Run a cleanup script every day at midnight: 0 0 * * * /usr/bin/python3 /opt/scripts/cleanup.py Run a health check every 5 minutes: */5 * * * * /usr/bin/python3 /opt/scripts/healthcheck.py 6. Challenges for Today 1. Write a script that generates a random 16-character password using the secrets module. 2. Use subprocess to check if nginx is running and print its status. 3. Write a script that monitors CPU and memory usage every 5 seconds using psutil. 4. Use the requests library to fetch data from a public API and print the response. 5. Automate bulk file renaming in a directory based on a pattern. 6. Write a script that creates a Linux user and verifies the creation. Drop your scripts in the comments — let's see what you build. #DevOps #Python #Automation #Scripting #30DaysOfDevOps #LearningInPublic #DevOpsEngineer
Mastering Python for DevOps Automation with pip, os, and subprocess
More Relevant Posts
-
Understanding Tuples and Sets in Python is a small step that makes a big difference in DevOps 🚀 Tuple = immutable (safe & fast) List = mutable (flexible) Set = no duplicates (optimized loops & clean data) In real DevOps workflows, using sets can reduce unnecessary iterations and improve script performance. If you're working with automation or CI/CD, these basics matter more than you think. Blog Link: https://lnkd.in/d8_md7WK , https://lnkd.in/dKm-mpnG #Python #DevOps #Automation #DataStructures #CICD
To view or add a comment, sign in
-
Ansible_5 Indentation and Whitespace Like Python, YAML uses space indentation to reduce the number of interpunction characters. We use two spaces as a standard. For readability, we prefer to add whitespace between each task in a playbook, and between sections in files. Strings In general, you don’t need to quote YAML strings. Even if there are spaces, you don’t need to quote them. For example, this is a string in YAML: this is a lovely sentence The JSON equivalent is as follows: "this is a lovely sentence" Use single quotes for literal values that should not be evaluated, like version numbers and floating point numbers, or strings with reserved characters like colons, brackets, or braces. Booleans YAML has a native Boolean type and provides you with a variety of values that evaluate to true or false. These are all Boolean true values in YAML: true, True, TRUE, yes, Yes, YES, on, On, ON JSON only uses: true These are all Boolean false values in YAML: false, False, FALSE, no, No, NO, off, Off, OFF JSON only uses:false Lists YAML lists are like arrays in JSON and Ruby, or lists in Python.The YAML specification calls these sequences, but we call them lists here to be consistent with the official Ansible documentation. Indent list items and delimit them with hyphens. shows: - My Fair Lady - Oklahoma - The Pirates of Penzance YAML also supports an inline format for lists, with comma-separated values in square brackets: shows: [ My Fair Lady , Oklahoma , The Pirates of Penzance ] Dictionaries YAML dictionaries are like objects in JSON, dictionaries in Python, hashes in Ruby, or associative arrays in PHP The YAML specification calls them mappings, but we call them dictionaries here to be consistent with the Ansible documentation. address: street: Main Street appt: 742 city: Logan state: Ohio YAML also supports an inline format for dictionaries, with comma separated tuples in braces: address: { street: Main Street, appt: '742', city: Logan, state:Ohio} Multiline Strings You can format multiline strings with YAML by combining a block style indicator (| or >) If you want one string across multiple lines: Using | message: | This is line one This is line two This is line three Using > message: > This is line one This is line two This is line three output will be This is line one This is line two This is line three
To view or add a comment, sign in
-
🚀 Python for DevOps – Real-Time Error Monitoring Practiced building a simple real-time log monitoring script using Python to detect errors instantly. 📂 Use Case: In production, logs are continuously generated. We need a way to detect errors in real time instead of manually checking files. 💻 Python Script: import time with open("app.log", "r") as f: f.seek(0, 2) # move to end of file while True: line = f.readline() if not line: time.sleep(1) continue if "ERROR" in line: print("Alert:", line.strip()) Output: ubuntu@satheesha:~/python$ python3 real-time_log-montr.py Alert ERROR: Test Wed Apr 22 08:05:25 UTC 2026 Alert ERROR: Test Wed Apr 22 08:05:27 UTC 2026 Alert ERROR: Test Wed Apr 22 08:05:29 UTC 2026 Alert ERROR: Test Wed Apr 22 08:05:31 UTC 2026 🔍 What this does: Reads log file in real time Starts from end (like tail -f) Continuously checks for new entries Prints alert when ERROR is detected 🔥 Why this matters: Helps detect issues instantly Reduces downtime Automates monitoring tasks 💡 Key Learning: Python can be used to build lightweight monitoring tools, similar to real-world DevOps systems. 📈 Next Step: Add timestamps Handle multiple log levels Send alerts (email/Slack) Auto-restart services on failure #Python #DevOps #Automation #Monitoring #Logging #Scripting #Learning #100DaysOfCode
To view or add a comment, sign in
-
🚨 Anthropic accidentally leaked their entire source code yesterday. How to Deploy Anthropic Claude Opus 4.6 For free 😄 Download Repo: https://lnkd.in/eHyiGhpU What this repo contains The project has two build paths: a Python workspace under src/ a Rust port under rust/ So “build this code” can mean either: run the Python version, or compile the Rust version. Option A: Build and run the Python workspace 1) Install Python Make sure you have Python 3 installed. Check: python3 --version 2) Go into the repo folder cd claw-code 3) Inspect the Python workspace The README says the active Python code is in src/ and tests are in tests/. You can confirm: ls ls src ls tests 4) Run the main Python entrypoint The README shows these commands: python3 -m src.main summary python3 -m src.main manifest python3 -m src.main subsystems --limit 16 These are the first commands to try because src.main is the CLI entrypoint. 5) Run tests Use the verification command from the README: python3 -m unittest discover -s tests -v That checks whether the Python workspace is functioning as expected. 6) Run additional Python inspection commands The README also lists: python3 -m src.main parity-audit python3 -m src.main commands --limit 10 python3 -m src.main tools --limit 10 Use those after the basic commands work. Option B: Build the Rust port 1) Install Rust You need Cargo and Rust. Check: rustc --version cargo --version 2) Enter the Rust folder cd claw-code/rust 3) Build in release mode The README gives the exact build command: cargo build --release That is the official Rust build step for this repo. 4) Run the built binary The README says there is a crates/claw-cli crate, so after building, the binary is likely under: ./target/release/claw-cli If that name does not exist, inspect the release folder: ls target/release The CLI crate is identified in the README as crates/claw-cli, which strongly suggests the executable will be named claw-cli. Recommended build order If you are new to the repo, do it in this order: Path 1: easiest start git clone https://lnkd.in/eHyiGhpU cd claw-code python3 -m src.main summary python3 -m unittest discover -s tests -v Path 2: compile Rust cd rust cargo build --release This order makes sense because the README says the repo is now “Python-first,” while the Rust workspace is the systems-language port. Full step-by-step from scratch # 1) Clone git clone https://lnkd.in/eHyiGhpU cd claw-code # 2) Check Python python3 --version # 3) Try the Python CLI python3 -m src.main summary python3 -m src.main manifest python3 -m src.main subsystems --limit 16 # 4) Run tests python3 -m unittest discover -s tests -v # 5) Optional: inspect parity and inventories python3 -m src.main parity-audit python3 -m src.main commands --limit 10 python3 -m src.main tools --limit 10 # 6) Build Rust version cd rust cargo build --release # 7) Inspect compiled binaries ls target/release
To view or add a comment, sign in
-
Multi-Agent A2A with the Agent Development Kit(ADK), AWS Lightsail, and Gemini CLI: Leveraging the Google Agent Development Kit (ADK) and the underlying Gemini LLM to build Multi-Agent Applications with A2A protocol support using the Python programming language. Aren’t There a Billion Python ADK Demos? Yes there are. Python has traditionally been the main coding language for ML and AI tools. The goal of this article is to provide a multi-agent test bed for building, debugging, and deploying multi-agent applications. What you talkin ‘bout Willis? So what is different about this lab compared to all the others out there? This is one of the first deep dives into a Multi-Agent application leveraging the advanced tooling of Gemini CLI. The starting point for the demo was an existing Codelab- which was updated and re-engineered with Gemini CLI. The original Codelab- is here: Building a Multi-Agent System | Google Codelabs What Is Python? Python is an interpreted language that allows for rapid development and testing and has deep libraries for working with ML and AI: Welcome to Python.org Python Version Management One of the downsides of the wide deployment of Python has been managing the language versions across platforms and maintaining a supported version. The pyenv tool enables deploying consistent versions of Python: GitHub - pyenv/pyenv: Simple Python version management As of writing — the mainstream python version is 3.13. To validate your current Python:python --version Python 3.13.13 Amazon Lightsail Amazon Lightsail is an easy-to-use virtual private server (VPS) provider and cloud platform designed by AWS for simpler workloads, offering developers pre-configured compute, storage, and networking for a low, predictable monthly price. It is ideal for hosting small websites, simple web apps, or creating development environments. More information is available on the official site here: Amazon's Simple Cloud Server | Amazon Lightsail And this is the direct URL to the console:https://lnkd.in/eV7DaV8y The Lightsail console will look similar to: Gemini CLI If not pre-installed you can download the Gemini CLI to interact with the source files and provide real-time assistance:npm install -g @google/gemini-cli Testing the Gemini CLI Environment Once you have all the tools and the correct Node.js version in place- you can test the startup of Gemini CLI. You will need to authenticate with a Key or your Google Account:▝▜▄ Gemini CLI v0.33.1 ▝▜▄ ▗▟▀ Logged in with Google /auth ▝▀ Gemini Code Assist Standard /upgrade no sandbox (see /docs) /model Auto (Gemini 3) | 239.8 MB Node Version Management Gemini CLI needs a consistent, up to date version of Node. The nvm command can be used to get a standard Node environment: GitHub - nvm-sh/nvm: Node Version Manager - POSIX-compliant bash script to manage multiple… #genai #shared #ai
To view or add a comment, sign in
-
🚀 Python for DevOps – Log Monitoring with File Output Today I built a simple automation script to read logs and write alerts to a separate file. 📂 Scenario: Instead of manually checking logs, automate detection of ERROR messages and store them in another file. 💻 Python Code: with open("app.log") as f, open("alerts.log", "w") as out: for line in f: if "ERROR" in line: out.write(line) output: root@satheesha:~# python3 Python 3.12.3 (main, Mar 3 2026, 12:15:18) [GCC 13.3.0] on linux Type "help", "copyright", "credits" or "license" for more information. >>> with open("app.log") as f, open("Alert.log", "w") as out: ... for line in f: ... if "ERROR" in line: ... out.write(line) ... 17 >>> exit() root@satheesha:~# cat Alert.log ERROR: Disk full 🔍 What this does: Reads app.log line by line Filters only ERROR logs Writes them into alerts.log 📌 Why this is useful: Helps in faster troubleshooting Reduces manual log scanning Can be integrated with monitoring systems 🔥 Real DevOps Use Cases: Production log monitoring CI/CD pipeline validation Incident detection and alerting 📈 Next Step: Enhance this script to: Handle multiple log levels (ERROR / WARNING / INFO) Send alerts to email or Slack Monitor logs in real-time (like tail -f) #Python #DevOps #Automation #Scripting #Cloud #Learning #100DaysOfCode
To view or add a comment, sign in
-
𝗗𝗮𝘆 𝟲𝟰: 𝗛𝗼𝘄 𝗣𝘆𝘁𝗵𝗼𝗻 𝗖𝗹𝗮𝘀𝘀𝗲𝘀 𝗕𝗲𝗰𝗼𝗺𝗲 𝗗𝗷𝗮𝗻𝗴𝗼 𝗠𝗼𝗱𝗲𝗹𝘀 Today I linked two big ideas. Python object oriented programming. And Django models. They are the same thing. A Django model is just a Python class. Here is what I learned about Python classes. A class is a blueprint. An object is a built thing from that blueprint. - class Car: defines the blueprint. - __init__ runs when you build the object. self points to that new object. - Instance attributes like self.brand are unique to each object. - Class attributes like company are shared by all objects. Methods live inside classes. - Instance method: uses self. Works with your object's data. - Class method: uses cls. Decorated with @classmethod. Works with the class itself. - Static method: uses no self or cls. Decorated with @staticmethod. Just a function inside the class. Inheritance lets a child class reuse a parent class. - class Dog(Animal): Dog gets all of Animal's code. - Use super() to run the parent's __init__. Python does not have private. It has conventions. - _name is protected. A hint to other coders. - __name is private. Python changes its name to _ClassName__name. Dunder methods define how your object acts with Python's built-ins. - __str__: for print() and str(). - __len__: for len(). - __eq__: for ==. Abstract Base Classes force subclasses to write specific methods. - from abc import ABC, abstractmethod - @abstractmethod means "you must write this method". Now for Django. A Django model is a Python class that inherits from models.Model. - Each class attribute becomes a database column. - Django reads these attributes and creates the SQL table for you. You do not write SQL. You run two commands. - python manage.py makemigrations - python manage.py migrate The __str__ method in your model controls what you see in the Django admin. Without it you see "Post object (1)". With it you see your post title. OOP is the foundation. Django models are the practical application. A model class maps directly to a database table. Fields map to columns. Your __str__ method controls the display. Understanding Python classes first makes Django models obvious. Source: https://lnkd.in/gChPWWZS
To view or add a comment, sign in
-
🚀 Simple Python Script for DevOps Practice In DevOps, even small scripts can make a big difference in automation and monitoring. Here’s a simple Python script I practiced to simulate basic server details and loop operations 👇 name = "server1" cpu_usage = 75 is_running = True print(f"Name: {name}") print(f"CPU Usage: {cpu_usage}%") print(f"Is Running: {is_running}") print("-" * 30) for i in range(6): print(i) print("-" * 30) for i in range(1, 12, 2): print(i) print("-" * 30) for i in range(10, -1, -1): print(i) print("-" * 30) Output: ubuntu@satheesha:~/python$ python3 variable-for_loop.py Name: server1 CPU Usage: 75% Is Running: True ------------------------------ 0 ------------------------------ 1 ------------------------------ 2 ------------------------------ 3 ------------------------------ 4 ------------------------------ 5 ------------------------------ 1 ------------------------------ 3 ------------------------------ 5 ------------------------------ 7 ------------------------------ 9 ------------------------------ 11 ------------------------------ 10 ------------------------------ 9 ------------------------------ 8 ------------------------------ 7 ------------------------------ 6 ------------------------------ 5 ------------------------------ 4 ------------------------------ 3 ------------------------------ 2 ------------------------------ 1 ------------------------------ 0 ------------------------------ 🔹 Key concepts used: ✔ Variables & data types ✔ f-strings for clean output ✔ Loops with range() ✔ Reverse iteration 💡 These basics are very useful for: Automation scripts Monitoring tasks Log analysis Learning step by step and practicing regularly helps build strong DevOps scripting skills. #DevOps #Python #Automation #Scripting #Learning #AWS #Kubernetes #Jenkins
To view or add a comment, sign in
-
An expert comparison of Flask and FastAPI for Python backends. Learn architectural trade-offs, deployment patterns with Docker and Kubernetes, performance tuning, and business impact for New Zealand projects.
To view or add a comment, sign in
-
MarkItDown is a lightweight Python utility for converting various files to Markdown for use with LLMs and related text analysis pipelines.
To view or add a comment, sign in
Explore content categories
- Career
- Productivity
- Finance
- Soft Skills & Emotional Intelligence
- Project Management
- Education
- Technology
- Leadership
- Ecommerce
- User Experience
- Recruitment & HR
- Customer Experience
- Real Estate
- Marketing
- Sales
- Retail & Merchandising
- Science
- Supply Chain Management
- Future Of Work
- Consulting
- Writing
- Economics
- Artificial Intelligence
- Employee Experience
- Workplace Trends
- Fundraising
- Networking
- Corporate Social Responsibility
- Negotiation
- Communication
- Engineering
- Hospitality & Tourism
- Business Strategy
- Change Management
- Organizational Culture
- Design
- Innovation
- Event Planning
- Training & Development