From 2b67097ba0def1726c54e3d67d76d631bae66ab1 Mon Sep 17 00:00:00 2001 From: Puru <5674762+tuladhar@users.noreply.github.com> Date: Fri, 20 Nov 2026 15:46:10 +0545 Subject: [PATCH 1/3] Modernize the guide into community-editable chapters - Split README into 14 Markdown chapters under chapters/ with a chapters.json manifest that powers purutuladhar.com/python-for-sys-admin - Rewrite content for Python 3.10+: subprocess.run, pathlib, f-strings, OSError, UTC datetimes, fixed broken examples - New chapters/sections: lab setup (iximiuz Labs playground), SQLite, socket - Sync examples/ with chapter scripts (all verified to run) - Add CONTRIBUTING.md, chapter issue template and help-wanted list - New README with website, playground, /step-by-step skill and star CTA Co-Authored-By: Claude Opus 5.5 --- .github/ISSUE_TEMPLATE/chapter.yml | 32 + CONTRIBUTING.md | 71 ++ README.md | 1192 +------------------------ chapters/01-set-up-your-lab.md | 67 ++ chapters/02-standard-io.md | 79 ++ chapters/03-working-with-files.md | 130 +++ chapters/04-command-line-arguments.md | 84 ++ chapters/05-os-module.md | 142 +++ chapters/06-sys-module.md | 83 ++ chapters/07-shutil-and-glob.md | 83 ++ chapters/08-date-and-time.md | 120 +++ chapters/09-subprocess.md | 149 ++++ chapters/10-argparse.md | 159 ++++ chapters/11-json.md | 131 +++ chapters/12-csv.md | 103 +++ chapters/13-sqlite.md | 128 +++ chapters/14-socket.md | 103 +++ chapters/chapters.json | 51 ++ examples/app.py | 16 +- examples/argv_01.py | 6 + examples/argv_02.py | 10 + examples/backup_log.py | 32 + examples/bideriectional.py | 26 - examples/capture_output.py | 20 +- examples/check_call.py | 14 +- examples/disk_alert.py | 19 + examples/filesizes.py | 32 +- examples/follow.py | 13 + examples/github_stars.py | 10 + examples/grep.py | 21 +- examples/line_count.py | 9 +- examples/one_way.py | 26 - examples/port_check.py | 15 + examples/prune_backups.py | 22 + examples/stdio.py | 20 + examples/stopped_containers.py | 14 + examples/sweep.py | 21 + examples/sys_01.py | 35 +- examples/tcp_port_checker.py | 49 +- examples/upper.py | 6 + examples/users_to_csv.py | 14 + examples/working_with_files_01.py | 30 +- 42 files changed, 2065 insertions(+), 1322 deletions(-) create mode 100644 .github/ISSUE_TEMPLATE/chapter.yml create mode 100644 CONTRIBUTING.md create mode 100644 chapters/01-set-up-your-lab.md create mode 100644 chapters/02-standard-io.md create mode 100644 chapters/03-working-with-files.md create mode 100644 chapters/04-command-line-arguments.md create mode 100644 chapters/05-os-module.md create mode 100644 chapters/06-sys-module.md create mode 100644 chapters/07-shutil-and-glob.md create mode 100644 chapters/08-date-and-time.md create mode 100644 chapters/09-subprocess.md create mode 100644 chapters/10-argparse.md create mode 100644 chapters/11-json.md create mode 100644 chapters/12-csv.md create mode 100644 chapters/13-sqlite.md create mode 100644 chapters/14-socket.md create mode 100644 chapters/chapters.json create mode 100644 examples/argv_01.py create mode 100644 examples/argv_02.py create mode 100644 examples/backup_log.py delete mode 100755 examples/bideriectional.py create mode 100644 examples/disk_alert.py create mode 100644 examples/follow.py create mode 100644 examples/github_stars.py delete mode 100755 examples/one_way.py create mode 100644 examples/port_check.py create mode 100644 examples/prune_backups.py create mode 100644 examples/stdio.py create mode 100644 examples/stopped_containers.py create mode 100644 examples/sweep.py create mode 100644 examples/upper.py create mode 100644 examples/users_to_csv.py diff --git a/.github/ISSUE_TEMPLATE/chapter.yml b/.github/ISSUE_TEMPLATE/chapter.yml new file mode 100644 index 0000000..e00b90b --- /dev/null +++ b/.github/ISSUE_TEMPLATE/chapter.yml @@ -0,0 +1,32 @@ +name: Chapter request or proposal +description: Suggest a new chapter, or claim one from the "Help wanted" list. +title: "Chapter: " +labels: ["chapter", "help wanted"] +body: + - type: markdown + attributes: + value: | + Thanks for helping the community! See [CONTRIBUTING.md](https://github.com/tuladhar/Python-for-SysAdmin/blob/main/CONTRIBUTING.md) for how chapters are written. + - type: input + id: module + attributes: + label: Module or topic + placeholder: e.g. re, logging, paramiko + validations: + required: true + - type: textarea + id: why + attributes: + label: Why is it useful for sysadmins and DevOps engineers? + placeholder: Real tasks this chapter would help with. + validations: + required: true + - type: dropdown + id: write + attributes: + label: Do you want to write it? + options: + - Yes, I'll open a pull request + - I'd like someone else to write it + validations: + required: true diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..0cf7858 --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,71 @@ +# Contributing + +Python for SysAdmin is a community guide. Every chapter you add or fix shows up on the website at **[purutuladhar.com/python-for-sys-admin](https://purutuladhar.com/python-for-sys-admin/)** as soon as it is merged. No build step, no website code to touch. + +All kinds of help are welcome: + +- Fix a typo, a broken example or an outdated explanation. +- Write a chapter from the **wanted** list in [`chapters/chapters.json`](chapters/chapters.json) (shown as "Help wanted" on the website). +- Propose a new chapter by [opening an issue](https://github.com/tuladhar/Python-for-SysAdmin/issues/new?template=chapter.yml). +- Record a short GIF that shows an example running. + +## How the repo is organised + +```text +chapters/ + chapters.json # order of chapters + the "wanted" list + 01-set-up-your-lab.md + 02-standard-io.md + ... +examples/ # every runnable script from the chapters +assets/ # images and GIFs used by chapters +``` + +The website reads `chapters/chapters.json`, then loads each chapter's Markdown file straight from the `main` branch. + +## Fixing an existing chapter + +1. Open the chapter on the website and click **Edit this page on GitHub**, or edit the file in `chapters/` directly. +2. If you change a script, update the matching file in `examples/` too. +3. Open a pull request. + +## Writing a new chapter + +1. Comment on (or open) an issue for the topic so nobody else starts the same chapter. +2. Create `chapters/NN-short-name.md`, using the next free number. +3. Add an entry to the right section in `chapters/chapters.json`: + + ```json + { "slug": "regex", "file": "15-regex.md", "title": "Regular Expressions", "summary": "Parse log lines, extract IPs and validate input." } + ``` + + If the topic was on the `wanted` list, remove it from there. +4. Put every complete script in `examples/` as well. +5. Open a pull request. + +### Chapter style + +Look at [`09-subprocess.md`](chapters/09-subprocess.md) for a good template. + +- Start with a `# Title` and one or two sentences on **why a sysadmin needs this**. +- Short sections with `##` headings. Explain one idea, then show it. +- Use **Python 3.10+** and the standard library unless the chapter is about a third-party package. +- Use `pathlib`, f-strings, `subprocess.run()`, `with` blocks and `encoding="utf-8"`. +- Every complete script starts with `#!/usr/bin/env python3` and a `# filename.py` comment, and must run as shown. +- Show the command and its output in a separate `bash` block. +- End with **Exercises** and a link to the official documentation. +- Link to other chapters by file name, e.g. `[argparse](10-argparse.md)`. The website turns these into chapter links. +- Use simple, plain English. Many readers are not native speakers. + +Preview your Markdown in the GitHub pull request "Preview" tab or any Markdown viewer. + +## Adding a GIF + +Short GIFs of a script running in a terminal help a lot, especially in the [iximiuz Labs Python Playground](https://labs.iximiuz.com/playgrounds/python). + +- Keep it under 20 seconds and under 3 MB. Tools like [VHS](https://github.com/charmbracelet/vhs) or [asciinema](https://asciinema.org/) + [agg](https://github.com/asciinema/agg) work well. +- Put it in `assets/` and reference it from the chapter: `![What the GIF shows](../assets/my-demo.gif)`. + +## Code of conduct + +Be kind and patient. Everyone here is learning. diff --git a/README.md b/README.md index ce1718f..4d71d61 100755 --- a/README.md +++ b/README.md @@ -1,1171 +1,71 @@ -# Python3 for Systems Administrator -[![Generic badge](https://img.shields.io/badge/Author-Puru_Tuladhar-.svg)](https://github.com/tuladhar) -[![Generic badge](https://img.shields.io/badge/Editor_and_Maintainer-Silent_Mobius-.svg)](https://github.com/silent-mobius) +# Python for SysAdmin -## Contents -- #### Getting Started - 1. [Standard I/O](#getting-started-standard-input-output-and-error) - 2. [Working with files](#getting-started-working-with-files) - 3. [Command-line Arguments](#getting-started-command-line-arguments) -- #### Exploring Standard Modules - 1. [Operating System (OS) Module](#exploring-standard-modules-operating-system-os-module) - 2. [System-specific Module](#exploring-standard-modules-system-specific-module) - 3. [Shell Modules](#exploring-standard-modules-shell-modules) - 4. [Date and Time Modules](#exploring-standard-modules-date-and-time-modules) - 5. [Subprocess Module](#exploring-standard-modules-subprocess-module) - 6. [Argparse Module](#exploring-argparse-command-line-option-and-argument-parsing) - 6. [SQLite Module](#exploring-standard-modules-embedded-relational-database-module) ![Generic badge](https://img.shields.io/badge/Coming%20-Soon-blue) - 7. [XmlTree Module](#exploring-xmltree-module) ![Generic badge](https://img.shields.io/badge/Coming%20-Soon-blue) - 8. [JSON Module]( #exploring-json-module-exploring-json-module) - 8. [CSV Module]( #exploring-csv-module-exploring-csv-module) - 9. [Regular Expressions Module](#exprloting-standard-regular-expression-module) ![Generic badge](https://img.shields.io/badge/Coming%20-Soon-blue) - 10. [Compression Module](#exploring-compression-module) ![Generic badge](https://img.shields.io/badge/Coming%20-Soon-blue) - 11. [Platform Module](#exploring-platform-module) ![Generic badge](https://img.shields.io/badge/Coming%20-Soon-blue) - 12. [Signal Module](#exploring-standard-modules-signal-module) ![Generic badge](https://img.shields.io/badge/Coming%20-Soon-blue) - 13. [Socket Module](#exploring-standard-modules-socket-module) ![Generic badge](https://img.shields.io/badge/Coming%20-Soon-blue) - -- #### Exploring External Modules - - #### Network Modules - 1. [Netmiko Module](#exploring-standard-modules-netmiko-module) ![Generic badge](https://img.shields.io/badge/Coming%20-Soon-blue) - 2. [Twisted Module](#exploring-standard-modules-twisted-module) ![Generic badge](https://img.shields.io/badge/Coming%20-Soon-blue) - 3. [Ipaddress Module](#exploring-standard-modules-ipaddress-module) ![Generic badge](https://img.shields.io/badge/Coming%20-Soon-blue) - 4. [Netsnmp Module](#exploring-standard-modules-netsnmp-module) ![Generic badge](https://img.shields.io/badge/Coming%20-Soon-blue) - - #### DB Modules - 1. [SQLAlchemy Module](#exploring-standard-modules-sqlalchemy-module) ![Generic badge](https://img.shields.io/badge/Coming%20-Soon-blue) - ---- - -## `Getting Started` Standard Input, Output and Error - -Standard input, output and error (commonly referred to as `stdin`, `stdout` and `stderr`) are what's called pipes. - -These pipes are normally connected to the terminal window where you are working. - -When printing something (using `print()`), it goes to the `stdout` pipe by default; when your program needs to print errors (like a traceback in Python), it goes to the `stderr` pipe; and when your program requires input from a user or other programs, it goes to the `stdin` pipe. - -```bash -$ cat /etc/passwd | grep /bin/bash -# `\_ writes to stdout `\_ reads from stdin - -$ ls no_such_file.txt -# `\_ writes to stderr -``` - -Python built-in `sys` module provides `stdin`, `stdout` and `stderr` as a file-objects, exposing `read()`, `readlines()`, `write()`, `writelines()` methods, as shown below: - -```python -#!/usr/bin/env python3 -import sys - -# writing to stdout pipe -print ('Hello, world') -sys.stdout.write('Hello, world\n') - -# writing to stderr pipe -print("Error occured") -sys.stderr.write("Error occured\n") - -# reading single line from stdin pipe -sys.stdout.write('Username: ') -username = sys.stdin.readline() -print (username) - -# reading 'n' number of characters from stdin -print ('Enter few characters and press Ctrl-D') -data = sys.stdin.read(1024) -print('len(data):', len(data)) - -# reading lines (separated by newlines) from stdin -print('Enter few lines and press Ctrl-D') -lines = sys.stdin.readlines() -print ('total lines read:', len(lines)) -``` - ---- - -## `Getting Started` Working with files - -Python built-in `open` function is the standard interface for working with files. `open` returns a file object with familiar methods for performing read/write operations. - -``` -open(file, mode='r') -``` - -###### Common arguments: - -- __file:__ absolute or relative path of the file. e.g: `/etc/passwd`, `./ip-list.txt` -- __mode:__ an optional string specifying mode in which the file is opened. Default's to `r` for reading in text mode. Common values are: - - `w` write only *(truncates the file already exists)* - - `x` create and write to a new file _(if file already exists then open fails)_ - - `a` append to a file *(insert data to end of the file)* - - `+` updating a file (reading and writing). e.g: `r+` `w+` - - `b` binary mode for non-text files. Contents are returned as `byte` objects. - - `t` text mode (default). Contents are returned as `strings`. - -###### File object methods: - -- `.close()` -- `.read(size=-1)` read at most `n` characters. If `n` is negative or ommited, reads the whole file until `EOF`. -- `.readline()` Read single line until newline or `EOF`. -- `.readlines()` Read all newlines and returns as a list. -- `.write(data)` Write data to file. Returns number of characters written. -- `.writelines(list)` Write all data in the list. Useful for writing multiple lines to a file. - -##### Example - -```python -## Reading a file -r = open('/etc/passwd') -# same as: -# r = open('/etc/passwd', 'r') -passwd = r.readlines() -for line in passwd: - line = line.strip() - size = len(line) - print(size, line) -r.close() - -## Reading a file using `with` statement, automatically closes the file -with open('/etc/passwd') as f: - pass - -## Writing to a file -w = open('test.txt', 'w') -w.write('127.0.0.1\n') -w.flush() -lines = ['1.1.1.1\n', '2.2.2.2\n', '3.3.3.3\n'] -w.writelines(lines) -w.close() -``` ---- -### Handling Errors - -All `open` related errors raises `IOError` exception. - -```python -try: - f = open('/etc/passwd') -except IOError as e: - print ('Opps, something went wrong.') - print (e) -``` ---- - -#### Reading `/etc/passwd` and search each line for `/bin/bash` shell; when found print the line number and the line - -```python -#!/usr/bin/env python3 -# working-with-files-01.py - -def main(): - try: - with open('/etc/passwd') as f: - for no, line in enumerate(f, 1): - if '/bin/bash' in line: - line = line.strip() - print(f'{no} {line}') - except IOError as e: - print(e) - -if __name__ == '__main__': main() -``` - ---- - -#### Using `fileinput` High-level module - -`fileinput` module allows to quickly write a loop over standard input or a list of files. - -##### Example - -```python -#!/usr/bin/env python3 -# linescount-02.py +[![Read the guide](https://img.shields.io/badge/Read_the_guide-purutuladhar.com-9ece6a?style=flat-square)](https://purutuladhar.com/python-for-sys-admin/) +[![Try it free](https://img.shields.io/badge/Hands--on-iximiuz_Labs_Playground-7aa2f7?style=flat-square)](https://labs.iximiuz.com/playgrounds/python) +[![GitHub stars](https://img.shields.io/github/stars/tuladhar/Python-for-SysAdmin?style=flat-square)](https://github.com/tuladhar/Python-for-SysAdmin/stargazers) +[![PRs welcome](https://img.shields.io/badge/PRs-welcome-e0af68?style=flat-square)](CONTRIBUTING.md) -import fileinput +A practical, community-driven guide to **Python 3 for system administrators and DevOps engineers**. Each chapter teaches one module through the tasks you actually do on servers: reading configs and logs, running commands, checking disks and ports, and building your own command-line tools. -lines = 0 -for line in fileinput.input(): - lines += 1 +**📖 Read it as a website: [purutuladhar.com/python-for-sys-admin](https://purutuladhar.com/python-for-sys-admin/)** -print('totat lines:', lines) -``` - -```bash -$ cat /etc/passwd | python3 linescount.py -totat lines: 86 -$ python3 linescount.py /etc/services -totat lines: 13921 -$ python3 linescount.py /etc/services /etc/passwd /etc/hosts -totat lines: 14023 -``` - -By default, `fileinput.input()` will read all lines from files given as an argument to the script; if no arguments given then defaults to standard input. - ---- - -## `Getting Started` Command-line Arguments - -`sys` module provides `argv` variable containing the list of arguments passed to the script when executed as a command-line application. - ->NOTE: The first argument `sys.argv[0]` is always the name of the script itself. - -```python -#!/usr/bin/env python3 -# argv_01.py - -import sys - -print ('sys.argv:', sys.argv) -print ('length:', len(argv)) -``` -```bash -$ python3 args_01.py --help -['argv-01.py', '--help'] -2 -$ python3 args_01.py 1 2 3 -['argv-01.py', '1', '2', '3'] -4 -``` - -#### Accept specific number of arguments and fail if not satistified. - -```python -#!/usr/bin/env python3 -# args-02.py -import sys - -# NOTE: [1:] excludes the first item at index 0, i.e script name -argv_len = len(sys.argv[1:]) +⭐ If this guide helps you, please **give it a star**. It helps other sysadmins find it. -if not argv_len == 2: - sys.exit(f'invalid number of arguments (expected 2, given: {argv_len})') +## Practice hands-on, for free -print('two arguments are:', sys.argv[1:]) -``` +You don't need a server. The **[iximiuz Labs Python Playground](https://labs.iximiuz.com/playgrounds/python)** gives you a real Linux VM with root access, the latest Python 3, `uv`, Docker and VS Code, right in your browser. Start it, then: ```bash -$ python args_02.py -invalid number of arguments (expected 2, given: 0) -$ python args_02.py 1 -invalid number of arguments (expected 2, given: 1) -$ python args_02.py 1 2 -two arguments are: ['1', '2'] -$ python args_02.py 1 2 3 -invalid number of arguments (expected 2, given: 3) -``` - -#### Simple Implementation of `grep' command - -```python -#!/usr/bin/env python3 -# grep.py - -import sys - -script = sys.argv[0] - -def print_usage(): - sys.exit(f'Usage: python {script} pattern') - -def main(argv): - if not len(argv) == 1: - print_usage() - - pattern = argv[0] - - for line in sys.stdin: - if pattern in line: - print(line.strip()) - -if __name__ == '__main__': - main(sys.argv[1:]) -``` - -```bash -$ cat /etc/services | python3 grep.py 8080 -http-alt 8080/udp # HTTP Alternate (see port 80) -http-alt 8080/tcp # HTTP Alternate (see port 80) -``` - ---- - -#### Improvement Exercises -- Extend `grep.py` to read from a file instead of standard input, and can be run as: - -```bash -$ python3 grep.py 8080 /etc/services -``` - -- Extend `grep.py` to read from a file if given as a second argument or default back to read from standard input similar to what `grep` does. - -```bash -$ cat /etc/services | python3 grep.py 8080 -# and also should works as -$ python3 grep.py 8080 /etc/services -``` - ---- - -## `Exploring Standard Modules` Operating System (OS) Module - -Python built-in `os` module exposes operating system dependent functionality in a portable way, thus works across many different platforms. - -``` -import os +git clone https://github.com/tuladhar/Python-for-SysAdmin.git +cd Python-for-SysAdmin/examples +cat /etc/passwd | python3 grep.py bash ``` -###### Working with environmental variables: +## Learn step by step with AI -- `os.environ` a dictionary mapping system environment variables. e.g. `os.environ.get('SHELL')` -- `os.getenv(key)` retrieve a specific variable. -- `os.putenv(key, value)`. change variable to specific value. e.g. `os.putenv('HOME', '/opt')` - -###### Working with files and directories: - -- `os.tmpnam` returns a unique file name that can be used to create temporariry file. `mktemp()` from `tempfile` module is more secure. -- `os.mkdir(path)` `os.rmdir(path)` `os.chdir(path)` `os.listdir(path)` -- `os.getcwd()` returns current working directory as string. Similar to `pwd` command. -- `os.stat(path)` similar to `stat` command -- `os.walk(path)` recursively walk the dictionary tree, similar to `ls -R`. Returns generator yielding 3-tuple `(dirpath, dirnames, files)` - -##### Example - -```bash ->>> import os - -# environment variables ->>> os.environ['SHELL'] # or os.environ.get('SHELL') or os.getenv('SHELL') -'bash' - -# Get a temporary filename using `tempfile` module ->>> from tempfile import mktemp ->>> temp = mktemp() -'/var/folders/6s/4xn2fv852_1ghssypng0wwfw0000gn/T/tmp15O9aR' - -# Create the temporary file and write 'test' ->>> with open(temp, 'w') as f: -... f.write('test\n') - -# Get the file stat, such as creation timestamp (ctime) ->>> st = os.stat(temp) ->>> st.st_ctime -1436466688.0 - -# convert timestamp to human readable format, we'll cover date & time later. ->>> import datetime ->>> d = datetime.datetime.fromtimestamp(st.st_ctime) ->>> d.year # d.month, d.hour and so on... -2016 -``` --- -###### Working with Path names `os.path`: - -- `os.path.abspath(path)` get absolute path. -- `os.path.basename(path)` get the filename excluding the directory part. Opposite of `os.path.dirname` which excludes filename part and returns directory path. -- `os.path.exists(path)` returns `True` if path exists else `False`. -- `os.path.getsize(path)` return size (in bytes) for a given path. -- `os.path.isfile(path)`, `os.path.isdir(path)` returns `True` or `False` if path is file or a directory. -- `os.path.getctime(path)`, `os.path.getmtime(path)` Similar to `os.stat(path).ctime`, `os.stat(path).mtime()` - -#### Learn more at [os.path documentation](https://docs.python.org/3.7/library/os.path.html) - -##### Example - -```bash ->>> os.path.isdir('/etc') -True - ->>> os.chdir('/etc') - ->>> os.getcwd() -'/etc' - ->>> os.path.abspath('hosts') -'/etc/hosts' - ->>> os.path.isfile('/etc/hosts') -True - ->>> os.path.getsize('/etc/hosts') -475 - ->>> print (os.path.basename('/etc/passwd')) -'passwd' - ->>> print (os.path.dirname('/etc/passwd')) -'/etc' -``` - - -###### Process related functions: - -- `os.getpid()` get id of current process and `os.getppid()`to get parent process id. -- `os.system(command)` execute a command and returns exit code. - -###### Getting System Informations: - -- `os.uname()` returns a 5-tuple `(sysname, nodename, release, version, machine)` identifying the current OS. Similar to `uname -a` command. -- `os.getloadavg()` returns 3-tuple containing 1-min, 5-min and 15-min load average. - --- - -#### Print size (in bytes) of all files in a given directory - -```python -#!/usr/bin/env python3 -# filesizes.py - -import os -import sys - -script = sys.argv[0] - -def print_usage(): - print(f' >> {sys.stderr}, "Usage: python3 {script} DIR"') - sys.exit(1) - -def filesizes(path): - ''' calculate and print size of each file in a given directory. ''' - - for dirpath, dirnames, filenames in os.walk(path): - for filename in filenames: - filepath = os.path.join(dirpath, filename) - _bytes = os.path.getsize(filepath) - print (f'{_bytes}, {filepath}') - -def main(argv): - if not len(argv) == 1: - print_usage() - - path = argv[0] - filesizes(path) - -if __name__ == '__main__': - main(sys.argv[1:]) - -``` - ->```bash - $ python3 filesizes.py . - 678 ./filesizes.py - ``` - -#### [Learn more about OS module](https://docs.python.org/3.7/library/os.html) - ---- -## `Exploring Standard Modules` System-specific Module - -Python built-in `sys` module exposes system-specific parameters and functions. This module provides access to some variables used or maintained by the interpreter and functions that interact strongly with the interpreter. `sys` module is always available. - -``` -import sys -``` - - - -###### Commonly used variables and functions: - -- `sys.argv` contains list of command-line arguments. *Already covered.* -- `sys.exit([arg])` exit the program. `arg` is optional, can be `0` to indicate success, `> 0` for failure or `string` to display the errors during exit. -- `sys.version` stores version of Python installed. -- `sys.stdin` `sys.stdout` `sys.stderr` File objects corresponding to the interpreter's standard input, output and error pipes. -- `sys.platform` stored the name of the platofrm Python is running. Such as `darwin` for MacOS, `linux` for Linux and others -- `sys.path` A list of strings that specified the search path while importing modules via `import` statement. -- `sys.modules` A dictionary mapping the `{ 'module_name': 'module_path', ... }` which have already been loaded. - ---- - -```python -#!/usr/bin/env python3 -# sys-01.py - -import sys -from sys import argv - -print (f''' -Python version installed: {sys.version} - -Python running on platforn: {sys.platform} -''') - -if len(argv) == 10: - sys.exit('error: too many arguments') - -print(f''' -argv = {argv} -len(argv) = {len(argv)} -''') - -print ('Printing to stdout') -print (f'>> {sys.stderr}, "Printing to stderr"') - -print(f''' -total modules search path: {len(sys.path)} -total modules loaded: {len(sys.modules)} -''') - -# success -sys.exit(0) -``` - -###### Output should look like this - -```bash -$ python3 sys-01.py - -Python version installed: 3.7.4 (default, Jul 9 2019, 16:48:28) -[GCC 8.3.1 20190223 (Red Hat 8.3.1-2)] - -Python running on platforn: linux - - -argv = ['sys_01.py'] -len(argv) = 1 - -Printing to stdout ->> <_io.TextIOWrapper name='' mode='w' encoding='UTF-8'>, "Printing to stderr" - -total modules search path: 7 -total modules loaded: 57 - - -$ echo $? -0 -``` - -#### [Learn more about sys module](https://docs.python.org/3.7/library/sys.html) - ---- - -## `Exploring Standard Modules` Shell Modules - -### shutil module — High-level file operations - -The `shutil` module provides high-level operations on files or collection of files. - -###### Copy Operations: - -- `shutil.copy(src, dst)` Copy src file to dst file or directory. -- `shutil.copymode(src, dst)` Copy permission mode of src file to dst file. -- `shutil.copystat(src, dst)` Copy permission mode, modification and creation date from src file to dst file. -- `shutil.copy2(src, dst)` Similar to `cp -p` command or equivalent of `shutil.copy` and `shutil.copystat`. - -###### Move Operations: - -- `shutil.move(src, dst)` Move src file to dst file or directory. - -#### [Learn more about shutil module](https://docs.python.org/3.7/library/shutil.html) - ---- - -### glob module — Unix style pathname pattern expansion - -The `glob` module finds all the pathnames matching a specified pattern according to the rules used by the Unix shell. - -- `glob.glob(pattern)` Return a list of path names that match the path pattern. Path can be absolute `/usr/local/bin/*.py` or relative `local/bin/*.py`. - -##### Example - -```bash ->>> import glob ->>> glob.glob('/etc/sysconfig/network-scripts/ifcfg*') -['/etc/sysconfig/network-scripts/ifcfg-venet0', - '/etc/sysconfig/network-scripts/ifcfg-lo'] +Stuck on a concept? Install the free [`/step-by-step` Claude skill](https://github.com/tuladhar/my-claude-skills-as-devops-engineer). It explains any topic one short sentence at a time, and waits for you to say "understood" before it moves on: ->>> glob.glob('/etc/*.conf') -['/etc/vnstat.conf', - '/etc/sudo.conf', - '/etc/resolv.conf', - '/etc/host.conf', - '/etc/logrotate.conf'] +```text +/step-by-step how subprocess.run captures stdout and the exit code ``` -#### [Learn more about glob module](https://docs.python.org/3.7/library/glob.html) - ---- - -## `Exploring Standard Modules` Date and Time Modules - -### time module — Clock time - -The `time` module exposes the time-related functions from the underlying C library. - -###### Commonly used functions: - -- `time.time()` returns the number of seconds since the start of the epoch as a floating-point value. -- `time.ctime()` returns a human-friendly date and time representation. -- `time.gmtime()` returns an object containing current time in UTC format. -- `time.localtime()` returns an object containing the current time in current time zone. -- `time.tzset()` sets the time zone based on `TZ` environment variable: `os.environ.get('TZ')` - -##### Example - -```bash ->>> import time ->>> time.time() -1459924583.396017 - ->>> # current time in UTC ->>> utc = time.gmtime() ->>> dir(utc) -['tm_hour', - 'tm_isdst', - 'tm_mday', - 'tm_min', - 'tm_mon', - 'tm_sec', - 'tm_wday', - 'tm_yday', - 'tm_year'] - ->>> # current time in GMT by updating timezone ->>> import os ->>> os.putenv('TZ', 'GMT') # or os.environ['TZ'] = 'GMT' ->>> time.tzset() ->>> gmt = '{} {}'.format(time.ctime(), time.tzname[0]) -``` - -#### [Learn more about time module](https://docs.python.org/3.7/library/time.html) - ---- - -## datetime module — Date and Time Value Manipulation - -The `datetime` module includes functions and classes for doing date and time parsing, formatting, and arithmetic. - -##### Commonly used functions: - -- `datetime.date.today()` returns current date object without the time -- `datetime.datetime.today()` returns current date and time object -- `datetime.datetime.fromtimestamp(float)` convert unix timestamp to datetime object -- `datetime.timedelta` future and past dates can be calculated using basic arithmetic (+, -) on two datetime objects, or by combining a datetime with a timedelta object. - -##### Example - -```python ->>> import datetime ->>> today_date = datetime.date.today() ->>> ten_days = datetime.timedelta(days=10) ->>> today_date - ten_days # past ->>> today_date + ten_days # future -``` - -###### Alternate formats can be generated using `strftime()` and `strptime` to convert formatted string to `datetime` object. - -```bash ->>> import datetime - -# convert datetime to custom format ->>> format = "%a %b %d %H:%M:%S %Y" ->>> today = datetime.datetime.today() ->>> today.strftime(format) -'Mon Oct 14 17:56:24 2019' - -# convert formatted string to datetime object ->>> datetime.datetime.strptime('Mon Oct 14 17:56:24 2019', format) -datetime.datetime(2019, 10, 14, 17, 56, 24) -``` - -#### [Learn more about datetime module](https://docs.python.org/3.7/library/datetime.html) - ---- - -## `Exploring Standard Modules` Subprocess Module - -### subprocess module — Subprocess management - -The `subprocess` module allows to run new processes, connect to their input/output/error pipes, and obtain their return codes. - -The module defines a many helper functions and a class called `Popen` which allows to set up the new process so the parent can communicate with it via pipes. - - -### Running external commands - -To run an external command without interacting with, use `subprocess.call(command, shell=True)` function. - -```python ->>> import subprocess ->>> rc = subprocess.call('ls -l /etc', shell=True) -0 ->>> rc = subprocess.call('ls -l no_such_file.txt', shell=True) -1 -``` - -Setting the **shell** argument to a **True** value causes subprocess to spawn a shell process (normally bash), which then runs the command. Using a shell means that variables, glob patterns, and other special shell features in the command string are processed before the command is run. - -```py ->>> import subprocess ->>> subprocess.call('echo $PATH' ) - -# will return error -subprocess.call('echo $PATH', shell=True) -# will print the shell PATH variable value -``` - --- - -### Error Handling - -The return value from `subprocess.call()` is the exit code of the program and is used to detect errors. The `subprocess.check_call()` function works like `call()`, except that the exit code is checked, and if it returns non-zero, then a `subprocess.CalledProcessError` exception is raised. - -```python -#!/usr/bin/env python3 -# check_call.py - -import sys -import subprocess - -try: - cmd = 'false' - print ('running command:',cmd) - subprocess.check_call(cmd, shell=True) -except subprocess.CalledProcessError as error: - sys.exit(f'error: {error}') -``` - -```bash -$ python3 check_call.py -running command: false -error: Command 'false' returned non-zero exit status 1 -``` - ---- - -### Capturing Command Output - -To run an external command and capture it's output, use `check_output(command, shell=True)` to capture the output for later processing. If command returns non-zero, then a `CalledProcessError` exception is raised similar to `check_call`. - ->Execute `cat /etc/hosts` and write the output to a file `hosts.txt` - -```python -#!/usr/bin/env python3 -# capture_output.py - -import subprocess -import sys - -try: - cmd = 'cat /etc/hosts' - print('running command:', cmd) - output = subprocess.check_output(cmd, shell=True, stderr=subprocess.STDOUT) -except subprocess.CalledProcessError as error: - sys.exit('error: {error}') -else: - print('success!') - with open('hosts.txt', 'w') as f: - f.write(output) - #this should give an error in python3.6+ -``` - -By default, `check_output` captures outputs written to `stdout`. Setting the `stderr=subprocess.STDOUT` causes `stderr` outputs to redirected to `stdout`, so errors can be captured as well. - ---- - -### Working directory with Popen - -The `call()`, `check_call()`, and `check_output()` are wrappers around the `Popen` class. Using `Popen` directly gives more control over how the command is run and how its input and output streams are processed. - -#### One-Way Communication with a Process - -To run a process and capture it's output, set the `stdout` and `stderr` arguments to `subprocess.PIPE` and call `communicate()`. - -`communicate()` returns 2-tuple `(stderr_output, stderr_putput)` - -```python -#!/usr/bin/env python3 -# one-way.py -import subprocess -import sys - -script = sys.argv[0] - -def main(argv): - if not len(argv) == 1: - sys.exit(f'usage: python3 {script} command') - cmd = sys.argv[1] - print ('running command:', cmd) - proc = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) - stdout, stderr = proc.communicate() - print(f''' -exit code: {proc.poll()} - -stdout: -{stdout or None} - -stderr: -{stderr or None} -''') - -if __name__ == '__main__': - main(sys.argv[1:]) -``` - -```bash -$ python3 one_way.py ls -running command: ls - -exit code: 0 - -stdout: -b'capture_output.py\ncheck_call.py\nhosts.txt\none_way.py\nsys_01.py\n' - -stderr: -None - -``` - ---- - -### Bidirectional Communication with a Process - -To set up the Popen instance for reading and writing at the same time, pass additional argument `stdin=subprocess.PIPE`. - -```python -#!/usr/bin/env python3 -# bidirectional.py -import subprocess -from subprocess import PIPE -import sys - -cmd = 'bc' -send = '1 + 1\n' - -print('running command:', cmd, 'and sending input:', send) - -proc = subprocess.Popen(cmd, shell=True, stdin=PIPE, stdout=PIPE, stderr=PIPE) -stdout, stderr = proc.communicate(send) - -print(f''' -exit code: {proc.poll()} - -stdin: -{send} - -stdout: -{stdout or None} - -stderr: -{stderr or None} -''') -``` - -```bash -$ python3 bidirectional.py -running command: bc and sending input: 1 + 1 - -exit code: 0 - -stdin: -1 + 1 - -stdout: -2 - -stderr: -None -``` - -#### [Learn more about subprocess module](https://docs.python.org/3.7/library/subprocess.html?highlight=subprocess#module-subprocess) - -## `Exploring Argparse` Command-Line Option and Argument Parsing - -Python built-in `argparse` is parser for command-line options, arguments and subcommands. The argparse module provides argument management just like `sys.argv`, but with options, e.g it generates help and usage messages and issues errors when users give the program invalid arguments. -Let’s show the sort of functionality by making use of the ls command: - -```bash -$ ls -examples LICENSE README.md -$ ls -l -total 44 -drwxrwxr-x. 4 que que 4096 Oct 14 18:05 . -drwxrwxr-x. 24 que que 4096 Oct 13 15:32 .. -drwxrwxr-x. 2 que que 4096 Oct 14 18:48 examples -drwxrwxr-x. 8 que que 4096 Oct 15 01:01 .git --rw-rw-r--. 1 que que 1210 Oct 13 15:32 LICENSE --rw-rw-r--. 1 que que 24357 Oct 15 01:02 README.md -$ ls --help -Usage: ls [OPTION]... [FILE]... -List information about the FILEs (the current directory by default). -Sort entries alphabetically if none of -cftuvSUX nor --sort is specified. -... -``` - -A few concepts we can learn from the four commands: - -- When you run the "ls -l" command with options, it will default displaying the contents of the current directory -- The "-l" is knowns as an "optional argument" -- If you want to display the help text of the ls command, you would type "ls --help" - -To start using the argparse module, we first have to import it. - -```py ->>> import argparse -``` - -#### Intro to positional arguments - - The following code is a Python program that takes a list of integers and produces either the sum or the max: - -##### Example - -```py -#!/usr/bin/env python3 -#app.py -import argparse - -parser = argparse.ArgumentParser(description='Process some integers.') -parser.add_argument('integers', metavar='N', type=int, nargs='+', - help='an integer for the accumulator') -parser.add_argument('--sum', dest='accumulate', action='store_const', - const=sum, default=max, - help='sum the integers (default: find the max)') - -args = parser.parse_args() -print(args.accumulate(args.integers)) -``` - -Assuming the Python code above is saved into a file called `app.py`, it can be run at the command line and provides useful help messages - -```bash -$ app.py -h -usage: prog.py [-h] [--sum] N [N ...] - -Process some integers. - -positional arguments: - N an integer for the accumulator - -optional arguments: - -h, --help show this help message and exit - --sum sum the integers (default: find the max) - -$ app.py 1 2 3 4 -4 - -$ app.py 1 2 3 4 --sum -10 -``` - -### Creating a parser - -The first step in using the `argparse` is creating an `ArgumentParser` object: - -```py ->>> parser = argparse.ArgumentParser(description='Process some integers.') -``` - -The `ArgumentParser` object will hold all the information necessary to parse the command line into python data types. - -### Adding arguments - -Filling an`ArgumentParser` with information about program arguments is done by making calls to the `ArgumentParser.add_argument` method. Generally, these calls tell the `ArgumentParser` how to take the strings on the command line and turn them into objects. This information is stored and used when `ArgumentParser.parse_args` is called. For example: - -```py ->>> parser.add_argument('integers', metavar='N', type=int, nargs='+', -... help='an integer for the accumulator') ->>> parser.add_argument('--sum', dest='accumulate', action='store_const', -... const=sum, default=max, -... help='sum the integers (default: find the max)') -``` - -Later, calling `parse_args` will return an object with two attributes, integers and accumulate. The integers attribute will be a list of one or more ints, and the accumulate attribute will be either the `sum` function, if --sum was specified at the command line, or the `max` function if it was not. - -### Parsing arguments - -`ArgumentParser` parses args through the `ArgumentParser.parse_args` method. This will inspect the command-line, convert each arg to the appropriate type and then invoke the appropriate action. In most cases, this means a simple namespace object will be built up from attributes parsed out of the command-line: - -```py ->>> parser.parse_args(['--sum', '7', '-1', '42']) -Namespace(accumulate=, integers=[7, -1, 42]) -``` - -In a script,`ArgumentParser.parse_args` will typically be called with no arguments, and the `ArgumentParser` will automatically determine the command-line args from `sys.argv`. - -### ArgumentParser objects - -Create a new `ArgumentParser` object. Each parameter has its own more detailed description below, but in short they are: - -- `description` - Text to display before the argument help. -- `epilog` - Text to display after the argument help. -- `add_help` - Add a -h/--help option to the parser. (default: True) -- `argument_default` - Set the global default value for arguments. (default: None) -- `parents` - A list of `ArgumentParser` objects whose arguments should also be included. -- `prefix_chars` - The set of characters that prefix optional arguments. (default: '-') -- `fromfile_prefix_chars` - The set of characters that prefix files from which additional arguments should be read. (default: None) -- `formatter_class` - A class for customizing the help output. -- `conflict_handler` - Usually unnecessary, defines strategy for resolving conflicting optionals. -- `prog` - The name of the program (default:`sys.argv[0]`) -- `usage` - The string describing the program usage (default: generated) - -#### [Learn more about argparse module](https://docs.python.org/3.7/library/argparse.html) - -## `Exploring SQLite Module` exploring-standard-modules-embedded-relational-database-module - -SQLite is a C-language library that implements a SQL like database engine which is relatively quick, serverless and self-contained, high-reliable. SQLite comes built-in with most of the moden software, hardware devices and browsers, thus Python also has embedded SQLite engine named sqlite3. - -To Start using the sqlite3 library: - -```py ->>> import sqlite3 -``` - -#### Commonly used functions: - -- `sqlite3.connect()` - A connection object is created using the connect() function e.g **connection = sqlite.connect('name_of_file_db.db')** -- `connection.cursor()` - To execute SQLite statements, cursor object is needed. You can create it using the cursor() method. e.g **cursor_object = connection.cursor()** -- `connection.execute()` - To create a table in SQLite3, you can use the Create Table, Insert Into Table, Update Table, or Select query with the execute() method of SQLite library. For example **cursor_object.execute("CREATE TABLE employees()"); connection.commit()** -- `connection.commit()` - The commit() method saves all the changes we make. -- `cursor_object.fetchall()` - To fetch the data from a database we will execute the SELECT statement and then will use the fetchall() method of the cursor object to store the values into a variable, e.g **cursor_object.execute('SELECT * FROM employees') ; rows = cursor_object.fetchall()** -- `cursor_object.rowcount()` - The SQLite3 rowcount is used to return the number of rows that are affected or selected by the latest executed SQL query -- `cursor_object.executemany()` - It can use the **executemany** statement to insert multiple rows at once. -- `connection.close()` - You are done with your database, it is a good practice to close the connection with close() method. e.g. **connection.close()** - -#### [Learn More about SQLite3 Module](https://docs.python.org/3.7/library/sqlite3.html) - -## `Exploring XmlTree Module` exploring-xmltree-module - - -#### [Learn More about XmlTree Module](https://docs.python.org/3.7/library/xml.etree.elementtree.html#module-xml.etree.ElementTree) - - - - -## `Exploring JSON Module` exploring-json-module - -JSON is text, written with JavaScript object notation. JSON is a syntax for storing and exchanging data. -It is commonly used for transmitting data in web applications (e.g., sending some data from the server to the client, so it can be displayed on a web page -and vice versa - -- `json.loads()` -- take a file object and returns the json object. A JSON object contains data in the form of key/value pair. The keys are strings and the values are the JSON types - -- `json.dumps()` --json.dumps() function converts a Python object into a json string -.It is the exact opposite of json.loads. - -THIS IS THE ENCODING DECODING LIST - - JSON -Python - - 1)object- DICT - 2)array - list - 3)string - str - 4)int - int - 5)real - float - 6)true - true - 7)False - False - 8)NULL - NONE - - - - - - ` Encoding is from python to JSON(final type)` ->>> json.JSONEncoder().encode({"foo": ["bar", "baz"]}) -'{"foo": ["bar", "baz"]}' - - -- `Decoding is from JSON to python(final type)` - -## Encoding functions - -- `iterencode(o)` --Encode the given object, o, and yield each string representation as available. For example: ->>>for chunk in json.JSONEncoder().iterencode(bigobject): - mysocket.write(chunk)] - -` -sort-keys` -Sort the output of dictionaries alphabetically by key. - -`-h, --help¶`- help box - -`infile`-to check your Json file for syntax +## Contents -`outfile`-Write the output of the infile to the given outfile +### Getting Started +1. [Set Up Your Lab](chapters/01-set-up-your-lab.md) +2. [Standard Input, Output and Error](chapters/02-standard-io.md) +3. [Working with Files](chapters/03-working-with-files.md) +4. [Command-line Arguments](chapters/04-command-line-arguments.md) -## Note -If the optional infile and outfile arguments are not specified, sys.stdin and sys.stdout will be used respectively: +### Standard Library +5. [The `os` Module](chapters/05-os-module.md) +6. [The `sys` Module](chapters/06-sys-module.md) +7. [`shutil` and `glob`](chapters/07-shutil-and-glob.md) +8. [Date and Time](chapters/08-date-and-time.md) +9. [Running Commands with `subprocess`](chapters/09-subprocess.md) +10. [Building CLIs with `argparse`](chapters/10-argparse.md) - `json.tool `- to validate and pretty-print JSON objects. - - `raw_decode`- This can be used to decode a JSON document from a string that may have extraneous data at the end. +### Data and Networking +11. [Working with JSON](chapters/11-json.md) +12. [Working with CSV](chapters/12-csv.md) +13. [SQLite: a Database in a File](chapters/13-sqlite.md) +14. [Network Checks with `socket`](chapters/14-socket.md) -#### [Learn More about JSON Module](https://docs.python.org/3.7/library/json.html) +### Help wanted 🙌 +Regular expressions, logging, compression, XML, platform, signals, `ipaddress`, concurrency, HTTP APIs, SSH automation (`paramiko`), `psutil`, `netmiko`, `boto3`, Docker and Kubernetes clients, Jinja2 templating, and testing with `pytest`. +**[Pick one and write it →](CONTRIBUTING.md)** -## `Exploring CSV Module` exploring-csv-module -CSV - comma-separated values file is a text file with it's content delimited by comma (most often but any other delimiter is acceptable, yet it is advised to stick to the standards) defined by RFC 4180. -These files are really useful when it comes to share, read and save data. Structure of such file is very simple: -```csv -header1,header2,header3 -datacell11,datacell12,datacell13 -datacell21,datacell22,datacell23 -datacell31,datacell32,datacell33 -``` -You can easily read and write CSV files with Python using `csv` module. To open CSV file we need code like this: -```python -import csv -with open('file.csv') as f: - f_csv = csv.reader(f, delimiter=',', quotechar='"') - headers = next(f_csv) # this line uses next() function to save first row of the file and skip it. Rest is our data. - # now we are ready to process our rows. Example: - for row in f_csv: - print(row[0], row[1], row[2]) -``` -Script would just print data like this: -```shell -$> datacell11 datacell12 datacell13 -$> datacell21 datacell22 datacell23 -$> datacell31 datacell32 datacell33 -``` -Here's explanation for some parameters of `csv.reader`: +All runnable scripts are in [`examples/`](examples/). -`delimiter` - is as it name shows - character or set of them that determines where are columns of value and how they are separated +## Contributing -`quotechar` - is a char starting and ending a quote in our CSV file. It prevents our script from breaking output when we would have somethin like: `datacell21,"datacell22",datacell23` +This guide is written by the community. Fixing a typo is as welcome as writing a new chapter. Merged chapters appear on the website automatically. Read [CONTRIBUTING.md](CONTRIBUTING.md) to get started, or [open an issue](https://github.com/tuladhar/Python-for-SysAdmin/issues/new?template=chapter.yml) to propose a topic. -If the file is more complicated than this (and it probably will) it is advised to use DictReader. It would look like this: -```python -import csv -with open('file.csv') as f: - f_csv = csv.DictReader(f, delimiter=',', quotechar='"') - headers = next(f_csv) # this line uses next() function to save first row of the file and skip it. Rest is our data. - # now we are ready to process our rows. Example: - for row in f_csv: - print(row['header1'], row['header2'], row['header3']) -``` -Instead of column indexes it is possible to use their names from header. - -To write file we can simply do this: -```python -import csv -data = [ - ['data1', 'data2', 'data3'], - ['data4', 'data5', 'data6'] - # ... -] -with open('newfile.csv', 'w') as nf: - headers = ['header_1', 'header_2', 'header_3'] - csv_writer = csv.writer(nf) - csv_writer.writerow(headers) - csv_writer.writerows(data) -``` -We use `writerow` for writing header for our data and then `writerows` to simply handle a few(hundred) rows of data - -Alternatively we DictWriter can be used: -```python -import csv - -data = [ - {'header_1': 'data1', 'header_2': 'data2', 'header_3': 'data3'}, - {'header_1': 'data4', 'header_2': 'data5', 'header_3': 'data6'}, - {'header_1': 'data7', 'header_2': 'data8', 'header_3': 'data9'} -] -with open('countries.csv', 'w', encoding='UTF8', newline='') as f: - headers = ['header_1', 'header_2', 'header_3'] - writer = csv.DictWriter(f, fieldnames=headers) - writer.writeheader() - writer.writerows(data) -``` +## Credits -#### [Learn More about CSV Module](https://docs.python.org/3/library/csv.html) +- Author: [Puru Tuladhar](https://github.com/tuladhar) +- Editor and maintainer: [Silent Mobius](https://github.com/silent-mobius) +- And [everyone who contributed](https://github.com/tuladhar/Python-for-SysAdmin/graphs/contributors) ❤️ +Licensed under the terms in [LICENSE](LICENSE). diff --git a/chapters/01-set-up-your-lab.md b/chapters/01-set-up-your-lab.md new file mode 100644 index 0000000..a8f5abf --- /dev/null +++ b/chapters/01-set-up-your-lab.md @@ -0,0 +1,67 @@ +# Set Up Your Lab + +You learn Python for system administration by **running** things: reading `/etc/passwd`, starting processes, checking ports. So before the first chapter, get a Linux box with Python on it. + +You have two options. Pick one. + +## Option 1: A free Linux VM in your browser (recommended) + +The [iximiuz Labs Python Playground](https://labs.iximiuz.com/playgrounds/python) gives you a real Linux VM with root access, the latest Python 3, `uv`, `pyenv`, Docker and VS Code. It starts in seconds and there is no paywall. You only need to sign in. + +1. Open the [Python Playground](https://labs.iximiuz.com/playgrounds/python). +2. Sign in and click **Start playground**. +3. Open the terminal tab and check your Python version: + +```bash +python3 --version +``` + +4. Clone this guide so every example is on the machine: + +```bash +git clone https://github.com/tuladhar/Python-for-SysAdmin.git +cd Python-for-SysAdmin/examples +ls +``` + +Because it is a throwaway VM, you can break things safely. Delete files, kill processes, fill the disk. Nothing touches your own laptop. + + + +## Option 2: Your own Linux or macOS machine + +Most Linux distributions and macOS already ship Python 3. Check it: + +```bash +python3 --version +``` + +You want **Python 3.10 or newer**. Every example in this guide uses only the standard library, so there is nothing to install with `pip`. + +If you need a newer Python, [uv](https://docs.astral.sh/uv/) is the quickest way to get one without touching the system Python: + +```bash +curl -LsSf https://astral.sh/uv/install.sh | sh +uv python install 3.13 +uv run --python 3.13 python --version +``` + +> Never upgrade or remove the system Python on a server. Tools like `dnf`, `apt` and many agents depend on it. Use `uv` or a virtual environment instead. + +## How to use this guide + +- Each chapter introduces one module and ends with a small, real script. +- Type the examples yourself instead of copy-pasting. You remember what your fingers typed. +- Every script lives in the [`examples/`](https://github.com/tuladhar/Python-for-SysAdmin/tree/main/examples) folder, so you can compare your version with the reference. +- Try the **exercises** at the end of a chapter before you move on. + +## Stuck? Learn it step by step with AI + +If a concept doesn't click, use the free [`/step-by-step` Claude skill](https://github.com/tuladhar/my-claude-skills-as-devops-engineer). It explains any topic one short sentence at a time and waits for you to say "understood" before moving on, so you never get a wall of text: + +```text +/step-by-step how subprocess.run captures stdout and the exit code +/step-by-step what os.walk yields for each directory +``` diff --git a/chapters/02-standard-io.md b/chapters/02-standard-io.md new file mode 100644 index 0000000..a7e9c06 --- /dev/null +++ b/chapters/02-standard-io.md @@ -0,0 +1,79 @@ +# Standard Input, Output and Error + +Every process on a Unix system starts with three open streams: standard input (`stdin`), standard output (`stdout`) and standard error (`stderr`). When you run a command in a terminal, all three are connected to that terminal. + +- `print()` writes to `stdout`. +- Errors and tracebacks go to `stderr`. +- When your program reads input from the user or from a pipe, it reads `stdin`. + +```bash +$ cat /etc/passwd | grep /bin/bash +# \_ writes to stdout \_ reads from stdin + +$ ls no_such_file.txt +# \_ writes to stderr +``` + +Keeping `stdout` for data and `stderr` for messages is what makes your scripts play nicely in pipelines: `script.py | sort` sorts the data, while errors still show up on screen. + +## The `sys` streams + +The built-in `sys` module exposes the three streams as file objects with `read()`, `readline()`, `readlines()` and `write()` methods. + +```python +#!/usr/bin/env python3 +# stdio.py +import sys + +# write to stdout +print("Hello, world") +sys.stdout.write("Hello, world\n") + +# write to stderr +print("Something went wrong", file=sys.stderr) +sys.stderr.write("Something went wrong\n") + +# read a single line from stdin +username = input("Username: ") +print(f"Hi, {username}") + +# read everything until EOF (press Ctrl-D in a terminal) +print("Enter a few lines and press Ctrl-D", file=sys.stderr) +lines = sys.stdin.readlines() +print("total lines read:", len(lines)) +``` + +> `print(..., file=sys.stderr)` is the modern way to print errors. You'll still see `sys.stderr.write()` in older code; both work. + +## Iterating over `stdin` + +Most filters you write read `stdin` line by line. Iterating over `sys.stdin` does that without loading everything into memory, so it works on a 10 GB log file too: + +```python +#!/usr/bin/env python3 +# upper.py +import sys + +for line in sys.stdin: + sys.stdout.write(line.upper()) +``` + +```bash +$ echo "hello sysadmin" | python3 upper.py +HELLO SYSADMIN +``` + +## Redirecting streams in the shell + +Because your script uses the standard streams, the shell can redirect them: + +```bash +$ python3 stdio.py > out.txt # stdout to a file, stderr to screen +$ python3 stdio.py 2> errors.txt # stderr to a file +$ python3 stdio.py > all.txt 2>&1 # both to the same file +``` + +## Exercises + +- Write `count.py` that reads `stdin` and prints the number of lines, words and characters, like `wc`. +- Make it print a warning to `stderr` if the input is empty, and still print `0 0 0` to `stdout`. diff --git a/chapters/03-working-with-files.md b/chapters/03-working-with-files.md new file mode 100644 index 0000000..fca167e --- /dev/null +++ b/chapters/03-working-with-files.md @@ -0,0 +1,130 @@ +# Working with Files + +Config files, logs, inventories, CSV exports: most sysadmin scripts start by reading a file. Python's built-in `open()` is the standard interface for that. + +```python +open(file, mode="r", encoding=None) +``` + +- **file**: an absolute or relative path, such as `/etc/passwd` or `./ip-list.txt`. +- **mode**: how to open the file. The default is `r` (read, text mode). +- **encoding**: always pass `encoding="utf-8"` for text files, so your script behaves the same on every machine. + +| Mode | Meaning | +| --- | --- | +| `r` | read (default) | +| `w` | write, **truncating** the file if it exists | +| `x` | create a new file, fail if it already exists | +| `a` | append to the end of the file | +| `+` | read and write, e.g. `r+` | +| `b` | binary mode, returns `bytes` instead of `str` | + +## Always use `with` + +The `with` statement closes the file for you, even when an exception is raised. There is almost never a reason to call `.close()` by hand. + +```python +# reading a file line by line +with open("/etc/passwd", encoding="utf-8") as f: + for line in f: + print(len(line), line.rstrip()) + +# writing a file +with open("hosts.txt", "w", encoding="utf-8") as f: + f.write("127.0.0.1\n") + f.writelines(["1.1.1.1\n", "8.8.8.8\n"]) +``` + +Useful file object methods: + +- `.read()` reads the whole file as one string. +- `.readline()` reads a single line. +- `.readlines()` returns all lines as a list. +- `.write(text)` writes a string and returns the number of characters written. +- `.writelines(lines)` writes every string in a list. + +## Handling errors + +Missing files, wrong permissions and directories all raise subclasses of `OSError`. Catch the specific one when you can: + +```python +try: + with open("/etc/shadow", encoding="utf-8") as f: + print(f.read()) +except FileNotFoundError: + print("no such file") +except PermissionError: + print("permission denied, try with sudo") +except OSError as e: + print(f"could not read file: {e}") +``` + +## Example: find users with a bash shell + +Read `/etc/passwd` and print every line (with its line number) whose shell is `/bin/bash`: + +```python +#!/usr/bin/env python3 +# working_with_files_01.py +import sys + + +def main(): + try: + with open("/etc/passwd", encoding="utf-8") as f: + for no, line in enumerate(f, start=1): + if line.rstrip().endswith("/bin/bash"): + print(f"{no} {line.rstrip()}") + except OSError as e: + sys.exit(f"error: {e}") + + +if __name__ == "__main__": + main() +``` + +## The modern way: `pathlib` + +`pathlib.Path` wraps a path in an object with handy methods. For quick reads and writes it is shorter than `open()`: + +```python +from pathlib import Path + +hosts = Path("/etc/hosts") +print(hosts.exists(), hosts.stat().st_size) + +text = hosts.read_text(encoding="utf-8") +Path("hosts.bak").write_text(text, encoding="utf-8") + +# all .conf files in /etc +for conf in Path("/etc").glob("*.conf"): + print(conf.name) +``` + +## Reading many files with `fileinput` + +The `fileinput` module loops over the lines of every file given on the command line, or over `stdin` if no files are given. That's exactly how tools like `cat` and `grep` behave. + +```python +#!/usr/bin/env python3 +# line_count.py +import fileinput + +lines = 0 +for line in fileinput.input(encoding="utf-8"): + lines += 1 + +print("total lines:", lines) +``` + +```bash +$ cat /etc/passwd | python3 line_count.py +total lines: 41 +$ python3 line_count.py /etc/services /etc/passwd /etc/hosts +total lines: 11520 +``` + +## Exercises + +- Write `tail.py FILE N` that prints the last `N` lines of a file. Hint: `collections.deque(f, maxlen=n)`. +- Write a script that backs up `/etc/hosts` to `hosts.YYYY-MM-DD.bak` before you edit it. diff --git a/chapters/04-command-line-arguments.md b/chapters/04-command-line-arguments.md new file mode 100644 index 0000000..66f418a --- /dev/null +++ b/chapters/04-command-line-arguments.md @@ -0,0 +1,84 @@ +# Command-line Arguments + +A script becomes a tool when it accepts arguments. The simplest way to read them is `sys.argv`, a list of strings passed to your script. + +> `sys.argv[0]` is always the name of the script itself. The real arguments start at `sys.argv[1]`. + +```python +#!/usr/bin/env python3 +# argv_01.py +import sys + +print("sys.argv:", sys.argv) +print("length:", len(sys.argv)) +``` + +```bash +$ python3 argv_01.py --help +sys.argv: ['argv_01.py', '--help'] +length: 2 +$ python3 argv_01.py 1 2 3 +sys.argv: ['argv_01.py', '1', '2', '3'] +length: 4 +``` + +## Require an exact number of arguments + +`sys.exit("message")` prints the message to `stderr` and exits with status `1`, which is exactly what you want for a usage error. + +```python +#!/usr/bin/env python3 +# argv_02.py +import sys + +args = sys.argv[1:] # drop the script name + +if len(args) != 2: + sys.exit(f"invalid number of arguments (expected 2, given: {len(args)})") + +print("two arguments are:", args) +``` + +```bash +$ python3 argv_02.py 1 +invalid number of arguments (expected 2, given: 1) +$ echo $? +1 +$ python3 argv_02.py 1 2 +two arguments are: ['1', '2'] +``` + +## Example: a tiny `grep` + +```python +#!/usr/bin/env python3 +# grep.py +import sys + + +def main(argv): + if len(argv) != 1: + sys.exit(f"usage: python3 {sys.argv[0]} PATTERN") + + pattern = argv[0] + for line in sys.stdin: + if pattern in line: + print(line.rstrip()) + + +if __name__ == "__main__": + main(sys.argv[1:]) +``` + +```bash +$ cat /etc/services | python3 grep.py 8080 +http-alt 8080/tcp webcache # WWW caching service +``` + +> `sys.argv` is fine for one or two positional arguments. As soon as you need flags like `-v` or `--port 8080`, use [`argparse`](10-argparse.md). It writes the help text and error handling for you. + +## Exercises + +- Extend `grep.py` to read from a file given as a second argument: `python3 grep.py 8080 /etc/services`. +- Then make the file optional: read the file if given, otherwise fall back to `stdin`, just like the real `grep`. +- Add a `-i` flag for case-insensitive matching. diff --git a/chapters/05-os-module.md b/chapters/05-os-module.md new file mode 100644 index 0000000..a205294 --- /dev/null +++ b/chapters/05-os-module.md @@ -0,0 +1,142 @@ +# The `os` Module + +The built-in `os` module exposes operating system functionality (environment variables, files, directories, processes) in a portable way, so the same script runs on Linux, macOS and Windows. + +```python +import os +``` + +## Environment variables + +- `os.environ` is a dictionary-like mapping of the environment, e.g. `os.environ["HOME"]`. +- `os.environ.get("KEY", "default")` (or `os.getenv`) returns a default instead of raising `KeyError`. +- Assign to `os.environ["KEY"]` to change a variable for the current process and any child processes it starts. + +```python +>>> import os +>>> os.environ.get("SHELL") +'/bin/bash' +>>> os.getenv("NO_SUCH_VAR", "fallback") +'fallback' +>>> os.environ["APP_ENV"] = "staging" # visible to subprocesses you start +``` + +> Reading configuration from environment variables (like `DATABASE_URL`) is the standard way to configure scripts in containers and CI pipelines. + +## Files and directories + +- `os.getcwd()` returns the current working directory, like `pwd`. +- `os.chdir(path)` changes it, like `cd`. +- `os.listdir(path)` lists entries in a directory. +- `os.makedirs(path, exist_ok=True)` creates a directory tree, like `mkdir -p`. +- `os.remove(path)` / `os.rmdir(path)` delete a file / empty directory. +- `os.stat(path)` returns size, permissions, owner and timestamps, like `stat`. +- `os.walk(path)` walks a directory tree recursively, like `find`. It yields `(dirpath, dirnames, filenames)` tuples. + +```python +>>> import os, tempfile, datetime +>>> fd, temp = tempfile.mkstemp() # safely create a temporary file +>>> with os.fdopen(fd, "w") as f: +... f.write("test\n") +>>> st = os.stat(temp) +>>> st.st_size, oct(st.st_mode) +(5, '0o100600') +>>> datetime.datetime.fromtimestamp(st.st_mtime) +datetime.datetime(2026, 11, 20, 15, 42, 7, 120394) +``` + +> Use the `tempfile` module (`mkstemp()`, `TemporaryDirectory()`) for temporary files. Old functions like `os.tmpnam` and `tempfile.mktemp` are insecure and have been removed or deprecated. + +## Path names with `os.path` + +- `os.path.join(a, b)` joins path parts with the right separator. +- `os.path.abspath(path)` returns the absolute path. +- `os.path.basename(path)` / `os.path.dirname(path)` return the file / directory part. +- `os.path.exists(path)`, `os.path.isfile(path)`, `os.path.isdir(path)` test a path. +- `os.path.getsize(path)` returns the size in bytes. + +```python +>>> os.path.isdir("/etc") +True +>>> os.path.basename("/etc/passwd"), os.path.dirname("/etc/passwd") +('passwd', '/etc') +>>> os.path.getsize("/etc/hosts") +475 +``` + +`pathlib` does the same with objects instead of strings, and is the recommended style for new code: + +```python +>>> from pathlib import Path +>>> p = Path("/etc/passwd") +>>> p.name, p.parent, p.suffix +('passwd', PosixPath('/etc'), '') +>>> p.is_file(), p.stat().st_size +(True, 2861) +>>> Path.home() / ".ssh" / "config" +PosixPath('/home/puru/.ssh/config') +``` + +## Processes and system information + +- `os.getpid()` / `os.getppid()` return the current and parent process ID. +- `os.uname()` returns system name, hostname, kernel release, version and machine, like `uname -a`. +- `os.getloadavg()` returns the 1, 5 and 15 minute load average. +- `os.cpu_count()` returns the number of CPUs. + +```python +>>> os.uname().nodename +'web-01' +>>> os.getloadavg() +(0.42, 0.37, 0.31) +>>> os.cpu_count() +4 +``` + +> To run other commands, don't use `os.system()`. Use the [`subprocess`](09-subprocess.md) module, which gives you the exit code and output safely. + +## Example: print the size of every file in a directory + +```python +#!/usr/bin/env python3 +# filesizes.py +import os +import sys + + +def filesizes(path): + """Print the size in bytes of each file under path.""" + for dirpath, dirnames, filenames in os.walk(path): + for filename in filenames: + filepath = os.path.join(dirpath, filename) + try: + size = os.path.getsize(filepath) + except OSError: + continue # broken symlink or file removed meanwhile + print(f"{size:>10} {filepath}") + + +def main(argv): + if len(argv) != 1: + sys.exit(f"usage: python3 {sys.argv[0]} DIR") + filesizes(argv[0]) + + +if __name__ == "__main__": + main(sys.argv[1:]) +``` + +```bash +$ python3 filesizes.py /etc/ssh + 573 /etc/ssh/ssh_config + 3289 /etc/ssh/sshd_config + ... +``` + +## Exercises + +- Change `filesizes.py` to print only the 10 largest files. Hint: collect `(size, path)` tuples and use `sorted(..., reverse=True)[:10]`. +- Print the sizes in human-readable units (`K`, `M`, `G`), like `du -h`. +- Rewrite it with `Path(path).rglob("*")` instead of `os.walk`. + +[Learn more in the `os` documentation](https://docs.python.org/3/library/os.html) diff --git a/chapters/06-sys-module.md b/chapters/06-sys-module.md new file mode 100644 index 0000000..a6eb43c --- /dev/null +++ b/chapters/06-sys-module.md @@ -0,0 +1,83 @@ +# The `sys` Module + +The built-in `sys` module gives you access to the Python interpreter itself: its arguments, streams, version, platform and exit status. + +```python +import sys +``` + +## Commonly used variables and functions + +- `sys.argv` is the list of command-line arguments. *Covered in [Command-line Arguments](04-command-line-arguments.md).* +- `sys.exit(arg)` exits the program. `0` means success, any other number means failure, and a string is printed to `stderr` with exit code `1`. +- `sys.stdin`, `sys.stdout`, `sys.stderr` are the [standard streams](02-standard-io.md). +- `sys.version` / `sys.version_info` describe the running Python. +- `sys.platform` is the OS name, such as `linux` or `darwin` (macOS). +- `sys.executable` is the path to the Python binary that is running your script. +- `sys.path` is the list of directories Python searches when you `import`. +- `sys.modules` maps module names to modules that are already loaded. + +## Example + +```python +#!/usr/bin/env python3 +# sys_01.py +import sys + +print(f"Python version: {sys.version}") +print(f"Running on platform: {sys.platform}") +print(f"Interpreter: {sys.executable}") + +if len(sys.argv) > 10: + sys.exit("error: too many arguments") + +print(f"argv = {sys.argv}") +print("Printing to stdout") +print("Printing to stderr", file=sys.stderr) + +print(f"module search paths: {len(sys.path)}") +print(f"modules loaded: {len(sys.modules)}") + +sys.exit(0) # success +``` + +```bash +$ python3 sys_01.py +Python version: 3.13.0 (main, Oct 8 2026, 10:12:44) [GCC 14.2.1] +Running on platform: linux +Interpreter: /usr/bin/python3 +argv = ['sys_01.py'] +Printing to stdout +Printing to stderr +module search paths: 5 +modules loaded: 37 + +$ echo $? +0 +``` + +## Fail early on an old Python + +If your script uses newer features, check the version at the top and exit with a clear message instead of a confusing `SyntaxError` later: + +```python +import sys + +if sys.version_info < (3, 10): + sys.exit(f"this script needs Python 3.10+, you have {sys.version.split()[0]}") +``` + +## Exit codes matter + +Cron, systemd, CI pipelines and shell scripts all look at your exit code to decide whether something failed. A script that prints "error" but exits with `0` is reported as a success. + +```bash +$ python3 backup.py && echo "backup ok" || echo "backup FAILED" +``` + +## Exercises + +- Write a script that exits with `0` if it runs on Linux and with `1` (and a message) everywhere else. +- Print every directory in `sys.path`, one per line, and mark the ones that don't exist. + +[Learn more in the `sys` documentation](https://docs.python.org/3/library/sys.html) diff --git a/chapters/07-shutil-and-glob.md b/chapters/07-shutil-and-glob.md new file mode 100644 index 0000000..04a10a6 --- /dev/null +++ b/chapters/07-shutil-and-glob.md @@ -0,0 +1,83 @@ +# Shell Utilities: `shutil` and `glob` + +Two modules replace most of the file-shuffling you do with `cp`, `mv`, `rm -r`, `df` and shell wildcards. + +## `shutil`: high-level file operations + +### Copy + +- `shutil.copy(src, dst)` copies a file's content and permission bits. `dst` can be a directory. +- `shutil.copy2(src, dst)` also copies timestamps, like `cp -p`. +- `shutil.copytree(src, dst)` copies a whole directory tree, like `cp -r`. + +### Move and delete + +- `shutil.move(src, dst)` moves a file or directory, like `mv`. +- `shutil.rmtree(path)` deletes a directory tree, like `rm -rf`. **There is no undo.** + +### Disk, commands and archives + +- `shutil.disk_usage(path)` returns `(total, used, free)` in bytes, like `df`. +- `shutil.which("cmd")` returns the full path of a command, or `None`, like `which`. +- `shutil.make_archive(base, "gztar", root_dir)` creates a `.tar.gz` (or `zip`) archive. +- `shutil.chown(path, user, group)` changes ownership, like `chown`. + +```python +>>> import shutil +>>> shutil.copy2("/etc/hosts", "/tmp/hosts.bak") +'/tmp/hosts.bak' +>>> shutil.which("docker") +'/usr/bin/docker' +>>> total, used, free = shutil.disk_usage("/") +>>> f"{used / total:.0%} used" +'63% used' +>>> shutil.make_archive("/tmp/etc-backup", "gztar", "/etc/ssh") +'/tmp/etc-backup.tar.gz' +``` + +## Example: alert when the disk is almost full + +```python +#!/usr/bin/env python3 +# disk_alert.py +import shutil +import sys + +THRESHOLD = 80 # percent + + +def main(path="/"): + total, used, free = shutil.disk_usage(path) + percent = used / total * 100 + print(f"{path}: {percent:.1f}% used, {free / 2**30:.1f} GiB free") + if percent > THRESHOLD: + # a non-zero exit code lets cron, systemd or your monitoring react + sys.exit(f"WARNING: {path} is above {THRESHOLD}%") + + +if __name__ == "__main__": + main(*sys.argv[1:]) +``` + +> The original version of this example also sends an email with `smtplib`. See [`examples/Monitoring Disk Space and Sending Alerts.py`](https://github.com/tuladhar/Python-for-SysAdmin/blob/main/examples/Monitoring%20Disk%20Space%20and%20Sending%20Alerts.py). + +## `glob`: Unix-style wildcards + +`glob.glob(pattern)` returns the paths that match a shell-style pattern. Use `**` with `recursive=True` to search subdirectories. + +```python +>>> import glob +>>> glob.glob("/etc/*.conf") +['/etc/resolv.conf', '/etc/sudo.conf', '/etc/host.conf', '/etc/logrotate.conf'] +>>> glob.glob("/var/log/**/*.log", recursive=True) +['/var/log/dnf.log', '/var/log/nginx/access.log', '/var/log/nginx/error.log'] +``` + +`pathlib` has the same feature built in: `Path("/var/log").rglob("*.log")`. + +## Exercises + +- Write `rotate.py` that gzips every `*.log` file older than 7 days in a directory. Hint: `os.stat(path).st_mtime`, `time.time()` and `shutil.copyfileobj` with `gzip.open`. +- Make `disk_alert.py` check every path given on the command line and exit non-zero if any of them is over the threshold. + +[Learn more in the `shutil`](https://docs.python.org/3/library/shutil.html) and [`glob`](https://docs.python.org/3/library/glob.html) documentation. diff --git a/chapters/08-date-and-time.md b/chapters/08-date-and-time.md new file mode 100644 index 0000000..55fd3e6 --- /dev/null +++ b/chapters/08-date-and-time.md @@ -0,0 +1,120 @@ +# Date and Time + +Log timestamps, certificate expiry, backup retention, "how long did this job take?": you will deal with time constantly. Python gives you two modules for it. + +## `time`: clocks and sleeping + +- `time.time()` returns seconds since the Unix epoch as a float. +- `time.monotonic()` is a clock that never jumps backwards. Use it to **measure durations**. +- `time.sleep(seconds)` pauses the script. +- `time.ctime()` returns a human-readable local time string. +- `time.strftime(format)` formats the current local time. + +```python +>>> import time +>>> time.time() +1795189224.396017 +>>> time.ctime() +'Fri Nov 20 15:40:24 2026' +>>> time.strftime("%Y-%m-%d %H:%M:%S") +'2026-11-20 15:40:24' +``` + +### Measuring how long something takes + +```python +import time + +start = time.monotonic() +time.sleep(1.5) # your slow task here +elapsed = time.monotonic() - start +print(f"took {elapsed:.2f}s") +``` + +> Don't use `time.time()` for durations. If NTP adjusts the system clock while your job runs, the result can be wrong or even negative. + +## `datetime`: dates you can do math with + +- `datetime.date.today()` returns today's date. +- `datetime.datetime.now(datetime.UTC)` returns the current date and time **in UTC**. +- `datetime.datetime.fromtimestamp(ts, datetime.UTC)` converts a Unix timestamp. +- `datetime.timedelta(days=7)` is a duration you can add to or subtract from a date. + +```python +>>> from datetime import date, datetime, timedelta, UTC +>>> today = date.today() +>>> today - timedelta(days=10) # past +datetime.date(2026, 11, 10) +>>> today + timedelta(days=10) # future +datetime.date(2026, 11, 30) +>>> datetime.now(UTC).isoformat(timespec="seconds") +'2026-11-20T09:55:24+00:00' +``` + +> `datetime.UTC` was added in Python 3.11. On 3.10, use `datetime.timezone.utc`. + +## Formatting and parsing + +`strftime()` turns a datetime into text; `strptime()` parses text into a datetime. + +```python +>>> fmt = "%a %b %d %H:%M:%S %Y" +>>> datetime.now().strftime(fmt) +'Fri Nov 20 15:40:24 2026' +>>> datetime.strptime("Mon Oct 14 17:56:24 2019", fmt) +datetime.datetime(2019, 10, 14, 17, 56, 24) +>>> datetime.fromisoformat("2026-11-20T09:55:24+00:00") +datetime.datetime(2026, 11, 20, 9, 55, 24, tzinfo=datetime.timezone.utc) +``` + +| Code | Meaning | Example | +| --- | --- | --- | +| `%Y-%m-%d` | date | `2026-11-20` | +| `%H:%M:%S` | time | `15:40:24` | +| `%a %b` | short day and month | `Fri Nov` | +| `%z` | UTC offset | `+0545` | + +## Time zones + +Store and compare times in **UTC**, and only convert to local time when you show them to a person. The `zoneinfo` module knows every time zone: + +```python +>>> from zoneinfo import ZoneInfo +>>> now = datetime.now(UTC) +>>> now.astimezone(ZoneInfo("Asia/Kathmandu")) +datetime.datetime(2026, 11, 20, 15, 40, 24, tzinfo=zoneinfo.ZoneInfo(key='Asia/Kathmandu')) +``` + +## Example: delete backups older than 7 days + +```python +#!/usr/bin/env python3 +# prune_backups.py +import sys +from datetime import datetime, timedelta, UTC +from pathlib import Path + +KEEP = timedelta(days=7) + + +def main(directory): + cutoff = datetime.now(UTC) - KEEP + for path in Path(directory).glob("*.tar.gz"): + modified = datetime.fromtimestamp(path.stat().st_mtime, UTC) + if modified < cutoff: + print(f"deleting {path} (modified {modified:%Y-%m-%d})") + path.unlink() + + +if __name__ == "__main__": + if len(sys.argv) != 2: + sys.exit(f"usage: python3 {sys.argv[0]} BACKUP_DIR") + main(sys.argv[1]) +``` + +## Exercises + +- Add a `--dry-run` mode to `prune_backups.py` that only prints what it would delete. +- Write a script that prints how many days are left until a date given as `YYYY-MM-DD`. + +[Learn more in the `time`](https://docs.python.org/3/library/time.html) and [`datetime`](https://docs.python.org/3/library/datetime.html) documentation. diff --git a/chapters/09-subprocess.md b/chapters/09-subprocess.md new file mode 100644 index 0000000..b544bd0 --- /dev/null +++ b/chapters/09-subprocess.md @@ -0,0 +1,149 @@ +# Running Commands with `subprocess` + +Sooner or later your script needs to run `systemctl`, `git`, `kubectl` or `df`. The `subprocess` module starts other programs, passes them input, captures their output and gives you their exit code. + +## `subprocess.run()`: the one function you need + +Since Python 3.5, `subprocess.run()` is the recommended way to run a command. It waits for the command to finish and returns a `CompletedProcess` object. + +```python +>>> import subprocess +>>> result = subprocess.run(["ls", "-l", "/etc/hosts"]) +-rw-r--r-- 1 root root 475 Nov 20 09:12 /etc/hosts +>>> result.returncode +0 +``` + +Pass the command as a **list** of arguments. Python runs the program directly, without a shell, so a filename like `my file; rm -rf ~` is just a strange filename, not a second command. + +## Capturing output + +Add `capture_output=True` to collect `stdout` and `stderr`, and `text=True` to get strings instead of bytes: + +```python +>>> result = subprocess.run(["uname", "-r"], capture_output=True, text=True) +>>> result.stdout.strip() +'6.12.8-200.fc41.x86_64' +>>> result.stderr +'' +``` + +## Failing on errors + +By default, `run()` doesn't care if the command fails; you have to check `returncode`. Add `check=True` to raise `CalledProcessError` on any non-zero exit code: + +```python +#!/usr/bin/env python3 +# check_call.py +import subprocess +import sys + +cmd = ["ls", "/no/such/dir"] +print("running command:", " ".join(cmd)) + +try: + subprocess.run(cmd, check=True, capture_output=True, text=True) +except subprocess.CalledProcessError as e: + sys.exit(f"error: exit code {e.returncode}: {e.stderr.strip()}") +``` + +```bash +$ python3 check_call.py +running command: ls /no/such/dir +error: exit code 2: ls: cannot access '/no/such/dir': No such file or directory +``` + +Two more errors are worth catching in real scripts: + +- `FileNotFoundError` if the program isn't installed. +- `subprocess.TimeoutExpired` if you pass `timeout=` and the command hangs. + +```python +try: + subprocess.run(["ping", "-c", "1", "10.0.0.1"], check=True, timeout=5) +except FileNotFoundError: + sys.exit("ping is not installed") +except subprocess.TimeoutExpired: + sys.exit("host did not answer within 5 seconds") +except subprocess.CalledProcessError: + sys.exit("host is unreachable") +``` + +## Sending input + +Use `input=` to write to the command's `stdin`: + +```python +>>> result = subprocess.run(["bc"], input="1 + 1\n", capture_output=True, text=True) +>>> result.stdout +'2\n' +``` + +## When you need a shell + +Pipes (`|`), globs (`*.log`), `&&` and environment variable expansion are **shell features**. They only work with `shell=True` and a string command: + +```python +subprocess.run("grep -c bash /etc/passwd | tee count.txt", shell=True, check=True) +``` + +> Never build a `shell=True` command from user input or file content. A value like `x; rm -rf /` would run as a second command. If you must, quote each value with `shlex.quote()`. Usually you can avoid the shell completely: use `glob` for wildcards and Python for the filtering. + +## Example: capture output and save it to a file + +```python +#!/usr/bin/env python3 +# capture_output.py +import subprocess +import sys +from pathlib import Path + +cmd = ["cat", "/etc/hosts"] +print("running command:", " ".join(cmd)) + +try: + result = subprocess.run(cmd, check=True, capture_output=True, text=True) +except subprocess.CalledProcessError as e: + sys.exit(f"error: {e.stderr}") + +Path("hosts.txt").write_text(result.stdout, encoding="utf-8") +print("success! wrote", len(result.stdout), "characters to hosts.txt") +``` + +## Streaming output with `Popen` + +`run()` waits until the command finishes. For long-running commands, such as following a log or a deployment, use `Popen` to read output **while** the command runs: + +```python +#!/usr/bin/env python3 +# follow.py +import subprocess + +with subprocess.Popen( + ["ping", "-c", "5", "1.1.1.1"], + stdout=subprocess.PIPE, + text=True, +) as proc: + for line in proc.stdout: + print("ping says:", line.rstrip()) + +print("exit code:", proc.returncode) +``` + +## Old API cheat sheet + +You will find these in older scripts and Stack Overflow answers. They still work, but `run()` covers all of them: + +| Old | Modern equivalent | +| --- | --- | +| `subprocess.call(cmd)` | `subprocess.run(cmd).returncode` | +| `subprocess.check_call(cmd)` | `subprocess.run(cmd, check=True)` | +| `subprocess.check_output(cmd)` | `subprocess.run(cmd, check=True, capture_output=True).stdout` | +| `os.system("cmd")` | `subprocess.run(["cmd"])` | + +## Exercises + +- Write `svc_status.py SERVICE...` that runs `systemctl is-active` for each service and prints a table of `active` / `inactive`. +- Run `df -P` and parse its output into a list of dictionaries. Then compare the result with `shutil.disk_usage()` from the [shutil chapter](07-shutil-and-glob.md). + +[Learn more in the `subprocess` documentation](https://docs.python.org/3/library/subprocess.html) diff --git a/chapters/10-argparse.md b/chapters/10-argparse.md new file mode 100644 index 0000000..f9163f5 --- /dev/null +++ b/chapters/10-argparse.md @@ -0,0 +1,159 @@ +# Building CLIs with `argparse` + +`sys.argv` gets clumsy as soon as you need options. The built-in `argparse` module turns a few declarations into a real command-line tool with `--help`, type checking, defaults and helpful error messages. + +Think about how `ls` works: + +```bash +$ ls # no arguments: list the current directory +$ ls -l /etc # an optional flag and a positional argument +$ ls --help # automatic help +``` + +`argparse` lets your scripts behave the same way. + +## A first parser + +```python +#!/usr/bin/env python3 +# app.py +import argparse + +parser = argparse.ArgumentParser(description="Process some integers.") +parser.add_argument("integers", metavar="N", type=int, nargs="+", + help="an integer for the accumulator") +parser.add_argument("--sum", dest="accumulate", action="store_const", + const=sum, default=max, + help="sum the integers (default: find the max)") + +args = parser.parse_args() +print(args.accumulate(args.integers)) +``` + +```bash +$ python3 app.py -h +usage: app.py [-h] [--sum] N [N ...] + +Process some integers. + +positional arguments: + N an integer for the accumulator + +options: + -h, --help show this help message and exit + --sum sum the integers (default: find the max) + +$ python3 app.py 1 2 3 4 +4 +$ python3 app.py 1 2 3 4 --sum +10 +$ python3 app.py one +usage: app.py [-h] [--sum] N [N ...] +app.py: error: argument N: invalid int value: 'one' +``` + +You wrote no help text formatting and no validation, and you still got both. + +## The three steps + +1. **Create a parser**: `parser = argparse.ArgumentParser(description="...")` +2. **Add arguments**: `parser.add_argument(...)` once per argument. +3. **Parse**: `args = parser.parse_args()` reads `sys.argv` and returns a namespace, so `args.port`, `args.verbose` and so on. + +## The arguments you'll use most + +```python +# positional (required) +parser.add_argument("host") + +# option with a value and a default +parser.add_argument("-p", "--port", type=int, default=22) + +# on/off flag +parser.add_argument("-v", "--verbose", action="store_true") + +# restricted choices +parser.add_argument("--env", choices=["dev", "staging", "prod"], required=True) + +# one or more values +parser.add_argument("files", nargs="+") +``` + +## Example: a TCP port checker + +```python +#!/usr/bin/env python3 +# tcp_port_checker.py +import argparse +import socket +import sys + + +def check(host, port, timeout): + try: + with socket.create_connection((host, port), timeout=timeout): + return True + except OSError: + return False + + +def main(): + parser = argparse.ArgumentParser(description="Check if TCP ports are open.") + parser.add_argument("host", help="hostname or IP address") + parser.add_argument("-p", "--port", type=int, nargs="+", default=[22, 80, 443], + help="ports to check (default: 22 80 443)") + parser.add_argument("-t", "--timeout", type=float, default=3.0, + help="seconds to wait per port (default: 3)") + args = parser.parse_args() + + all_open = True + for port in args.port: + is_open = check(args.host, port, args.timeout) + all_open = all_open and is_open + print(f"{args.host}:{port:<5} {'open' if is_open else 'CLOSED'}") + + sys.exit(0 if all_open else 1) + + +if __name__ == "__main__": + main() +``` + +```bash +$ python3 tcp_port_checker.py github.com -p 22 443 8080 -t 1 +github.com:22 open +github.com:443 open +github.com:8080 CLOSED +``` + +## Subcommands + +Tools like `git` and `kubectl` have subcommands (`git commit`, `git push`). Use `add_subparsers()`: + +```python +parser = argparse.ArgumentParser(prog="svc") +sub = parser.add_subparsers(dest="command", required=True) + +start = sub.add_parser("start", help="start a service") +start.add_argument("name") + +status = sub.add_parser("status", help="show status") +status.add_argument("name", nargs="?", default="all") + +args = parser.parse_args() +print(args.command, args.name) +``` + +## Useful `ArgumentParser` options + +- `description` / `epilog`: text shown before / after the argument help. +- `prog`: the program name in usage messages (default: the script name). +- `formatter_class=argparse.ArgumentDefaultsHelpFormatter`: show default values in `--help` automatically. +- `parents=[...]`: reuse common arguments (like `--verbose`) across several parsers. + +## Exercises + +- Add a `--json` flag to `tcp_port_checker.py` that prints the results as JSON. You'll learn how in the [JSON chapter](11-json.md). +- Turn the `grep.py` exercise from [Command-line Arguments](04-command-line-arguments.md) into an `argparse` tool with `-i` (ignore case) and `-n` (line numbers). + +[Learn more in the `argparse` documentation](https://docs.python.org/3/library/argparse.html) diff --git a/chapters/11-json.md b/chapters/11-json.md new file mode 100644 index 0000000..839253e --- /dev/null +++ b/chapters/11-json.md @@ -0,0 +1,131 @@ +# Working with JSON + +JSON is how modern infrastructure talks: REST APIs, `kubectl get -o json`, `terraform show -json`, `docker inspect`, cloud CLIs. The built-in `json` module converts between JSON text and Python objects. + +## JSON ↔ Python types + +| JSON | Python | +| --- | --- | +| object `{}` | `dict` | +| array `[]` | `list` | +| string | `str` | +| number (int / real) | `int` / `float` | +| `true` / `false` | `True` / `False` | +| `null` | `None` | + +## The four functions + +- `json.loads(text)`: parse a JSON **string** into Python objects. +- `json.dumps(obj)`: turn Python objects into a JSON **string**. +- `json.load(file)`: parse JSON from an open **file**. +- `json.dump(obj, file)`: write JSON to an open **file**. + +> The `s` stands for *string*. `load`/`dump` work with files. + +```python +>>> import json +>>> data = json.loads('{"host": "web-01", "ports": [80, 443], "healthy": true}') +>>> data["ports"] +[80, 443] +>>> data["healthy"] +True +>>> json.dumps({"host": "web-01", "maintenance": None}) +'{"host": "web-01", "maintenance": null}' +``` + +## Pretty printing + +```python +>>> print(json.dumps(data, indent=2, sort_keys=True)) +{ + "healthy": true, + "host": "web-01", + "ports": [ + 80, + 443 + ] +} +``` + +From the shell, `python3 -m json.tool` validates and pretty-prints JSON, which is handy on a server without `jq`: + +```bash +$ echo '{"a": 1, "b": [1, 2]}' | python3 -m json.tool +{ + "a": 1, + "b": [ + 1, + 2 + ] +} +$ python3 -m json.tool broken.json +Expecting ',' delimiter: line 3 column 5 (char 18) +``` + +## Reading and writing files + +```python +import json + +with open("inventory.json", encoding="utf-8") as f: + inventory = json.load(f) + +inventory["hosts"].append({"name": "db-02", "ip": "10.0.0.12"}) + +with open("inventory.json", "w", encoding="utf-8") as f: + json.dump(inventory, f, indent=2) +``` + +## Handling bad JSON + +`json.JSONDecodeError` tells you exactly where the problem is: + +```python +try: + config = json.loads('{"debug": true,}') +except json.JSONDecodeError as e: + print(f"invalid JSON at line {e.lineno}, column {e.colno}: {e.msg}") +``` + +## Example: list containers that aren't running + +`docker ps -a --format json` prints one JSON object per line. Combine `subprocess` and `json`: + +```python +#!/usr/bin/env python3 +# stopped_containers.py +import json +import subprocess + +result = subprocess.run( + ["docker", "ps", "-a", "--format", "json"], + check=True, capture_output=True, text=True, +) + +for line in result.stdout.splitlines(): + container = json.loads(line) + if container["State"] != "running": + print(f"{container['Names']:<30} {container['Status']}") +``` + +## Example: call a JSON API with only the standard library + +```python +#!/usr/bin/env python3 +# github_stars.py +import json +import urllib.request + +url = "https://api.github.com/repos/tuladhar/Python-for-SysAdmin" +with urllib.request.urlopen(url, timeout=10) as response: + repo = json.load(response) + +print(f"{repo['full_name']} has {repo['stargazers_count']} stars") +``` + +## Exercises + +- Run `kubectl get pods -A -o json` (or use a saved sample file) and print each pod's namespace, name and phase. +- Extend `tcp_port_checker.py` from the [argparse chapter](10-argparse.md) with a `--json` flag. + +[Learn more in the `json` documentation](https://docs.python.org/3/library/json.html) diff --git a/chapters/12-csv.md b/chapters/12-csv.md new file mode 100644 index 0000000..8793389 --- /dev/null +++ b/chapters/12-csv.md @@ -0,0 +1,103 @@ +# Working with CSV + +CSV (comma-separated values, [RFC 4180](https://www.rfc-editor.org/rfc/rfc4180)) is still everywhere: asset inventories, billing exports, user lists from HR, reports your manager wants in a spreadsheet. The built-in `csv` module reads and writes it correctly, including quoted fields with commas inside. + +```csv +hostname,ip,role +web-01,10.0.0.10,web +web-02,10.0.0.11,web +db-01,10.0.0.20,"database, primary" +``` + +> Don't parse CSV with `line.split(",")`. It breaks as soon as a field contains a comma, like `"database, primary"` above. + +## Reading rows as lists + +```python +import csv + +with open("hosts.csv", newline="", encoding="utf-8") as f: + reader = csv.reader(f) + header = next(reader) # skip the header row + for row in reader: + print(row[0], row[1]) +``` + +Always open CSV files with `newline=""`. The `csv` module handles line endings itself. + +## Reading rows as dictionaries + +`csv.DictReader` uses the header row as keys, so you can refer to columns by name. It reads the header automatically. + +```python +import csv + +with open("hosts.csv", newline="", encoding="utf-8") as f: + for row in csv.DictReader(f): + print(f"{row['hostname']:<10} {row['ip']:<12} {row['role']}") +``` + +```text +web-01 10.0.0.10 web +web-02 10.0.0.11 web +db-01 10.0.0.20 database, primary +``` + +## Writing CSV + +```python +import csv + +rows = [ + {"hostname": "web-01", "ip": "10.0.0.10", "role": "web"}, + {"hostname": "db-01", "ip": "10.0.0.20", "role": "database, primary"}, +] + +with open("hosts.csv", "w", newline="", encoding="utf-8") as f: + writer = csv.DictWriter(f, fieldnames=["hostname", "ip", "role"]) + writer.writeheader() + writer.writerows(rows) +``` + +Use `csv.writer` and `writer.writerow([...])` if you're working with lists instead of dictionaries. + +## Other delimiters + +Many "CSV" files are really tab- or semicolon-separated. Pass `delimiter`: + +```python +csv.reader(f, delimiter="\t") +csv.DictReader(f, delimiter=";") +``` + +## Example: export local users to CSV + +`/etc/passwd` is a colon-separated file, so `csv` can read it too: + +```python +#!/usr/bin/env python3 +# users_to_csv.py +import csv +import sys + +fields = ["user", "password", "uid", "gid", "comment", "home", "shell"] + +with open("/etc/passwd", newline="", encoding="utf-8") as f: + users = [dict(zip(fields, row)) for row in csv.reader(f, delimiter=":", quoting=csv.QUOTE_NONE)] + +writer = csv.DictWriter(sys.stdout, fieldnames=["user", "uid", "home", "shell"], + extrasaction="ignore") +writer.writeheader() +writer.writerows(u for u in users if int(u["uid"]) >= 1000) +``` + +```bash +$ python3 users_to_csv.py > users.csv +``` + +## Exercises + +- Read `hosts.csv` and check that every `ip` column is a valid address. Hint: `ipaddress.ip_address()`. +- Combine this chapter with the [argparse chapter](10-argparse.md): run the TCP port checker for every host in a CSV file and write the results to a new CSV. + +[Learn more in the `csv` documentation](https://docs.python.org/3/library/csv.html) diff --git a/chapters/13-sqlite.md b/chapters/13-sqlite.md new file mode 100644 index 0000000..0db433c --- /dev/null +++ b/chapters/13-sqlite.md @@ -0,0 +1,128 @@ +# SQLite: a Database in a File + +SQLite is a fast, reliable SQL database engine that stores everything in a single file and needs no server. It ships inside Python as the `sqlite3` module, so it's perfect for an inventory, a job history or a cache that your scripts can query with SQL. + +```python +import sqlite3 +``` + +## The basic workflow + +1. `sqlite3.connect("file.db")` opens (or creates) a database file and returns a connection. +2. `connection.execute(sql, params)` runs a statement and returns a cursor. +3. `connection.commit()` saves your changes. +4. `cursor.fetchone()` / `cursor.fetchall()` read query results. +5. `connection.close()` closes the database. + +```python +>>> import sqlite3 +>>> con = sqlite3.connect("inventory.db") +>>> con.execute(""" +... CREATE TABLE IF NOT EXISTS hosts ( +... name TEXT PRIMARY KEY, +... ip TEXT NOT NULL, +... role TEXT +... ) +... """) +>>> con.execute("INSERT INTO hosts VALUES (?, ?, ?)", ("web-01", "10.0.0.10", "web")) +>>> con.commit() +>>> con.execute("SELECT * FROM hosts").fetchall() +[('web-01', '10.0.0.10', 'web')] +``` + +Use `":memory:"` instead of a file name for a temporary in-memory database, which is handy for tests. + +## Always use placeholders + +Pass values with `?` placeholders, never with f-strings. The driver escapes them, which protects you from SQL injection and from names like `O'Brien`: + +```python +# good +con.execute("SELECT * FROM hosts WHERE role = ?", (role,)) + +# bad: breaks on quotes and is an injection risk +con.execute(f"SELECT * FROM hosts WHERE role = '{role}'") +``` + +## Inserting many rows + +```python +hosts = [ + ("web-02", "10.0.0.11", "web"), + ("db-01", "10.0.0.20", "database"), +] +con.executemany("INSERT OR REPLACE INTO hosts VALUES (?, ?, ?)", hosts) +con.commit() +``` + +## Transactions with `with` + +Using the connection as a context manager commits on success and rolls back if an exception is raised: + +```python +with con: + con.execute("UPDATE hosts SET role = ? WHERE name = ?", ("cache", "web-02")) + con.execute("DELETE FROM hosts WHERE name = ?", ("old-01",)) +``` + +> `with con:` handles the transaction, not the connection. Call `con.close()` when you're done. + +## Rows by column name + +Set `row_factory` to `sqlite3.Row` to access columns by name: + +```python +con.row_factory = sqlite3.Row +for row in con.execute("SELECT name, ip FROM hosts ORDER BY name"): + print(row["name"], row["ip"]) +``` + +## Example: record every backup run + +```python +#!/usr/bin/env python3 +# backup_log.py +import sqlite3 +import sys +from datetime import datetime, UTC + +con = sqlite3.connect("backups.db") +con.execute(""" + CREATE TABLE IF NOT EXISTS runs ( + id INTEGER PRIMARY KEY, + started TEXT NOT NULL, + target TEXT NOT NULL, + ok INTEGER NOT NULL + ) +""") + +if len(sys.argv) == 3: + # record a run: python3 backup_log.py /srv/data ok + target, status = sys.argv[1], sys.argv[2] + with con: + con.execute( + "INSERT INTO runs (started, target, ok) VALUES (?, ?, ?)", + (datetime.now(UTC).isoformat(timespec="seconds"), target, status == "ok"), + ) + +# report the last 5 runs +for started, target, ok in con.execute( + "SELECT started, target, ok FROM runs ORDER BY id DESC LIMIT 5" +): + print(f"{started} {'OK ' if ok else 'FAIL'} {target}") + +con.close() +``` + +You can also open the file with the `sqlite3` command-line tool and run any SQL you like: + +```bash +$ sqlite3 backups.db "SELECT target, COUNT(*) FROM runs WHERE ok = 0 GROUP BY target" +``` + +## Exercises + +- Load the `hosts.csv` file from the [CSV chapter](12-csv.md) into a `hosts` table. +- Add a `--failed` flag to `backup_log.py` that shows only failed runs. + +[Learn more in the `sqlite3` documentation](https://docs.python.org/3/library/sqlite3.html) diff --git a/chapters/14-socket.md b/chapters/14-socket.md new file mode 100644 index 0000000..a8dbf32 --- /dev/null +++ b/chapters/14-socket.md @@ -0,0 +1,103 @@ +# Network Checks with `socket` + +"Is the port open?" is one of the most common questions in operations. The built-in `socket` module answers it, and lets you resolve hostnames and talk to network services directly, without `telnet`, `nc` or `nslookup` installed. + +```python +import socket +``` + +## Is a TCP port open? + +`socket.create_connection()` resolves the host, connects, and raises `OSError` if it can't. Always pass a `timeout`, or a firewall that silently drops packets will make your script hang. + +```python +#!/usr/bin/env python3 +# port_check.py +import socket + + +def is_open(host, port, timeout=5): + try: + with socket.create_connection((host, port), timeout=timeout): + return True + except OSError: + return False + + +for host, port in [("google.com", 80), ("google.com", 81), ("localhost", 22)]: + print(f"{host}:{port} is {'up' if is_open(host, port) else 'down'}") +``` + +```bash +$ python3 port_check.py +google.com:80 is up +google.com:81 is down +localhost:22 is up +``` + +> For a full CLI around this function, see the TCP port checker in the [argparse chapter](10-argparse.md). + +## DNS lookups + +```python +>>> import socket +>>> socket.gethostname() +'web-01' +>>> socket.gethostbyname("github.com") +'140.82.121.3' +>>> {info[4][0] for info in socket.getaddrinfo("google.com", 443)} # IPv4 and IPv6 +{'142.250.183.110', '2404:6800:4009:82a::200e'} +>>> socket.gethostbyaddr("1.1.1.1")[0] # reverse lookup +'one.one.one.one' +``` + +## Talking to a service + +Once connected, you send and receive **bytes**. Here's a minimal HTTP request: + +```python +import socket + +with socket.create_connection(("example.com", 80), timeout=5) as s: + s.sendall(b"HEAD / HTTP/1.1\r\nHost: example.com\r\nConnection: close\r\n\r\n") + response = s.recv(4096).decode() + +print(response.splitlines()[0]) # HTTP/1.1 200 OK +``` + +## Checking many hosts in parallel + +Checking 200 hosts one after another with a 5 second timeout can take minutes. `concurrent.futures` runs the checks in threads: + +```python +#!/usr/bin/env python3 +# sweep.py +from concurrent.futures import ThreadPoolExecutor +import socket + + +def is_open(target): + host, port = target + try: + with socket.create_connection((host, port), timeout=2): + return target, True + except OSError: + return target, False + + +targets = [(f"10.0.0.{i}", 22) for i in range(1, 255)] + +with ThreadPoolExecutor(max_workers=50) as pool: + for (host, port), up in pool.map(is_open, targets): + if up: + print(f"{host}:{port} open") +``` + +> Only scan networks you own or are allowed to test. + +## Exercises + +- Write `tls_expiry.py HOST` that prints how many days are left on a server's TLS certificate. Hint: `ssl.create_default_context().wrap_socket(...)` and `getpeercert()["notAfter"]`. +- Read hosts and ports from a CSV file and write a CSV report of which are reachable. + +[Learn more in the `socket` documentation](https://docs.python.org/3/library/socket.html) diff --git a/chapters/chapters.json b/chapters/chapters.json new file mode 100644 index 0000000..4aa1599 --- /dev/null +++ b/chapters/chapters.json @@ -0,0 +1,51 @@ +{ + "sections": [ + { + "title": "Getting Started", + "chapters": [ + { "slug": "set-up-your-lab", "file": "01-set-up-your-lab.md", "title": "Set Up Your Lab", "summary": "A free Linux VM in your browser, or Python on your own machine." }, + { "slug": "standard-io", "file": "02-standard-io.md", "title": "Standard Input, Output and Error", "summary": "stdin, stdout, stderr and writing scripts that work in pipelines." }, + { "slug": "working-with-files", "file": "03-working-with-files.md", "title": "Working with Files", "summary": "open(), with, pathlib and fileinput for configs and logs." }, + { "slug": "command-line-arguments", "file": "04-command-line-arguments.md", "title": "Command-line Arguments", "summary": "sys.argv, exit codes and a tiny grep." } + ] + }, + { + "title": "Standard Library", + "chapters": [ + { "slug": "os", "file": "05-os-module.md", "title": "The os Module", "summary": "Environment variables, directories, os.walk and system info." }, + { "slug": "sys", "file": "06-sys-module.md", "title": "The sys Module", "summary": "Interpreter info, version checks and why exit codes matter." }, + { "slug": "shutil-and-glob", "file": "07-shutil-and-glob.md", "title": "shutil and glob", "summary": "Copy, move, archive, check disk usage and match wildcards." }, + { "slug": "date-and-time", "file": "08-date-and-time.md", "title": "Date and Time", "summary": "Durations, UTC, time zones and pruning old backups." }, + { "slug": "subprocess", "file": "09-subprocess.md", "title": "Running Commands with subprocess", "summary": "subprocess.run(), capturing output, errors and streaming." }, + { "slug": "argparse", "file": "10-argparse.md", "title": "Building CLIs with argparse", "summary": "Flags, defaults, --help and subcommands for real tools." } + ] + }, + { + "title": "Data and Networking", + "chapters": [ + { "slug": "json", "file": "11-json.md", "title": "Working with JSON", "summary": "Parse API, kubectl and docker output; call a JSON API." }, + { "slug": "csv", "file": "12-csv.md", "title": "Working with CSV", "summary": "Inventories and reports with csv.DictReader and DictWriter." }, + { "slug": "sqlite", "file": "13-sqlite.md", "title": "SQLite: a Database in a File", "summary": "A zero-setup SQL database for inventories and job history." }, + { "slug": "socket", "file": "14-socket.md", "title": "Network Checks with socket", "summary": "Port checks, DNS lookups and parallel sweeps." } + ] + } + ], + "wanted": [ + { "title": "Regular Expressions", "module": "re", "summary": "Parse log lines, extract IPs and validate input." }, + { "title": "Logging", "module": "logging", "summary": "Proper log levels, files and syslog for your scripts." }, + { "title": "Compression and Archives", "module": "gzip, tarfile, zipfile", "summary": "Create and extract backups and rotate logs." }, + { "title": "XML with ElementTree", "module": "xml.etree", "summary": "Read and modify XML configs and API responses." }, + { "title": "Platform Information", "module": "platform", "summary": "Detect OS, distro, architecture and Python build." }, + { "title": "Signals", "module": "signal", "summary": "Handle SIGTERM and SIGHUP for graceful shutdown and reloads." }, + { "title": "IP Addresses and Networks", "module": "ipaddress", "summary": "Subnets, CIDR math and validating addresses." }, + { "title": "Concurrency", "module": "concurrent.futures, asyncio", "summary": "Run checks and commands on many hosts at once." }, + { "title": "HTTP APIs", "module": "urllib, requests, httpx", "summary": "Talk to REST APIs, webhooks and health endpoints." }, + { "title": "SSH Automation", "module": "paramiko, fabric", "summary": "Run commands and copy files on remote servers." }, + { "title": "System Metrics", "module": "psutil", "summary": "CPU, memory, disk and process info across platforms." }, + { "title": "Network Devices", "module": "netmiko", "summary": "Automate switches and routers over SSH." }, + { "title": "Cloud Automation", "module": "boto3", "summary": "Script AWS: EC2, S3, IAM and cost reports." }, + { "title": "Docker and Kubernetes", "module": "docker, kubernetes", "summary": "Manage containers and clusters from Python." }, + { "title": "Templating Configs", "module": "jinja2", "summary": "Generate nginx, systemd and YAML files from templates." }, + { "title": "Testing Your Scripts", "module": "pytest", "summary": "Test automation before it touches production." } + ] +} diff --git a/examples/app.py b/examples/app.py index f01e6b4..5ccf695 100755 --- a/examples/app.py +++ b/examples/app.py @@ -1,13 +1,13 @@ #!/usr/bin/env python3 -#app.py +# app.py import argparse -parser = argparse.ArgumentParser(description='Process some integers.') -parser.add_argument('integers', metavar='N', type=int, nargs='+', - help='an integer for the accumulator') -parser.add_argument('--sum', dest='accumulate', action='store_const', - const=sum, default=max, - help='sum the integers (default: find the max)') +parser = argparse.ArgumentParser(description="Process some integers.") +parser.add_argument("integers", metavar="N", type=int, nargs="+", + help="an integer for the accumulator") +parser.add_argument("--sum", dest="accumulate", action="store_const", + const=sum, default=max, + help="sum the integers (default: find the max)") args = parser.parse_args() -print(args.accumulate(args.integers)) \ No newline at end of file +print(args.accumulate(args.integers)) diff --git a/examples/argv_01.py b/examples/argv_01.py new file mode 100644 index 0000000..d91597b --- /dev/null +++ b/examples/argv_01.py @@ -0,0 +1,6 @@ +#!/usr/bin/env python3 +# argv_01.py +import sys + +print("sys.argv:", sys.argv) +print("length:", len(sys.argv)) diff --git a/examples/argv_02.py b/examples/argv_02.py new file mode 100644 index 0000000..6377215 --- /dev/null +++ b/examples/argv_02.py @@ -0,0 +1,10 @@ +#!/usr/bin/env python3 +# argv_02.py +import sys + +args = sys.argv[1:] # drop the script name + +if len(args) != 2: + sys.exit(f"invalid number of arguments (expected 2, given: {len(args)})") + +print("two arguments are:", args) diff --git a/examples/backup_log.py b/examples/backup_log.py new file mode 100644 index 0000000..3d8d115 --- /dev/null +++ b/examples/backup_log.py @@ -0,0 +1,32 @@ +#!/usr/bin/env python3 +# backup_log.py +import sqlite3 +import sys +from datetime import datetime, UTC + +con = sqlite3.connect("backups.db") +con.execute(""" + CREATE TABLE IF NOT EXISTS runs ( + id INTEGER PRIMARY KEY, + started TEXT NOT NULL, + target TEXT NOT NULL, + ok INTEGER NOT NULL + ) +""") + +if len(sys.argv) == 3: + # record a run: python3 backup_log.py /srv/data ok + target, status = sys.argv[1], sys.argv[2] + with con: + con.execute( + "INSERT INTO runs (started, target, ok) VALUES (?, ?, ?)", + (datetime.now(UTC).isoformat(timespec="seconds"), target, status == "ok"), + ) + +# report the last 5 runs +for started, target, ok in con.execute( + "SELECT started, target, ok FROM runs ORDER BY id DESC LIMIT 5" +): + print(f"{started} {'OK ' if ok else 'FAIL'} {target}") + +con.close() diff --git a/examples/bideriectional.py b/examples/bideriectional.py deleted file mode 100755 index 3d8eedf..0000000 --- a/examples/bideriectional.py +++ /dev/null @@ -1,26 +0,0 @@ -#!/usr/bin/env python3 -# bidirectional.py -import subprocess -from subprocess import PIPE -import sys - -cmd = 'bc' -send = '1 + 1\n' - -print('running command:', cmd, 'and sending input:', send) - -proc = subprocess.Popen(cmd, shell=True, stdin=PIPE, stdout=PIPE, stderr=PIPE) -stdout, stderr = proc.communicate(send) - -print(f''' -exit code: {proc.poll()} - -stdin: -{send} - -stdout: -{stdout or None} - -stderr: -{stderr or None} -''') \ No newline at end of file diff --git a/examples/capture_output.py b/examples/capture_output.py index b3650f5..7cfd691 100755 --- a/examples/capture_output.py +++ b/examples/capture_output.py @@ -1,16 +1,16 @@ #!/usr/bin/env python3 # capture_output.py - import subprocess import sys +from pathlib import Path + +cmd = ["cat", "/etc/hosts"] +print("running command:", " ".join(cmd)) try: - cmd = 'cat /etc/hosts' - print('running command:', cmd) - output = subprocess.check_output(cmd, shell=True, stderr=subprocess.STDOUT) -except subprocess.CalledProcessError as error: - sys.exit(f'error: {error}') -else: - print('success!') - with open('hosts.txt', 'w') as f: - f.write(str(output)) + result = subprocess.run(cmd, check=True, capture_output=True, text=True) +except subprocess.CalledProcessError as e: + sys.exit(f"error: {e.stderr}") + +Path("hosts.txt").write_text(result.stdout, encoding="utf-8") +print("success! wrote", len(result.stdout), "characters to hosts.txt") diff --git a/examples/check_call.py b/examples/check_call.py index 9f79c19..8fd7642 100755 --- a/examples/check_call.py +++ b/examples/check_call.py @@ -1,12 +1,12 @@ #!/usr/bin/env python3 # check_call.py - -import sys import subprocess +import sys + +cmd = ["ls", "/no/such/dir"] +print("running command:", " ".join(cmd)) try: - cmd = 'false' - print ('running command:',cmd) - subprocess.check_call(cmd, shell=True) -except subprocess.CalledProcessError as error: - sys.exit('error: {}'.format(error)) + subprocess.run(cmd, check=True, capture_output=True, text=True) +except subprocess.CalledProcessError as e: + sys.exit(f"error: exit code {e.returncode}: {e.stderr.strip()}") diff --git a/examples/disk_alert.py b/examples/disk_alert.py new file mode 100644 index 0000000..1f42f44 --- /dev/null +++ b/examples/disk_alert.py @@ -0,0 +1,19 @@ +#!/usr/bin/env python3 +# disk_alert.py +import shutil +import sys + +THRESHOLD = 80 # percent + + +def main(path="/"): + total, used, free = shutil.disk_usage(path) + percent = used / total * 100 + print(f"{path}: {percent:.1f}% used, {free / 2**30:.1f} GiB free") + if percent > THRESHOLD: + # a non-zero exit code lets cron, systemd or your monitoring react + sys.exit(f"WARNING: {path} is above {THRESHOLD}%") + + +if __name__ == "__main__": + main(*sys.argv[1:]) diff --git a/examples/filesizes.py b/examples/filesizes.py index 5fe1e2c..1313e91 100755 --- a/examples/filesizes.py +++ b/examples/filesizes.py @@ -1,30 +1,26 @@ #!/usr/bin/env python3 # filesizes.py - import os import sys -script = sys.argv[0] - -def print_usage(): - print(f' >> {sys.stderr}, "Usage: python {script} DIR"') - sys.exit(1) def filesizes(path): - ''' calculate and print size of each file in a given directory. ''' + """Print the size in bytes of each file under path.""" + for dirpath, dirnames, filenames in os.walk(path): + for filename in filenames: + filepath = os.path.join(dirpath, filename) + try: + size = os.path.getsize(filepath) + except OSError: + continue # broken symlink or file removed meanwhile + print(f"{size:>10} {filepath}") - for dirpath, dirnames, filenames in os.walk(path): - for filename in filenames: - filepath = os.path.join(dirpath, filename) - bytes = os.path.getsize(filepath) - print (f'{bytes}, {filepath}') def main(argv): - if not len(argv) == 1: - print_usage() + if len(argv) != 1: + sys.exit(f"usage: python3 {sys.argv[0]} DIR") + filesizes(argv[0]) - path = argv[0] - filesizes(path) -if __name__ == '__main__': - main(sys.argv[1:]) \ No newline at end of file +if __name__ == "__main__": + main(sys.argv[1:]) diff --git a/examples/follow.py b/examples/follow.py new file mode 100644 index 0000000..4118da3 --- /dev/null +++ b/examples/follow.py @@ -0,0 +1,13 @@ +#!/usr/bin/env python3 +# follow.py +import subprocess + +with subprocess.Popen( + ["ping", "-c", "5", "1.1.1.1"], + stdout=subprocess.PIPE, + text=True, +) as proc: + for line in proc.stdout: + print("ping says:", line.rstrip()) + +print("exit code:", proc.returncode) diff --git a/examples/github_stars.py b/examples/github_stars.py new file mode 100644 index 0000000..a2c7c8e --- /dev/null +++ b/examples/github_stars.py @@ -0,0 +1,10 @@ +#!/usr/bin/env python3 +# github_stars.py +import json +import urllib.request + +url = "https://api.github.com/repos/tuladhar/Python-for-SysAdmin" +with urllib.request.urlopen(url, timeout=10) as response: + repo = json.load(response) + +print(f"{repo['full_name']} has {repo['stargazers_count']} stars") diff --git a/examples/grep.py b/examples/grep.py index 0d5e1f1..b23e11d 100755 --- a/examples/grep.py +++ b/examples/grep.py @@ -1,22 +1,17 @@ #!/usr/bin/env python3 # grep.py - import sys -script = sys.argv[0] - -def print_usage(): - sys.exit(f'Usage: python {script} pattern' def main(argv): - if not len(argv) == 1: - print_usage() + if len(argv) != 1: + sys.exit(f"usage: python3 {sys.argv[0]} PATTERN") - pattern = argv[0] + pattern = argv[0] + for line in sys.stdin: + if pattern in line: + print(line.rstrip()) - for line in sys.stdin: - if pattern in line: - print line.strip() -if __name__ == '__main__': - main(sys.argv[1:]) \ No newline at end of file +if __name__ == "__main__": + main(sys.argv[1:]) diff --git a/examples/line_count.py b/examples/line_count.py index e8c830b..389023b 100755 --- a/examples/line_count.py +++ b/examples/line_count.py @@ -1,10 +1,9 @@ #!/usr/bin/env python3 -# linescount-02.py - +# line_count.py import fileinput lines = 0 -for line in fileinput.input(): - lines += 1 +for line in fileinput.input(encoding="utf-8"): + lines += 1 -print('totat lines:', lines) \ No newline at end of file +print("total lines:", lines) diff --git a/examples/one_way.py b/examples/one_way.py deleted file mode 100755 index 7c8e6b6..0000000 --- a/examples/one_way.py +++ /dev/null @@ -1,26 +0,0 @@ -#!/usr/bin/env python3 -# one-way.py -import subprocess -import sys - -script = sys.argv[0] - -def main(argv): - if not len(argv) == 1: - sys.exit(f'usage: python {script} command') - cmd = sys.argv[1] - print ('running command:', cmd) - proc = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) - stdout, stderr = proc.communicate() - print(f''' -exit code: {proc.poll()} - -stdout: -{stdout or None} - -stderr: -{stderr or None} -''') - -if __name__ == '__main__': - main(sys.argv[1:]) diff --git a/examples/port_check.py b/examples/port_check.py new file mode 100644 index 0000000..828bb0c --- /dev/null +++ b/examples/port_check.py @@ -0,0 +1,15 @@ +#!/usr/bin/env python3 +# port_check.py +import socket + + +def is_open(host, port, timeout=5): + try: + with socket.create_connection((host, port), timeout=timeout): + return True + except OSError: + return False + + +for host, port in [("google.com", 80), ("google.com", 81), ("localhost", 22)]: + print(f"{host}:{port} is {'up' if is_open(host, port) else 'down'}") diff --git a/examples/prune_backups.py b/examples/prune_backups.py new file mode 100644 index 0000000..32c9bd7 --- /dev/null +++ b/examples/prune_backups.py @@ -0,0 +1,22 @@ +#!/usr/bin/env python3 +# prune_backups.py +import sys +from datetime import datetime, timedelta, UTC +from pathlib import Path + +KEEP = timedelta(days=7) + + +def main(directory): + cutoff = datetime.now(UTC) - KEEP + for path in Path(directory).glob("*.tar.gz"): + modified = datetime.fromtimestamp(path.stat().st_mtime, UTC) + if modified < cutoff: + print(f"deleting {path} (modified {modified:%Y-%m-%d})") + path.unlink() + + +if __name__ == "__main__": + if len(sys.argv) != 2: + sys.exit(f"usage: python3 {sys.argv[0]} BACKUP_DIR") + main(sys.argv[1]) diff --git a/examples/stdio.py b/examples/stdio.py new file mode 100644 index 0000000..1a12439 --- /dev/null +++ b/examples/stdio.py @@ -0,0 +1,20 @@ +#!/usr/bin/env python3 +# stdio.py +import sys + +# write to stdout +print("Hello, world") +sys.stdout.write("Hello, world\n") + +# write to stderr +print("Something went wrong", file=sys.stderr) +sys.stderr.write("Something went wrong\n") + +# read a single line from stdin +username = input("Username: ") +print(f"Hi, {username}") + +# read everything until EOF (press Ctrl-D in a terminal) +print("Enter a few lines and press Ctrl-D", file=sys.stderr) +lines = sys.stdin.readlines() +print("total lines read:", len(lines)) diff --git a/examples/stopped_containers.py b/examples/stopped_containers.py new file mode 100644 index 0000000..75ad6f6 --- /dev/null +++ b/examples/stopped_containers.py @@ -0,0 +1,14 @@ +#!/usr/bin/env python3 +# stopped_containers.py +import json +import subprocess + +result = subprocess.run( + ["docker", "ps", "-a", "--format", "json"], + check=True, capture_output=True, text=True, +) + +for line in result.stdout.splitlines(): + container = json.loads(line) + if container["State"] != "running": + print(f"{container['Names']:<30} {container['Status']}") diff --git a/examples/sweep.py b/examples/sweep.py new file mode 100644 index 0000000..c26712e --- /dev/null +++ b/examples/sweep.py @@ -0,0 +1,21 @@ +#!/usr/bin/env python3 +# sweep.py +from concurrent.futures import ThreadPoolExecutor +import socket + + +def is_open(target): + host, port = target + try: + with socket.create_connection((host, port), timeout=2): + return target, True + except OSError: + return target, False + + +targets = [(f"10.0.0.{i}", 22) for i in range(1, 255)] + +with ThreadPoolExecutor(max_workers=50) as pool: + for (host, port), up in pool.map(is_open, targets): + if up: + print(f"{host}:{port} open") diff --git a/examples/sys_01.py b/examples/sys_01.py index aaacbbe..ef8e76c 100755 --- a/examples/sys_01.py +++ b/examples/sys_01.py @@ -1,30 +1,19 @@ #!/usr/bin/env python3 -# sys-01.py - +# sys_01.py import sys -from sys import argv - -print (f''' -Python version installed: {sys.version} - -Python running on platforn: {sys.platform} -''') -if len(argv) == 10: - sys.exit('error: too many arguments') +print(f"Python version: {sys.version}") +print(f"Running on platform: {sys.platform}") +print(f"Interpreter: {sys.executable}") -print(f''' -argv = {argv} -len(argv) = {len(argv)} -''') +if len(sys.argv) > 10: + sys.exit("error: too many arguments") -print ('Printing to stdout') -print (f'>> {sys.stderr}, "Printing to stderr"') +print(f"argv = {sys.argv}") +print("Printing to stdout") +print("Printing to stderr", file=sys.stderr) -print(f''' -total modules search path: {len(sys.path)} -total modules loaded: {len(sys.modules)} -''') +print(f"module search paths: {len(sys.path)}") +print(f"modules loaded: {len(sys.modules)}") -# success -sys.exit(0) +sys.exit(0) # success diff --git a/examples/tcp_port_checker.py b/examples/tcp_port_checker.py index 94a8615..c2b158d 100755 --- a/examples/tcp_port_checker.py +++ b/examples/tcp_port_checker.py @@ -1,30 +1,35 @@ #!/usr/bin/env python3 -#tcp_port_checker.py - +# tcp_port_checker.py +import argparse import socket -import re import sys -def check_server(address, port): - #create a TCP socket - s = socket.socket() - print (f"Attempting to connect to {address} on port {port}") + +def check(host, port, timeout): try: - s.connect((address, port)) - print(f"Connected to {address} on port {port}") - return True - except socket.error as e: - print(f"Connection to {address} on port {port} failed: {e}") + with socket.create_connection((host, port), timeout=timeout): + return True + except OSError: return False -if __name__ == '__main__': - from optparse import OptionParser - parser = OptionParser() - parser.add_option("-a", "--address", dest="address", default='localhost', help="ADDRESS for server", metavar="ADDRESS") - parser.add_option("-p", "--port", dest="port", type="int", default=80, help="PORT for server", metavar="PORT") - (options, args) = parser.parse_args() - print(f'options: {options}, args:{args}') - check = check_server(options.address, options.port) - print(f'check_server returned {check}') - sys.exit(not check) \ No newline at end of file +def main(): + parser = argparse.ArgumentParser(description="Check if TCP ports are open.") + parser.add_argument("host", help="hostname or IP address") + parser.add_argument("-p", "--port", type=int, nargs="+", default=[22, 80, 443], + help="ports to check (default: 22 80 443)") + parser.add_argument("-t", "--timeout", type=float, default=3.0, + help="seconds to wait per port (default: 3)") + args = parser.parse_args() + + all_open = True + for port in args.port: + is_open = check(args.host, port, args.timeout) + all_open = all_open and is_open + print(f"{args.host}:{port:<5} {'open' if is_open else 'CLOSED'}") + + sys.exit(0 if all_open else 1) + + +if __name__ == "__main__": + main() diff --git a/examples/upper.py b/examples/upper.py new file mode 100644 index 0000000..c518d29 --- /dev/null +++ b/examples/upper.py @@ -0,0 +1,6 @@ +#!/usr/bin/env python3 +# upper.py +import sys + +for line in sys.stdin: + sys.stdout.write(line.upper()) diff --git a/examples/users_to_csv.py b/examples/users_to_csv.py new file mode 100644 index 0000000..218f04c --- /dev/null +++ b/examples/users_to_csv.py @@ -0,0 +1,14 @@ +#!/usr/bin/env python3 +# users_to_csv.py +import csv +import sys + +fields = ["user", "password", "uid", "gid", "comment", "home", "shell"] + +with open("/etc/passwd", newline="", encoding="utf-8") as f: + users = [dict(zip(fields, row)) for row in csv.reader(f, delimiter=":", quoting=csv.QUOTE_NONE)] + +writer = csv.DictWriter(sys.stdout, fieldnames=["user", "uid", "home", "shell"], + extrasaction="ignore") +writer.writeheader() +writer.writerows(u for u in users if int(u["uid"]) >= 1000) diff --git a/examples/working_with_files_01.py b/examples/working_with_files_01.py index 01acae0..91cbeac 100755 --- a/examples/working_with_files_01.py +++ b/examples/working_with_files_01.py @@ -1,23 +1,17 @@ #!/usr/bin/env python3 -# working-with-files-01.py +# working_with_files_01.py +import sys -# NOTE : Works for Unix based systems def main(): - try: - with open('/etc/passwd') as f: - for no, line in enumerate(f, 1): - if '/bin/bash' in line: # Checks if the string /bin/bash is present in the line(each line from the file /etc/passwd). Filters out users whose default shell is Bash. - line = line.strip() - print ("{} {}".format(no, line)) - # Each line in /etc/passwd represents a user account, and it follows this format: - # username:password:UID:GID:GECOS:home_directory:shell - # password: An x or * indicates that the password is stored in the /etc/shadow file, not in this file. - # UID: User ID. GID: Group ID. GECOS: Typically includes the user’s full name or other information. - # home_directory: The path to the user's home directory. - # shell: The user’s login shell (e.g., /bin/bash, /bin/sh, etc - - except IOError as e: - print(e) + try: + with open("/etc/passwd", encoding="utf-8") as f: + for no, line in enumerate(f, start=1): + if line.rstrip().endswith("/bin/bash"): + print(f"{no} {line.rstrip()}") + except OSError as e: + sys.exit(f"error: {e}") -if __name__ == '__main__': main() \ No newline at end of file + +if __name__ == "__main__": + main() From 1b1d974e4400ba860ad3084f1771f973cb850ee5 Mon Sep 17 00:00:00 2001 From: Puru <5674762+tuladhar@users.noreply.github.com> Date: Fri, 20 Nov 2026 16:24:30 +0545 Subject: [PATCH 2/3] Fix examples found broken in the iximiuz playground; add tests and CI Tested on the iximiuz Labs Python playground (Ubuntu 24.04, Python 3.14): - port_check.py hung on google.com:81 (timeout per resolved address); use github.com targets and a 3s timeout, explain the pitfall - sweep.py scanned a hard-coded 10.0.0.0/24; take NETWORK and PORT args - nested_sequences_flattened.py: collections.Iterable was removed, and the generator yielded sublists too - remove snmp_discover.py (imports modules that never existed) and sys_02.py (duplicate of argv_02.py) - make every inline snippet self-contained; replace bc (not installed) with sort in the subprocess input example - require Python 3.11+ (datetime.UTC) - add scripts/test_examples.sh, scripts/check_snippets.py and a GitHub Actions workflow that runs both on 3.11 and 3.14 Co-Authored-By: Claude Opus 5.5 --- .github/workflows/check.yml | 25 ++++++ CONTRIBUTING.md | 14 +++- ...k_Monitoring_and_Utilities.cpython-314.pyc | Bin 0 -> 783 bytes chapters/01-set-up-your-lab.md | 2 +- chapters/03-working-with-files.md | 2 +- chapters/06-sys-module.md | 4 +- chapters/09-subprocess.md | 7 +- chapters/10-argparse.md | 6 ++ chapters/12-csv.md | 10 ++- chapters/13-sqlite.md | 2 + chapters/14-socket.md | 45 ++++++++--- ...stem_Tasks_with_subprocess.cpython-314.pyc | Bin 0 -> 617 bytes ...k Space and Sending Alerts.cpython-314.pyc | Bin 0 -> 1445 bytes .../Multi-threading.cpython-314.pyc | Bin 0 -> 985 bytes examples/__pycache__/app.cpython-314.pyc | Bin 0 -> 790 bytes examples/__pycache__/argv_01.cpython-314.pyc | Bin 0 -> 287 bytes examples/__pycache__/argv_02.cpython-314.pyc | Bin 0 -> 439 bytes .../__pycache__/backup_log.cpython-314.pyc | Bin 0 -> 1388 bytes .../capture_output.cpython-314.pyc | Bin 0 -> 965 bytes .../__pycache__/check_call.cpython-314.pyc | Bin 0 -> 751 bytes .../__pycache__/disk_alert.cpython-314.pyc | Bin 0 -> 885 bytes .../__pycache__/filesizes.cpython-314.pyc | Bin 0 -> 1329 bytes examples/__pycache__/follow.cpython-314.pyc | Bin 0 -> 627 bytes .../__pycache__/github_stars.cpython-314.pyc | Bin 0 -> 670 bytes examples/__pycache__/grep.cpython-314.pyc | Bin 0 -> 787 bytes .../__pycache__/line_count.cpython-314.pyc | Bin 0 -> 335 bytes ...nested_sequences_flattened.cpython-314.pyc | Bin 0 -> 1267 bytes .../__pycache__/port_check.cpython-314.pyc | Bin 0 -> 826 bytes .../__pycache__/prune_backups.cpython-314.pyc | Bin 0 -> 1316 bytes examples/__pycache__/stdio.cpython-314.pyc | Bin 0 -> 825 bytes .../stopped_containers.cpython-314.pyc | Bin 0 -> 679 bytes examples/__pycache__/sweep.cpython-314.pyc | Bin 0 -> 1916 bytes examples/__pycache__/sys_01.cpython-314.pyc | Bin 0 -> 1030 bytes .../tcp_port_checker.cpython-314.pyc | Bin 0 -> 1930 bytes examples/__pycache__/upper.cpython-314.pyc | Bin 0 -> 320 bytes .../__pycache__/users_to_csv.cpython-314.pyc | Bin 0 -> 1228 bytes .../working_with_files_01.cpython-314.pyc | Bin 0 -> 1035 bytes examples/nested_sequences_flattened.py | 5 +- examples/port_check.py | 6 +- examples/snmp_discover.py | 72 ------------------ examples/sweep.py | 24 ++++-- examples/sys_02.py | 11 --- scripts/check_snippets.py | 44 +++++++++++ scripts/test_examples.sh | 66 ++++++++++++++++ 44 files changed, 228 insertions(+), 117 deletions(-) create mode 100644 .github/workflows/check.yml create mode 100644 __pycache__/Network_Monitoring_and_Utilities.cpython-314.pyc create mode 100644 examples/__pycache__/Automating_System_Tasks_with_subprocess.cpython-314.pyc create mode 100644 examples/__pycache__/Monitoring Disk Space and Sending Alerts.cpython-314.pyc create mode 100644 examples/__pycache__/Multi-threading.cpython-314.pyc create mode 100644 examples/__pycache__/app.cpython-314.pyc create mode 100644 examples/__pycache__/argv_01.cpython-314.pyc create mode 100644 examples/__pycache__/argv_02.cpython-314.pyc create mode 100644 examples/__pycache__/backup_log.cpython-314.pyc create mode 100644 examples/__pycache__/capture_output.cpython-314.pyc create mode 100644 examples/__pycache__/check_call.cpython-314.pyc create mode 100644 examples/__pycache__/disk_alert.cpython-314.pyc create mode 100644 examples/__pycache__/filesizes.cpython-314.pyc create mode 100644 examples/__pycache__/follow.cpython-314.pyc create mode 100644 examples/__pycache__/github_stars.cpython-314.pyc create mode 100644 examples/__pycache__/grep.cpython-314.pyc create mode 100644 examples/__pycache__/line_count.cpython-314.pyc create mode 100644 examples/__pycache__/nested_sequences_flattened.cpython-314.pyc create mode 100644 examples/__pycache__/port_check.cpython-314.pyc create mode 100644 examples/__pycache__/prune_backups.cpython-314.pyc create mode 100644 examples/__pycache__/stdio.cpython-314.pyc create mode 100644 examples/__pycache__/stopped_containers.cpython-314.pyc create mode 100644 examples/__pycache__/sweep.cpython-314.pyc create mode 100644 examples/__pycache__/sys_01.cpython-314.pyc create mode 100644 examples/__pycache__/tcp_port_checker.cpython-314.pyc create mode 100644 examples/__pycache__/upper.cpython-314.pyc create mode 100644 examples/__pycache__/users_to_csv.cpython-314.pyc create mode 100644 examples/__pycache__/working_with_files_01.cpython-314.pyc delete mode 100755 examples/snmp_discover.py delete mode 100755 examples/sys_02.py create mode 100644 scripts/check_snippets.py create mode 100755 scripts/test_examples.sh diff --git a/.github/workflows/check.yml b/.github/workflows/check.yml new file mode 100644 index 0000000..1ac4dd2 --- /dev/null +++ b/.github/workflows/check.yml @@ -0,0 +1,25 @@ +name: Check examples + +on: + pull_request: + push: + branches: [main] + +jobs: + test: + runs-on: ubuntu-latest + strategy: + fail-fast: false + matrix: + python-version: ["3.11", "3.14"] + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: + python-version: ${{ matrix.python-version }} + - name: Validate chapters.json + run: python3 -c "import json; m = json.load(open('chapters/chapters.json')); import os; [open(os.path.join('chapters', c['file'])) for s in m['sections'] for c in s['chapters']]" + - name: Run every example script + run: scripts/test_examples.sh + - name: Run every inline snippet in the chapters + run: python3 scripts/check_snippets.py diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 0cf7858..5501bb4 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -19,6 +19,7 @@ chapters/ ... examples/ # every runnable script from the chapters assets/ # images and GIFs used by chapters +scripts/ # tests: test_examples.sh and check_snippets.py ``` The website reads `chapters/chapters.json`, then loads each chapter's Markdown file straight from the `main` branch. @@ -49,7 +50,7 @@ Look at [`09-subprocess.md`](chapters/09-subprocess.md) for a good template. - Start with a `# Title` and one or two sentences on **why a sysadmin needs this**. - Short sections with `##` headings. Explain one idea, then show it. -- Use **Python 3.10+** and the standard library unless the chapter is about a third-party package. +- Use **Python 3.11+** and the standard library unless the chapter is about a third-party package. - Use `pathlib`, f-strings, `subprocess.run()`, `with` blocks and `encoding="utf-8"`. - Every complete script starts with `#!/usr/bin/env python3` and a `# filename.py` comment, and must run as shown. - Show the command and its output in a separate `bash` block. @@ -59,6 +60,17 @@ Look at [`09-subprocess.md`](chapters/09-subprocess.md) for a good template. Preview your Markdown in the GitHub pull request "Preview" tab or any Markdown viewer. +### Test before you open a pull request + +Two scripts check that everything in the guide actually runs. GitHub Actions runs them on every pull request, on Python 3.11 and the latest Python: + +```bash +scripts/test_examples.sh # runs every script in examples/ and checks its exit code +python3 scripts/check_snippets.py # runs every inline snippet in chapters/ +``` + +If you add a script to `examples/`, add a line for it to `scripts/test_examples.sh`. The quickest place to run them is the free [iximiuz Labs Python Playground](https://labs.iximiuz.com/playgrounds/python). + ## Adding a GIF Short GIFs of a script running in a terminal help a lot, especially in the [iximiuz Labs Python Playground](https://labs.iximiuz.com/playgrounds/python). diff --git a/__pycache__/Network_Monitoring_and_Utilities.cpython-314.pyc b/__pycache__/Network_Monitoring_and_Utilities.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1268181067ed9e23e38ac13edc8472266178b531 GIT binary patch literal 783 zcmYjP&x;aK9RI%gwdOjaYwQwbDzdJFV6aI+Yc4_r9g;tGHt4(_1NlbPo(d6G_b z%A-f2Q-46vE&LCbC03aBR+qhPZ4lI@?{g>cy_wH^zP~@bdAYC}1YD^N=;R2%H*Wl2 zl20x(NJh|rDtQ77s=@{^@{**WDmL~C!c|rRqiN8jb8c1)-@Awf5Jh}10Vj;$Ce#;h z4tvXazBdKW$z7o#SIK=pxlkqb7{GE!)j;PbopHkam6ieEA({Aa{nANqI zWxDzPD=%amm_|o;P3I81g|V3bcejl&f(t>CvuA2-u5O;Fn^QLJek#w^(y3ZH3q{AZ z@#9Hq@@R5zx_-Qt{SwlCixA$$I6fz8>F@W|=)26$T5~FKNM$0f;bGeDQ$Pnyg_@K z;H+TvLiY!}VVtW7UZB{ctwGl;IZ-tErEqT`;6y^cg8EaDN%ltsi29~J**=BaP6VU> E0B+HnK>z>% literal 0 HcmV?d00001 diff --git a/chapters/01-set-up-your-lab.md b/chapters/01-set-up-your-lab.md index a8f5abf..0b545df 100644 --- a/chapters/01-set-up-your-lab.md +++ b/chapters/01-set-up-your-lab.md @@ -38,7 +38,7 @@ Most Linux distributions and macOS already ship Python 3. Check it: python3 --version ``` -You want **Python 3.10 or newer**. Every example in this guide uses only the standard library, so there is nothing to install with `pip`. +You want **Python 3.11 or newer**. Every example in this guide uses only the standard library, so there is nothing to install with `pip`. If you need a newer Python, [uv](https://docs.astral.sh/uv/) is the quickest way to get one without touching the system Python: diff --git a/chapters/03-working-with-files.md b/chapters/03-working-with-files.md index fca167e..54e05f1 100644 --- a/chapters/03-working-with-files.md +++ b/chapters/03-working-with-files.md @@ -2,7 +2,7 @@ Config files, logs, inventories, CSV exports: most sysadmin scripts start by reading a file. Python's built-in `open()` is the standard interface for that. -```python +```text open(file, mode="r", encoding=None) ``` diff --git a/chapters/06-sys-module.md b/chapters/06-sys-module.md index a6eb43c..45b7d0d 100644 --- a/chapters/06-sys-module.md +++ b/chapters/06-sys-module.md @@ -63,8 +63,8 @@ If your script uses newer features, check the version at the top and exit with a ```python import sys -if sys.version_info < (3, 10): - sys.exit(f"this script needs Python 3.10+, you have {sys.version.split()[0]}") +if sys.version_info < (3, 11): + sys.exit(f"this script needs Python 3.11+, you have {sys.version.split()[0]}") ``` ## Exit codes matter diff --git a/chapters/09-subprocess.md b/chapters/09-subprocess.md index b544bd0..faae12c 100644 --- a/chapters/09-subprocess.md +++ b/chapters/09-subprocess.md @@ -59,6 +59,9 @@ Two more errors are worth catching in real scripts: - `subprocess.TimeoutExpired` if you pass `timeout=` and the command hangs. ```python +import subprocess +import sys + try: subprocess.run(["ping", "-c", "1", "10.0.0.1"], check=True, timeout=5) except FileNotFoundError: @@ -74,9 +77,9 @@ except subprocess.CalledProcessError: Use `input=` to write to the command's `stdin`: ```python ->>> result = subprocess.run(["bc"], input="1 + 1\n", capture_output=True, text=True) +>>> result = subprocess.run(["sort"], input="web-02\nweb-01\n", capture_output=True, text=True) >>> result.stdout -'2\n' +'web-01\nweb-02\n' ``` ## When you need a shell diff --git a/chapters/10-argparse.md b/chapters/10-argparse.md index f9163f5..7d46207 100644 --- a/chapters/10-argparse.md +++ b/chapters/10-argparse.md @@ -63,6 +63,10 @@ You wrote no help text formatting and no validation, and you still got both. ## The arguments you'll use most ```python +import argparse + +parser = argparse.ArgumentParser() + # positional (required) parser.add_argument("host") @@ -131,6 +135,8 @@ github.com:8080 CLOSED Tools like `git` and `kubectl` have subcommands (`git commit`, `git push`). Use `add_subparsers()`: ```python +import argparse + parser = argparse.ArgumentParser(prog="svc") sub = parser.add_subparsers(dest="command", required=True) diff --git a/chapters/12-csv.md b/chapters/12-csv.md index 8793389..f79db39 100644 --- a/chapters/12-csv.md +++ b/chapters/12-csv.md @@ -63,11 +63,15 @@ Use `csv.writer` and `writer.writerow([...])` if you're working with lists inste ## Other delimiters -Many "CSV" files are really tab- or semicolon-separated. Pass `delimiter`: +Many "CSV" files are really tab- or semicolon-separated. Pass `delimiter`, e.g. `delimiter="\t"` or `delimiter=";"`: ```python -csv.reader(f, delimiter="\t") -csv.DictReader(f, delimiter=";") +import csv +import io + +tsv = io.StringIO("web-01\t10.0.0.10\nweb-02\t10.0.0.11\n") # stands in for an open file +for row in csv.reader(tsv, delimiter="\t"): + print(row) ``` ## Example: export local users to CSV diff --git a/chapters/13-sqlite.md b/chapters/13-sqlite.md index 0db433c..7878537 100644 --- a/chapters/13-sqlite.md +++ b/chapters/13-sqlite.md @@ -37,6 +37,8 @@ Use `":memory:"` instead of a file name for a temporary in-memory database, whic Pass values with `?` placeholders, never with f-strings. The driver escapes them, which protects you from SQL injection and from names like `O'Brien`: ```python +role = "web" + # good con.execute("SELECT * FROM hosts WHERE role = ?", (role,)) diff --git a/chapters/14-socket.md b/chapters/14-socket.md index a8dbf32..a2aeab4 100644 --- a/chapters/14-socket.md +++ b/chapters/14-socket.md @@ -16,7 +16,7 @@ import socket import socket -def is_open(host, port, timeout=5): +def is_open(host, port, timeout=3): try: with socket.create_connection((host, port), timeout=timeout): return True @@ -24,17 +24,19 @@ def is_open(host, port, timeout=5): return False -for host, port in [("google.com", 80), ("google.com", 81), ("localhost", 22)]: - print(f"{host}:{port} is {'up' if is_open(host, port) else 'down'}") +for host, port in [("github.com", 443), ("github.com", 8080), ("localhost", 22)]: + print(f"{host}:{port} is {'up' if is_open(host, port) else 'down'}", flush=True) ``` ```bash $ python3 port_check.py -google.com:80 is up -google.com:81 is down +github.com:443 is up +github.com:8080 is down localhost:22 is up ``` +> The timeout applies to **each address** the name resolves to. `google.com` has a dozen IPv4 and IPv6 addresses, so a closed port there can take `12 × timeout` to report as down. Keep timeouts short, or check a specific IP. + > For a full CLI around this function, see the TCP port checker in the [argparse chapter](10-argparse.md). ## DNS lookups @@ -72,25 +74,44 @@ Checking 200 hosts one after another with a 5 second timeout can take minutes. ` ```python #!/usr/bin/env python3 # sweep.py -from concurrent.futures import ThreadPoolExecutor +import ipaddress import socket +import sys +from concurrent.futures import ThreadPoolExecutor def is_open(target): host, port = target try: - with socket.create_connection((host, port), timeout=2): + with socket.create_connection((host, port), timeout=1): return target, True except OSError: return target, False -targets = [(f"10.0.0.{i}", 22) for i in range(1, 255)] +def main(argv): + if len(argv) != 2: + sys.exit(f"usage: python3 {sys.argv[0]} NETWORK PORT e.g. 172.16.0.0/24 22") + network, port = ipaddress.ip_network(argv[0], strict=False), int(argv[1]) + targets = [(str(ip), port) for ip in network.hosts()] + + with ThreadPoolExecutor(max_workers=50) as pool: + for (host, port), up in pool.map(is_open, targets): + if up: + print(f"{host}:{port} open") + -with ThreadPoolExecutor(max_workers=50) as pool: - for (host, port), up in pool.map(is_open, targets): - if up: - print(f"{host}:{port} open") +if __name__ == "__main__": + main(sys.argv[1:]) +``` + +Find your own network with `ip -4 addr`. In the iximiuz Labs playground it is `172.16.0.0/24`: + +```bash +$ ip -4 -o addr show eth0 +2: eth0 inet 172.16.0.2/24 ... +$ python3 sweep.py 172.16.0.0/24 22 +172.16.0.2:22 open ``` > Only scan networks you own or are allowed to test. diff --git a/examples/__pycache__/Automating_System_Tasks_with_subprocess.cpython-314.pyc b/examples/__pycache__/Automating_System_Tasks_with_subprocess.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c8dd247603540be13d72dabb8c8b99df0fb244d1 GIT binary patch literal 617 zcmdPq_L4Y0`egH`5!gt}NB=x=2PO^%l!X}?=cDQQ(qx*3{`x7dnH zQu0enZn2i;CFZ6A1&gZqy;FN1)O8(|_SYaB=yA|pjqYN4S)X{yo+gcf9^2*=v&4z`2sUCoZ$ zlwQn@_7V=Q6!pZ>z2%sys;d46ZlH;ov{It>l3NrGl~50Tv&KN_ThH6~-n{u{=6i2F z*%6B(ki-DmEGY>6DV&z5C&tltU{ui^WJ(K&HQy4Gz?T=~j}@kjAX6DY44W9VYN{-h z!3kuBrllqV3unTa(7WFt`2u)c2jP>8Zn?l*S}5oA4*^PF@hqF@R@u>4NZAqL`68jr zPkCSPE;~=`&FtBhv;%-bFnj}475yH6>sj1*5;tm>_v2H);{NKb-M&Wu;J530E5G%< zU0rOn#p^hJ1j)!g&q@RW0eAldIP0gpn!uAOLAB(wdU&#_q-7J2L$0ZU6%y83j~N#4 z^;6ts4DJOH^>6V$D`lmMTv4)U`XtL!(#mr9!V+*{7bzvBwh@WW|B&eKT@O6vn$4ctj z#+E#m*y=i0te`+Vyi&P)kJ#+E+j2^U@(ps|DtSecvfUELA5qZqs>`*aYg@&<>$4?8 zrQ*mu?3b8VEZpUIWpQcuNtFsEl49_`5D*)D9Kp@G#`2W- zdAI0L(Oq2ifK~QAqMZUF;4Jcf$#p74GDpWCCi>ss0QFjtBao_IkdSdzjzjKJSou!8}dv^WOL@ia1 XzV{T*ygV1HPh77@=bqvZf^+-}xmZNh literal 0 HcmV?d00001 diff --git a/examples/__pycache__/Multi-threading.cpython-314.pyc b/examples/__pycache__/Multi-threading.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6251b3d8542e4537dbc43ea1e11e15d7ecb3becb GIT binary patch literal 985 zcmZWoOK1~882)Ep>28|zAvB1sNhqmoA3@q!m8wv%m7>*UDZz?KNj7T|-Dbn?END(S zNfn_Ud+bqf#gl?yy?IQrkUI4y2;NF_D2NAV@~Bn+VgLQUZ~oUTvtz-40@R`*c=QVa zd}E|zzBXulr=SXH(9r^5)O>T8)432}J`Os62Vo(Fv}UDFa_g-H{^pD&+R_YKK_2Jv zE5{1f7{~0MhB_z0(j%6LOmEc=E3@N!6=KTOzN%^CYQWEqW%))S!c9-ESoqHG} zFb3yZ8<3~92BFA>VTeYtb!&KrAA%xMg&!>Dw$ZN9OpvH&-5M{btHS-J$eh-m=~$p3 z3Oenlb4iE`CnANDF)gg~7u)$|ltdcq@{gtA(p`WY-5G==bb~HTa>FeoGNejGC>Kll z3O8X8G^HXUxj1KgxDtpI-H2mmj6x=BnUx+!z0$Fu3Pf?eY}v65({%~&cqJle3)&n} z920v^$*^;#$`PSpyO>Ch>3SA+*|Z}O(!WSaaRL`;xg6~tFFzqN8)JnDAPhP#e7P{^1AvoxK~lU7g>Hjn!k*JF)4v(cRe0T5c`*@@mZ= ztqIH9*SDuXg=@3R6gOxgQ2C0Ix9z-T#tnOw;vz11S%!&h*+#}<&DCzwZ`dWna~!jT z;}1M~7SkolAI)Kxx;Y~eS%yn|ov8k$=7}`hw&ot2hKFs3beSE*uV%``*ZvYtH?2a% zvQsSK*WmQ9n(U^Nt}Cl{&a=#G&KXMCC33UW9qe>qqtXt2ljmw+n=iqqt#t{$FL_>m}f$IDhL0%hqy4c_; ZJMvMTCjE5j4*+jY%|^tJ5&!IY`8UrA+jIZ` literal 0 HcmV?d00001 diff --git a/examples/__pycache__/app.cpython-314.pyc b/examples/__pycache__/app.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c1feb7667f39de9610475b4f8abae7382a5da472 GIT binary patch literal 790 zcmZ{h&ubGw6vy9We59|$5<^iaZhUdxi5q`~YDW@g0(gn05A zPhNY}TaW%3){2R9DtPiDf%peFyUEr-aSm_Zyzgh;`wp{JStx>BgDSlIjR1b8hkRMH zWHOdXA6@`PPl1CAjY5w6+t&dXuu_*j(!~pIpXKdVs}DL+Jv%g2Z@qTSd(^Q-ibnC=88aj0&VqHy)cLERzz)nKy0tsOoF8A@rXLA zFapB8R~{8AKa7dcLXWnYP!C8q?rF6eO9D|mzd=Na$!lc48HJ4ZHl>=i%%|F$K52PL zm*2HpozTy;ze6jp~U}JvCPP>JQNR{=4XHH1IzJ Q?}JnQ=6AS7uS*ku0Tg-0iVQeZGD1`$bObRfGib8B1PS|9aTZq=>m?SYmswS@=cMMPmtemr0EtHNF?6CP_Ll!7Kcr4eoARhs$CJte;~VxwSdG2 yW=2NF&uk2g+z%O88?q-DPq&z8afLzVCXkmoQFub|^oWTOlVz_l$QN+{l>-2-IyU(L literal 0 HcmV?d00001 diff --git a/examples/__pycache__/argv_02.cpython-314.pyc b/examples/__pycache__/argv_02.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7effb2add17d47a5455f69de34ee511410f5e6b4 GIT binary patch literal 439 zcmdPqjEXo-eQe+tzWI*~k5Gr9TMTQ_|R6RTlK`chhFcah%Vp)M|Sb=6j zZI=hSN0~vB?Ip+vKdYA@tNi?`3^Mb|5_2+B6!J=QlTwQm^3xO&i_%MTQ}arS6*N*S z3R06xQd1O+bQIDv%Tn{K6mBtURtc4q=OZagEK0S~WV^*&Tv>dJ1*p3WOcvi_&PmO? z#gbZ)S#pcDpeQr1WF^CAknOj)K#JlGjPwdBZ*kb<=BJeAq}mnn0i{5$Ds~4FAD9^# z89%czFmgX&=W4HLteC*mTGPPtkeRKaq}g%;V~gDl7WQ_JCXWmJ_6L~{xE$u(QGG)3 a0qtQXj%X1H8qP%PpBngsya?P1OU literal 0 HcmV?d00001 diff --git a/examples/__pycache__/backup_log.cpython-314.pyc b/examples/__pycache__/backup_log.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ea854fa3878922434a243113a36862c25d1f639f GIT binary patch literal 1388 zcmZ`&&u<$=6n^{5>s@=((kiq?Zat|buobJKG^jyIK(4cHR&i`=yeW>T6I^=}S$4d^ zJEo~m4oD>Q5_3SbC*S}rw;VZAi9f(q5LnBhl{j%gN|cI9oS2QhF+$0k)%^P2eD8a2 zW=Dq<8K||-L*+vb;16fvn$({hyvYKzU=c8*0qKnlVd$FG*cq0vGaTW9kcW)dJvtai z0CQtZZ%u@}kWmJhJHx!|L0QBR$TOMKE;bllpG9sw2T-yA0w;JbGSSxt=ZMfcQ9fP7O(f~k(cr^_Kwd0 zT;s-QjU5ZpDm!hA-bQbILVU@s$7x860NkbiM4?#>_0>#KfEQl3_+L;0Z4Gk$(3^b-v+h7Ob8H+g3G%?RR^HV2H_%A?zCiXg1ZQ1CZhc5 z(4-=)?JX6ELCUL!&CToarhKPRtTfiFE2TTl?`1?Sj@6j1B0Y8^sUj_bQfVEjIW4Pa zQN2;KQ25Zx@hq2+meSRmDn=Qs&BgEnnpGE~N4P}_bz+o|uIBVZn$&zUIe;m;Vvv(i zvvNf4C~%G*5=Z3bbuE=uvF_mMzNUVtDC&_$ky(kLTe0N4nnmIFqR9CowrCkevsSVq zjO}$wV67QNn>8!VsjQk*<2pKq1|@KMt`{YZr)jD;7M#SV)odIkwK+{kZ#P+lntXZ| zA)8Ocv}EKJ8tJ2InHbk>&bnvSo!3+6X=jTxe$6Nno1+t3G}et`gV3v}8a11z_4wHK z^fItLR10ZXHdiz6+EUpvm(BWWfl%gNRqLX|C#==WHDU|Js%aTNzyaL@Tj|~DQq^3! zvUbn*POh4zM%8$??)-<&Yq$QQ-5$p<%z+1(Q@?}!3@$(SD4XUdX1luU3AMN`aGSmj z-yVnx{{lot*gpfj*s?a)H`YI$YR7)zhMy0g|0?%I?m^+p555UK3V$1ZeD%B0R;rcQ zN<5SN_s@2{zHQ&z<`Tg_P}R7uwyrI~z*l zq46T|BAzVq09O-DJbE;I08;`H9b;nR$r}a_Mla5`7BO`unfKnjncw@r$(#)ZW#D5o z0;_Kkz!xuQ4C#+^e4l5^um~!e16sF;A|CtZe6yJ17^qkkhI~}e#003K>Q{md$X}}o zBb?)n5ntWLpc^z$LiOnMngC5urP>UP3H1yOXqeOG21V&UeWUJc0VUeJtDaF?$4+Y2 zGzPUcUgN)~8+p(;9B3`yn#`5Ctl0Na<|ObImQ9tVEhKt#IDgs1}1B zUWLk6<#}4S1~Om*_ke*?ZC}01*HefIN}6UF*3+~k4-={nXDx?1rFPpjO~bq!*R6a$ zZDz(9ir+|KChA$DudPDdOO{IuE@c8GMOu=GZCmzuywp;I3{k!(y7bQAMP4XC zOx?E;nZ^ z+uloZ+4&3;3$|f$2`iRiGR$=|zfBxBM_G6(oy(DoQU^?X;us=KAVq^Rze6)zFO%17 zgOVk$f!ZGLh~XSDpTn{DMy%uCR)-4fEO04rW!xOOVtaqX`-9F)z8qnM(6Jv-_#?=l zAo5vi-N;q_-DUg%#Hv41NpAOV_3vDGHh2L2M*>F4_rb2mi;os7Q#5eTDiHcZE3G=RUvu+musZXEnJz|Uf5dLj|^1LO}~SgA4e?^2p>v) zds5$bK%6W{4`(0DZmezIds=)_++3*!6Nf_Yp3wWtlbQVKbaBNmIwukAqK?T4yc>>9 Lj^f=>k^8>^uv+8P literal 0 HcmV?d00001 diff --git a/examples/__pycache__/check_call.cpython-314.pyc b/examples/__pycache__/check_call.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..00c93ba34dc68a34630045cc08283cfddbf90610 GIT binary patch literal 751 zcmYLG&1(}u6o0dyY0O6xss>EkE$tyeOw1XkUCxjPu>dgAbRO+(q-Sk`~Bw4`@Q#O=4L7x2Wp2o*l8eu zU%@7{*d-a2=*d28fPx+Yo*=?VVHCE+U`AyZK;aZ#o(hE#s!WAy1FJ9-oQE5rf;{dz ziG+RuR7MfTOT5R0*$P?&DNrQBya)x*9|Gh7izZTrpLYv*A9%1SnJVWG0G) zOuinn2rHK~0e89ZKJze3-vf)QVld%^naG6u>@1k582=q;nuKY4-9*{4%bu@omvz(a zPP@Kknbs3Yvpb!ZrB?}(9v4}{YukplLsDAH!M%pUE8fn#;%E} zP&cG5Qv4 z6eMxipe?PSE)hJe(`JPCuxmQ+U=-YgB*(*TYP3kn*(0$B9b5O?#)=!fR`A1KkGgXf zAv6*IWq&~Yr+DSr#z4sLv)_Rq2)U!hmxbqr{_=}k-=J{Lv8aL0xKyus&^%l|(vK_e z^&waPdnRUv;?iev=?|cBhS*y_SRbUNe&$X7Rlc8kyLFs7&7I^<=T7Fn-dP>ot__m) lA-DF0Tl*jMZ=iqPRXWS-Yb)>}Q=4HwrmM9y`zg&+egQgwr?CJ4 literal 0 HcmV?d00001 diff --git a/examples/__pycache__/disk_alert.cpython-314.pyc b/examples/__pycache__/disk_alert.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7e3c43ed624b067a17ab3de4094e3b68594810c6 GIT binary patch literal 885 zcmZuv%}*0i5TDn5yWK6&gesw+k*$DXwSh>C;lmg;@)fl<3u!eeY*xC!hSJvEElN*4 zRujS=IP}O76HPe!XP{PvCkGO}ka&R9Kfw1ET0A((%$wPn`OU}9jbKXvD7j%+K12XN znNcTvrqt3@DZw15XbPOu7ddDy?)X$*^|eC=IovE(xuItO=}v&lFv~??7R5d6I^5~2 z;wX)%Qv@({QQU5i72$|EV)L|<28mSTDA#^dQG!&%5%)FJh7y4U+&asCMYF6>o=Zle zO^pDUOGo*0E00qRD*?^4iv(7EEueA<(zo-iNC3zlIN zrR04zHWizoK>^vcW&K5N)sPA5jhQt0o+1#zUMe_dh6K{4y{r{%ebFF%-ZHZek!B{< zvFXXDj~^1wUb6`{UYm}>6P(wbCBi#7N6!$cttm}R*1SK%65*55*&oDd=D$1!^(Egm+-(R+*TTMFYX0H>zT^**PvXQIKWbQ zrabOmb(588_sLdxyJx5ELv+X9RYpG!?*_)Iczn+v-0Z0OJAa8y8{%8h9j?q&#<#A& zf4==_=jCqe@HcVfga`3bjg|x=Y8vZA(?*WiJ;Y)PB4|JnEcVYVc9<4x(Cd^1XZ00B z(+JkB#npFUU0}XeDu{SzC6_K_jJp=QTZU!drs9}G2-O5Y!5dZv|9iG literal 0 HcmV?d00001 diff --git a/examples/__pycache__/filesizes.cpython-314.pyc b/examples/__pycache__/filesizes.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..69b01c63d1f2abdbed7aca718e5ab846006d2d8a GIT binary patch literal 1329 zcmZuw%}*0S6o1p1?k=V42Y$2_w2K(y`V~|ps6>PDo1``?qK87W+67jiZDtp18>1w8 zs3yj8f+Hpx(S!Og=wG1Gm^gCNi#N0!j3;NdEL7r4_RX6&@BQA}dB54SMhyX%N)$$? z0|4K|#uu_=REM}R34>su^WfH2Obb8@4B%E6KuHhT2dk|{ zaPO8CPY0^magN;PeY*5RxDwZwPP}uOYYafDE!;Z^DbFcXl6SmXTA?3&+;wm!4N%~@ zv?-7KG2dST$dft*{~zmMlA_)!xw5fisa8JNT;IX}@*7qq^KF07?LVL+@pP2G|C@W^FZa8)%SPzE24I?Lx40$7dt?z>ZWXK#Isv{%TY1Zq>IZ>FtsVaA+QW=ijyc7G1< zsj3j$Ud5ny{$32h#^yypYK*OmE?~a?ahiDTw}E(1H+kFLc(PG`7eZYB!%;pD!BMEr zd3~mq`Mbi#LDa>6BGWD=ms)0S@;?k} zF~KRF{1APX)=oI)uys_+7u}Iu_K;R0+NtwKLJu;`$H=f#mjlLg<&&fcE~1ViZ{j0|}Q)pK$C8 XQOX-0M;}Bh+aI;?hJIooTRhyq&&>Ni literal 0 HcmV?d00001 diff --git a/examples/__pycache__/follow.cpython-314.pyc b/examples/__pycache__/follow.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cd3d6181a823505bc1b37efd6a1f716c4061661e GIT binary patch literal 627 zcmZuuOKTHR6#nkaoyk0iO@jfE)TBO;G#C(Kg;p#|6-v|$gWI%dGA)DCnPKJ*wpn#q zS5^?JxNz;p|KMM6QR7_+uH3Z*3Apl3oUtxE2hQs|=R44>a?d+x+I#oc&1#xYv?QCleQx-*RD*cD$@3c)Wp^hf5 zW=&fHslt_Nm_u!<53VfBb8tzc@FVSc^td5$HD-e#VVp8&hYgL;^|$Krlihe}XgE7A ztM`L}v(%uRrpQpb*5~BLuyDOK)rQWEIC&aILEnjEu2@0n_?%j6);%#Gs!{p|PCeIm zxDrOL&$t@JEOJ9`L=H-ZNzleBSm}8j` zGFCy#-;|jzO69Xs;q>Cjth`)#u`<$&lLA$xpAhC)gKCUQXAjNS=05$Z75BY2tM5B+ zJMSJIX$vPZW~&oZ^qrJI)IIND^|1S@dxXoASy7y%48LMiZ2Z`~v#5MpH1DeVZ!%hV A9RL6T literal 0 HcmV?d00001 diff --git a/examples/__pycache__/github_stars.cpython-314.pyc b/examples/__pycache__/github_stars.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7ddd143fcdcd0f0353e60b34beee1550376cf346 GIT binary patch literal 670 zcmZ8fzi-n(6ntIGO!?3C^8F6V!4f*m^wb=I}gbe zCMp&>c4UODBP;(w5R_KOg2coI%233_xsDZychbH0efPb0@13q%xRe8Khu2`giU5AZ zAT?zcO#kp;3>`4hW1xvgR4@f9wuP3O%ICh7pT}v`7CSjpydxxd3t1=%A|Ele3BbbhAP~g zrS*7U*TEG^unMJ%wXJQ5tKg!F`ZLx%88!Qq24qv$?ZDM~F6~D<+AbdGp%Y-D)5x>C zeLK`!L)yoFeGiBAr$b_N2d-a1Orh?;!4YNIy~y({-yS$4sob|onO!E-4tw^<35m6f zBcG1sa!ip*j%A(`?6X1?dY-$Zh0cq}A(Y7pW+L}YNm+#>95_BxLx%*|Cl1Sa*zU4S z+#!>K(Dmtin8wqv#bf~M;vy{=GWFg7cO%caA1?9p_`QkGw_hScXet9*_y$+M%f?td zlk%@RFFU7F@sm_Mdid_jL@J(2wJ%cbSUt-xzG=R09zOe=UmHI<7eTK7=DG60^1=Q| wc4eX#k8ZzRo^0GbS#M6tn;$kNvhfujoGV<&Yy2hgzd2qqD$>VF-e_k30kqGa1^@s6 literal 0 HcmV?d00001 diff --git a/examples/__pycache__/grep.cpython-314.pyc b/examples/__pycache__/grep.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..276fd9a7a797ffd11eef3943675f34e81639ed39 GIT binary patch literal 787 zcmZuuL2DCH5T4zA$!?l7P12$<1iP`N5YiTHb4aULa!`>%2unykBw2!4;?iWhyxnS( zg9P*th1wN`UKJGUzwuCtK5`H|^;XRv@V#x;NuY%20c}2)kppgVfLX}HF6^eeZbo?r4IWdm1l!M7U?X}=) z+IP+pg~ua=1>mD9P#yYdwg;7eSQ)$yH7@szvfpIv6`mC_DS9(shOSLfo{2C1Gh+=V zXAIE|*94De9?Ep{N!*<5CQT5H+z8xX1TguX*apos=^jbg4gyrDUP_rSPJ90N&5qnL z^Y#)z0Iq`~EI=BavnzCG_N{tT+my|Y{bbKrm%EZ&%$G{{ltLjb5}~CTM6fy*LE3?C z6I92|r^IL34c#C<6YGXe{MfRwZl(pyh9{y~w`~m@1hsTSv)I{}WSNLfteLB3hoE*{ zH}DKiv&&f}YI-mbr~26!9Vh?t`9KODNv|bm>(ly|+{fHW{`2h*D<=ovqPbIP<7YVL z+&XOb9tRb_Olx{2AJq&p$Z zXkC7W8uhlOs_x`p0Y?}Vb_?&c_Zs^x?Jl09A-j~dO3j79aoo@kT=0)y!q-8xI3R33DuC9HR~|LRkr;Hy;B7CxaYAEDKNvODv-a6GT=XXoE6?ChJQO z*RP7Tv?NW}LX+_pM`~VjeoAIudKFJeeo11ELQZC0YO$3j>n+Z-%$(HByn@n_TdZKg zTdWWs3y61%wV)_7uVf{|XOMxnctK+E$@!&uC3*#ww>WHa^HWN5QtgU>&SU^Ny4V~@ zd|+l|Wc7%g5T3Vx-mL8=p`lhqXkJ~#$f_}vwD0RB|YK&*YE_X!$psDOkTRLC5;q)BZ8s(RI!)}~2C%RxoYL1Uyr zq*=8p#>@u*egR+{YNV!>NlmYqHM3@wwX$AIm9?5(He{-59*1h`H0j?m0vFN%(yk6+ z)E-19U_J{l1jnFaoq%HM_I>BQwLnmOJbIJyO)7$BtHG$K^PnZET=OKo*6^fcp@M`= zNaj<));CyKXVeRQD!CVmYY}f^8U*vGNk!CTaxDl~X(PD7FiRkurKu8KI#orrG+m;3 zAvwO!qkE=AU#nvLbv!dwDx(BX75-F-{tv652vj&{PO7Rot8Z`-++=i>g^YVL;!cso z_MAj#rNQcoj(ti12Ld{t-UU=`ScIB3gR}54HVzA9ja0}ozUj-dHn2*mfdx>}p2lC% zkV5^j!o|aVX50ZYaVl61BhLJy78{K~$k>z{NG#T7DXu&zR8{%-#RDG-cb{(Nms^{0 z#&x|gjHD-->vEhZsA9x1RBiYNQY6<^>Yn_Lee=xnpW!9^Mv0Hc_%qn|j~_&=9!U`DwnUyH4&%ySN3L&? zwszTcu!8w>fVbU(wuv?lC0R@?G6k1M&gcOtlB-2Mb^;NELVCDxJR$q&0nVOK#)~>v z7jp|$Yy^@ug&KIFK)L!a`S3s`EWVB2W2E8Nk%^A6r;(u#$zSQ`@AzL{+D%XHq$lrP z|9)(@d~v6I@weQo-;UkS&F*GqcQUiTKX>HQcY0YErCl4c=g7Z8<^A~V`BCx%IX`Uu zIEq$myKd79Lf4J0{<2>!I&sQ%{iu$y;d<1-^^`#rin6y-?{}snGB#H>B@;=lDoN-y zarUu}s}++VHe2}P$ghECR4=Nl*go5g{EY^CgO8)D<|sT=dpaScs~N=j+W|89@XEW} z3yVL`CtI^O21cfH`xpJ_!*r&z-l^YN_`=?r+VZvv+hfJMQ`?7MzPrBdOts&9lr3zD Z2icPy^2pA1ywB~f4u?uz%Oplp!hdfeDW?Dc literal 0 HcmV?d00001 diff --git a/examples/__pycache__/port_check.cpython-314.pyc b/examples/__pycache__/port_check.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4424f4ff4cc039fb111526ebc59720e5a6fcace0 GIT binary patch literal 826 zcmX|9O-vI(6n-m4jegk(!kR6D1nN7)eTr5>eMiFVqINE8S4K&Fm~hPt_C0 z9z5s`V@%YG9*Lf~c_ckpop@3&+(=4df*0Rl>6^_r-`n}#-|mce8!2Z+K+tTqZ}d{@OR*cj2VFf!%0-XqlD1T1!r zZnv{^ULZ-qeR6@`qZS<1m?i}h(0~l7vO=sAdR?x>72g#YVwxYfQ}~GA!Ix#|y+lE^9Iw@;!US5wh3j&XRBn zwpXb*ws5_Q4Bxst%elu0G6r1I(xu%i%YGl6k5B*`#JxkEVr(tCN{*L$U1JMWN zv4K5?`+2D%PKE!7r`bk5!4NM`6&-AhFUV4+*;ci$?nAFzKEulYcUnY HRYU&(d>p64 literal 0 HcmV?d00001 diff --git a/examples/__pycache__/prune_backups.cpython-314.pyc b/examples/__pycache__/prune_backups.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..291b5174c1f6237688275617d9ddd312eadab063 GIT binary patch literal 1316 zcmZ`&L2DaF6n?uq+FeCbEn9Y@I3|{`U9wJOnmABV2N%~)un;w3Y1Aah5^HI#2urJF zchp2G1w$`#pp~E(A9`@1r4Bvxnqv?B0d}L>&fpMAPrW78AIQvF8;Q~m?0awCelzpE z_sv{+CvXnvXoq1-pWs$G%&qd6Ulp)0$#Oyht$MI$ z64v=BWF-}SKv%JWMb&d2u(U3#V*D;Z;Xc3wtb3!d4yn;I%%Hu|TbJeI4=MVxgND?* zgP5~83aa$qdt~A2cpvWvRlY8``%;F||DB!X2G{jhsN58-ehL)t-)!48MIdrP!#XZi zbmC>UpqH^mggc)uD;z;74L@MMpw;bsuO5ewOszn_?wZrnjFV(0MZ5p+5rqtLb1s*R z=w_}u%AL(jF5`9cX>hSApPTD@_3hsv+|~e0et?6&k8`6ar1{j4JL~%!y)YH*=iF$3 zb+0N@`0QGI1fWQ3pMc~dKqlm(RW8j_h4{3f3IR~jb&tz`lAS%~;`-h_dlHg)054nu z)kC!r8}jTN)~vZ=qv54`P<4!Aq~VKPu2c)9&5~Y-G~}6kv6)J2ra(AlP4QVw3nCcR zhZei-1SN0XN?EMM1QpBG4HDS2suiZMjkStN5OtWyHqJRo;xVm~fr(f%$|Yk(ffygcgn@Rd!BoZM()2bPIZbQp&)l7TNtP@nxN``fw0+_aT zjhbyZ4UDxik2Bv*Jquj=Vf2r{%=Ycm;As2aw?oIl>BHdk-utfwC@Ehq1!aw`c{@e{$W z+fFMjR@_-DC02I1wBdBqVmHw#jO}V@6+M?DLRmKm(yZd=1nG}T_z75H24gRs$Tw-j zYGr-Viqa{2LbgH8D}m#PA5rASUyT6rHya({!gJ|d zbG{YdiGTIwF4vJRoXEbG{8(;(v^W1#{QLO+(vJ&!vHdR&h8H^W&F4sNhFamBa69_- O#UnKKS^_lg@OcARtNr2t literal 0 HcmV?d00001 diff --git a/examples/__pycache__/stdio.cpython-314.pyc b/examples/__pycache__/stdio.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0ef7dc0a4ab8e127134075125ad9b27ff261fc43 GIT binary patch literal 825 zcma)4zi-n(6n?IM)IZWHp;VN%z@j-|+mt_rCYN?Cog=gSM4}d{as)93B7rivDK@%Fvs4nKlbPp8I4M#h5S@(~#`eB(CiE0Z!&8P0hr7 z5@AZ*7Pe8MZ2M~{S-DRbrpQG*I7Wd_aD-gqp*F=)gzhpLtlvv2EM#twPbqdiyJm4Y z+Kaf_raoa@iv< z!j1MG*SA`s*9q_)dO-}*|0+5V>6a`?(oh4*`Yn>yB?Fj01^Jcv(ma9kA(Z=->Ht=< zVP9K*zxmPrU?0QAf1KI?Rt2Y2*fgc5S@)b)Wn82(w@6F8HnccaZH4PBfnTPr-1n?sc64NGR zEQ?AT_Q6J5z)lb`~Q(eL;GYOkwc|vn=?+yS{ z9jIid)r2j9qn5?XVq?0a+wzsOCsFKe<;HV>LkZv>VF!|1UtT&{x_R} zYf{qpJZx_Qq#-ZTcteh1wL~{f^a1yHJ^Qe zar_57%Q6n^_>ubntQj`P#j#_Oh`HE!M1F>RVusY2U8DRRx?x*XhC##z!;6Ypwv z-87MaAP`DHsFC2{V=94~h$1+lo)B$8a7=$l!ZrvADxu!m1_@Cvyjgpb77omM-^{%E z-rJe?-Zzdl_`HDa*R62oSq|VgI&m6b8>~&?U>b%&W{!ec?HQA?=d8(M&mQGo;7vXZ zGS?2KAoD0)r`)p8`zpXl5FiMrToE|Mrkfn+8@=q>xp`xjWU6EI#dO+l)P0YtQc=e8 zXHFBPFp}1^u_Nb{V%gM4v4*#;+$ixBu=X{IX~@C^3qbr^AZIUAkw(qGTLez}d)Q${ zX7<%q`dLIl(I-j2ge?r6AVCbaSEn$FK7ydKVF=+GePpf^ z`neFOj08C+s^EeVks`y80hve7YzRH6HDpw{M^A=_cAM(BqLs}|YADKCE<-DxQB143 zh>CCh#Ml_P{`grdv>8ATL-S~F1U8ZiyJ-KQnV5{(H((c}80QZzR&VPXw}!U?CZMe>zXs?#;y!5`v#VL11l|?D#_Uc ze{#@p5HZk_)RV1&?0W9w{r=8cwX`43AtlCGgM4q(AGU1()%K02LqL|0O z;`k?#ER$|@P#e8df=zG&i!Tmkb_i*tbGc>*lU?6q7E3h69`nAMxSeQ##ugDi*6GPb%ISUn_#c$?yP&g{4rZWpgYKITDNpzBwbk+ zr8~hp=MBTLuIfHzkv+<>bXbvH`Q1+3ZqJ&q)(cswNj5X z)g`5lWKJHJk4fp{az>IQB|aLL_Uuc<_w0>#$GdkYl2Rfugj{nOCQ*wfj_Sq>=kgO8 zIinE6V)~{8i83V>^;z7QQnEN>(y(~toQmv1s-3kws$LiwA&OyGURBSR6q6cToLVw1 zfwIs*85)2HU)Bv;h)8C; z5n5RmKVDEvWE&1K^k96CVj5Q6-kIb(le2^GzPT#aT@c?FXAgeTbE)@Y@BHAW{d2n( zcV`xxPuv!>tAWsRV8_kCj`_fR;q&$@t+xXQzis&@^F!pjlh=bYnU!ew7ommFa3e0RY6GwgZjaxtNYeh;(jeh2XNGgG&@O+WGCOv{Ci^BuEWKMXGM NZ4Wr$Hnwkf54gSE|w&MbC~_+&HLVavomY+u`tllOTp_;9KcVu z@Q3IXBb)A=KnV)mE?_8fD^Lg&VNdXhf4@=K3_PZ6HkMr`Pno`wyD^?;Fa^q#Zcw~( zf*D)^%8O3(eBV;|>3e`m0^kl~&QCLG{-DqHQi`)RC%oCoLld16?Tk-*6y}};T-0+2 z7v1Cw(_CM1hFiqzy8Yi>|2T08e3xZPDTyv0V)#qhTOA)8!&E44oEO*X6pRwPnRPYSxj4O)EspV|iP)7WRyq zhM5%BWfNEQCZ58mOpYVMVNFF=vaVN}Dw0j480D(mP;k|xR&f_LWmQ)ysIn#JB7`^F zCJ8o}J_&i*iR8y6Vbnt9CRSdli0~@Xh`=%t0kvwFh%^edB?2=bAy54yjMyI`b5!}@ z;iHX4n@G>xz2^qIHTJH}&vg3Da~wAkfs0&2(3VpD#4t0+^kcSo&w=~j8Mf3f57mL% zFWF+=fpv;?W4-dZcBa|MyDsmV7f;Mi>rLzJc5l<+li!3;XXkXsj%6JoM}@ng9)B*K zNnOhp(+*^q?v3Iiah1MIe}()w!_uI9v3ixg%zmi%4{UMWfsJvF)F9D+Iou!Ye_71g YsRy>W=0N@j@Ez$?>fU-6G1$}n1FVwRMgRZ+ literal 0 HcmV?d00001 diff --git a/examples/__pycache__/tcp_port_checker.cpython-314.pyc b/examples/__pycache__/tcp_port_checker.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..386d16ce00f5704454a2d993f6e93c0691e0822f GIT binary patch literal 1930 zcmah}-ER{|5TCu<^GEEex3sGduI! z-I<*oZdRKB>H2QC5~Tot2*oFIQGH?a#)&^ zbQo{U9wP=>l9puSxfS=~dg3?MSPAza^??S%Fx0@B$LIuDQV(=PkM|S1JSKO8MKs7@ zM(PxRydpe>pDy=-)$mEuB;i5VS~N>b?#%3DQsx1tl)GZOye-GftZN#%Qn6^}T&q;% z!L#R2Gge~gMHfnr%c)&rE)%ObVvB==gFNQuY(toh+=7WfY}CHW6;Ean^a%;)lgKKt zDN&_!LyfJe19#Pdnp-QZoLN&-57g9pEdG}a&8G>f_`j>B{`oV~{tSrH$y+)$WgP!@ zUPF*;y%REgE4{9K7ee7yWCFrJQ&8t#h*8rh?u+M_)wHV;>N`BMOIeRum-)5$T*7QMhkDayM<7ZkIL=)<(>w3f~1ndvy_OBc+7U6w}da$sacKyfl$?yFjw^$^PUZ^*i3lK&Q*s~^Ha-BDm>uDFiu4ju39JNAXT3YMJv~VtMcURPi93QPIqGPT~?aU=X?c$sdr$E)<~@K@p5*sa9P#J%>nmV@iDy=$?d)!0xixE$IDsnlXo4`b8)Uy^kzF5jH70eTC7;U1- xoKa->!V!ldZ?hk0bh&(A?)r^}KAU_Z1Ks1{{R>YIf?5Co literal 0 HcmV?d00001 diff --git a/examples/__pycache__/upper.cpython-314.pyc b/examples/__pycache__/upper.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f6543b061e97ad85a93f689ac6a3bae900fe9d75 GIT binary patch literal 320 zcmdPqVlJ*M zzQtNxl9HKsizO#BFZC81kdt3pa*MURD6=H>7HeriL2A)ThR+}!w>ZE&y@JYH95%W6 zDWy57c11iu36M3#20-EiGb1D8XEp{#?gu>l{hmFZ4K6oW*xS7ty{@x}Tx1cM5HdY# UV$|fAYb;8inHhM+ia-Ge0Kxb;)c^nh literal 0 HcmV?d00001 diff --git a/examples/__pycache__/users_to_csv.cpython-314.pyc b/examples/__pycache__/users_to_csv.cpython-314.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4f9605265b0a0362847edd6bb08d6330506553f2 GIT binary patch literal 1228 zcmZWoL2nyH6n?YgU3=Gd>zIm$lEiVWQn@8@gp#(Zs~!q2LP2&|+>}F&ad#)q3VYYx z*(Iq@7AN3B;6f`7M1n&=LU8PX1LYUggf`J|0eWd~6+uEpLgMY(u0;EG=grLf-n{wV zd%GtNBsD?w=%}C zw&gKbM6dde7XXUYv>lfrs;yeAW!jB4<08Q}Jh#CchG#jpF|2M#Oh%o|>en%IvCSegJ>Asf(>Gq5x>=$bC&V3A^mR8ZeC zt^4R%&J#f`+e3!Z+`J$@51RhMv^eN<=JLAd)D8aLT<4ll&o-IOHahM(7rzuZfP-gI zJwT4PQ^gyl&8uI%xjnYM`0eMCtKQal8=f=5Lv{+ z!aA<$CJ`32X_+EwIPEsGJrP-R+DyoNjkQ|&i2DqBgl_KPU^R{^e^5{)CMdtgg%Z}5 zi-^-+&N>gO<>DOlV%{A?En;Wej_J49IX92n0N`JvdPoT&`wEcwub};*zS>iM zm(>qux6<3qUHRl4`Q**)Ug4$hy5DqfW`E?jtCx1GSNhc}cM8T%!t57}ZTeyLlicR& zbz>(zb2phoQ$Jz$N`F&OPCZmWOMX1{(bRSNg?2;xxlq|VI{OzTTA`=>2Ffm^`;h(x z4($c&R3G1Zo&vOT6U@CN z06+PrZbA+0cOzJW2~fygut5hK^cj2KxkI_!2;x>#f=t@qi-zpWOpVTIUMG@O=OmoCn3h zM|Vv--jAaVA`pY)Zm2s5x)6pC-X0%3BSk}?lL(}%Ux-U^K(?J{7HHa2m4t58S4Ssn zD=5xK6txH^T0+QKpf@OIK0-RtYdxZJ$sO11sdyn{Sqs^cRJ5l%`=W%&nlY8n>c$LW z$+9!1U2?@Ibt68Rv1S>GjFg<3Y39xTNK|HGzMvV*r5VMXW@c=SIZVqo^#W(fS_`^8 z%cO#-8#Z%3czB1GF={PZOw^w0c2s0!nh8dpiSxRlF``)_9w>swnilfr9EwmmhdQm# zYnFN?ak;R_#9T%<%m5}ja9Xd>Ey1qfkRm(YhH~ddN5z}`>P>#k>;&7_GaFAT!NiJO z7QXu%S5qsgHv<)a^ou{b5v%xnw*5Ujf#x-3?e;oZzxY1(HukP_J^Z;P@hyD)Iu$An7Ex(Yb%7 literal 0 HcmV?d00001 diff --git a/examples/nested_sequences_flattened.py b/examples/nested_sequences_flattened.py index b95b0a9..68b4b9a 100644 --- a/examples/nested_sequences_flattened.py +++ b/examples/nested_sequences_flattened.py @@ -3,14 +3,15 @@ [1, [2], [[3, "string", [5, 6]], 7], 8] to this [1, 2, 3, "string", 5, 6, 7, 8] It is recursive generator """ -from collections import Iterable +from collections.abc import Iterable def nested_sequence_flattener(nested_sequence: list | tuple, ignored: tuple=(str,bytes)): for item in nested_sequence: """we check if item is another iterable sequence on inside parent, but only tuple or list because string is also an iterable but we do not want it to be flattened (but it is possible)""" if isinstance(item, Iterable) and not isinstance(item, ignored): yield from nested_sequence_flattener(item, ignored) - yield item + else: + yield item if __name__ == "__main__": diff --git a/examples/port_check.py b/examples/port_check.py index 828bb0c..dd8298b 100644 --- a/examples/port_check.py +++ b/examples/port_check.py @@ -3,7 +3,7 @@ import socket -def is_open(host, port, timeout=5): +def is_open(host, port, timeout=3): try: with socket.create_connection((host, port), timeout=timeout): return True @@ -11,5 +11,5 @@ def is_open(host, port, timeout=5): return False -for host, port in [("google.com", 80), ("google.com", 81), ("localhost", 22)]: - print(f"{host}:{port} is {'up' if is_open(host, port) else 'down'}") +for host, port in [("github.com", 443), ("github.com", 8080), ("localhost", 22)]: + print(f"{host}:{port} is {'up' if is_open(host, port) else 'down'}", flush=True) diff --git a/examples/snmp_discover.py b/examples/snmp_discover.py deleted file mode 100755 index f54b0db..0000000 --- a/examples/snmp_discover.py +++ /dev/null @@ -1,72 +0,0 @@ -#!/usr/bin/env python3 -#snmp_discover.py - -from processing import Process, Queue, Pool -import time -import subprocess -import sys -from snmp import Snmp - -q = Queue() -oq = Queue() -#ips = IP("10.0.1.0/24") -ips = ["10.0.28.11", "10.0.28.10", "10.0.28.9","10.0.29.100","10.0.28.7"] -num_workers = 10 - -class HostRecord(): - """Record for Hosts""" - def __init__(self, ip=None, mac=None, snmp_response=None): - self.ip = ip - self.mac = mac - self.snmp_response = snmp_response - - def __repr__(self): - return f"[Host Record({self.ip},{self.mac},{self.snmp_response})]" - -def f(i,q,oq): - while True: - time.sleep(.1) - if q.empty(): - sys.exit() - print(f"Process Number: {i} Exit" ) - ip = q.get() - print (f"Process Number: {i}") - ret = subprocess.call(f"ping -c 1 {ip}",shell=True,stdout=open('/dev/null', 'w'),stderr=subprocess.STDOUT) - if ret == 0: - print (f"{ip}: is alive") - oq.put(ip) - else: - print (f"Process Number: {i} didn’t find a response for {ip}") - pass - -def snmp_query(i,out): - while True: - time.sleep(.1) - if out.empty(): - sys.exit() - print (f"Process Number: {i}") - ipaddr = out.get() - s = Snmp() - h = HostRecord() - h.ip = ipaddr - h.snmp_response = s.query() - print (h) - return h - -try: - q.putmany(ips) -finally: - for i in range(num_workers): - p = Process(target=f, args=[i,q,oq]) - p.start() - - for i in range(num_workers): - pp = Process(target=snmp_query, args=[i,oq]) - pp.start() - -print("main process joins on queue") -p.join() -#while not oq.empty(): -# -print("Validated", oq.get()) -print("Main Program finished") \ No newline at end of file diff --git a/examples/sweep.py b/examples/sweep.py index c26712e..978e120 100644 --- a/examples/sweep.py +++ b/examples/sweep.py @@ -1,21 +1,31 @@ #!/usr/bin/env python3 # sweep.py -from concurrent.futures import ThreadPoolExecutor +import ipaddress import socket +import sys +from concurrent.futures import ThreadPoolExecutor def is_open(target): host, port = target try: - with socket.create_connection((host, port), timeout=2): + with socket.create_connection((host, port), timeout=1): return target, True except OSError: return target, False -targets = [(f"10.0.0.{i}", 22) for i in range(1, 255)] +def main(argv): + if len(argv) != 2: + sys.exit(f"usage: python3 {sys.argv[0]} NETWORK PORT e.g. 172.16.0.0/24 22") + network, port = ipaddress.ip_network(argv[0], strict=False), int(argv[1]) + targets = [(str(ip), port) for ip in network.hosts()] + + with ThreadPoolExecutor(max_workers=50) as pool: + for (host, port), up in pool.map(is_open, targets): + if up: + print(f"{host}:{port} open") + -with ThreadPoolExecutor(max_workers=50) as pool: - for (host, port), up in pool.map(is_open, targets): - if up: - print(f"{host}:{port} open") +if __name__ == "__main__": + main(sys.argv[1:]) diff --git a/examples/sys_02.py b/examples/sys_02.py deleted file mode 100755 index d448541..0000000 --- a/examples/sys_02.py +++ /dev/null @@ -1,11 +0,0 @@ -#!/usr/bin/env python3 -# args-02.py -import sys - -# NOTE: [1:] excludes the first item at index 0, i.e script name -argv_len = len(sys.argv[1:]) - -if not argv_len == 2: - sys.exit('invalid number of arguments (expected 2, given: {})'.format(argv_len)) - -print('two arguments are:', sys.argv[1:]) \ No newline at end of file diff --git a/scripts/check_snippets.py b/scripts/check_snippets.py new file mode 100644 index 0000000..58cf3ec --- /dev/null +++ b/scripts/check_snippets.py @@ -0,0 +1,44 @@ +#!/usr/bin/env python3 +"""Run every inline Python snippet in chapters/*.md and report the ones that raise. + +Full scripts (blocks starting with "# name.py") are tested by scripts/test_examples.sh. +Usage: python3 scripts/check_snippets.py +""" +import contextlib, glob, io, json, os, re, sys, tempfile + +root = os.path.abspath(sys.argv[1] if len(sys.argv) > 1 else os.path.join(os.path.dirname(__file__), "..")) +os.chdir(tempfile.mkdtemp()) +open("hosts.csv", "w").write("hostname,ip,role\nweb-01,10.0.0.10,web\nweb-02,10.0.0.11,web\ndb-01,10.0.0.20,\"database, primary\"\n") +json.dump({"hosts": []}, open("inventory.json", "w")) +fails = 0 +for fn in sorted(glob.glob(os.path.join(root, "chapters", "*.md"))): + ns = {"__name__": "snippet"} + for i, block in enumerate(re.findall(r"```python\n(.*?)```", open(fn).read(), re.S)): + if re.match(r"(?:#!.*\n)?# [\w.]+\.py\n", block): + continue # full script, run by test_examples.sh + if ">>>" in block: + code, cur = [], None + for line in block.splitlines(): + if line.startswith(">>> "): + if cur is not None: code.append(cur) + cur = line[4:] + elif line.startswith("..."): + cur += "\n" + line[4:] + if cur is not None: code.append(cur) + stmts = code + else: + stmts = [block] + for st in stmts: + out = io.StringIO() + try: + with contextlib.redirect_stdout(out), contextlib.redirect_stderr(out): + try: + exec(compile(st, "", "single" if ">>>" in block and "\n" not in st.strip() else "exec"), ns) + except SystemExit as e: + print(f"(SystemExit: {e})") + except Exception as e: + fails += 1 + print(f"FAIL {os.path.basename(fn)} block {i}: {st.strip().splitlines()[0][:70]!r}\n -> {type(e).__name__}: {e}") +print(f"\nsnippet failures: {fails}") + +sys.exit(1 if fails else 0) diff --git a/scripts/test_examples.sh b/scripts/test_examples.sh new file mode 100755 index 0000000..8b705cf --- /dev/null +++ b/scripts/test_examples.sh @@ -0,0 +1,66 @@ +#!/usr/bin/env bash +# Run every script in examples/ the way a reader would, and check its exit code. +# Usage: scripts/test_examples.sh (from anywhere inside the repo) +set -u +cd "$(dirname "$0")/../examples" +E=$PWD +T=$(mktemp -d) +trap 'rm -rf "$T"' EXIT +pass=0 +fail=0 + +# expect RC COMMAND... runs COMMAND in a scratch dir and checks its exit code +expect() { + local want=$1; shift + local out rc + out=$(cd "$T" && timeout 30 "$@" 2>&1 < /dev/null); rc=$? + if [ "$rc" -eq "$want" ]; then + pass=$((pass + 1)); echo "ok rc=$rc $*" + else + fail=$((fail + 1)); echo "FAIL rc=$rc (want $want) $*"; echo "$out" | head -15 | sed 's/^/ | /' + fi +} + +echo "python: $(python3 --version)" +for f in *.py ../*.py; do python3 -m py_compile "$f" || fail=$((fail + 1)); done + +expect 0 bash -c "printf 'alice\nline1\nline2\n' | python3 '$E/stdio.py'" +expect 0 bash -c "echo hello sysadmin | python3 '$E/upper.py'" +expect 0 python3 "$E/working_with_files_01.py" +expect 0 bash -c "cat /etc/passwd | python3 '$E/line_count.py'" +expect 0 python3 "$E/line_count.py" /etc/services /etc/passwd /etc/hosts +expect 0 python3 "$E/argv_01.py" 1 2 3 +expect 1 python3 "$E/argv_02.py" 1 +expect 0 python3 "$E/argv_02.py" 1 2 +expect 0 bash -c "cat /etc/passwd | python3 '$E/grep.py' root" +expect 1 python3 "$E/grep.py" +expect 0 python3 "$E/filesizes.py" /etc +expect 0 python3 "$E/sys_01.py" +expect 0 python3 "$E/disk_alert.py" / +mkdir -p "$T/bk"; touch -d '10 days ago' "$T/bk/old.tar.gz"; touch "$T/bk/new.tar.gz" +expect 0 python3 "$E/prune_backups.py" bk +if [ -e "$T/bk/old.tar.gz" ] || [ ! -e "$T/bk/new.tar.gz" ]; then fail=$((fail + 1)); echo "FAIL prune_backups.py deleted the wrong files"; fi +expect 1 python3 "$E/check_call.py" +expect 0 python3 "$E/capture_output.py" +expect 0 python3 "$E/app.py" 1 2 3 4 --sum +expect 2 python3 "$E/app.py" one +expect 0 python3 "$E/tcp_port_checker.py" github.com -p 443 -t 3 +expect 1 python3 "$E/tcp_port_checker.py" github.com -p 443 8080 -t 2 +expect 0 python3 "$E/github_stars.py" +expect 0 python3 "$E/users_to_csv.py" +expect 0 python3 "$E/backup_log.py" /srv/data ok +expect 0 python3 "$E/backup_log.py" /srv/x fail +expect 0 python3 "$E/port_check.py" +expect 0 python3 "$E/sweep.py" 127.0.0.1/32 1 +expect 1 python3 "$E/sweep.py" +expect 0 python3 "$E/nested_sequences_flattened.py" +expect 0 python3 "$E/Monitoring Disk Space and Sending Alerts.py" +expect 0 python3 "$E/Automating_System_Tasks_with_subprocess.py" +expect 0 python3 "$E/Multi-threading.py" +expect 0 python3 "$E/../Network_Monitoring_and_Utilities.py" +if command -v ping > /dev/null; then expect 0 python3 "$E/follow.py"; fi +if docker info > /dev/null 2>&1; then expect 0 python3 "$E/stopped_containers.py"; else echo "skip stopped_containers.py (no docker)"; fi + +echo +echo "passed: $pass failed: $fail" +[ "$fail" -eq 0 ] From 13d69ce9ec2a50ddfd24c326ec6d08ead42daa4f Mon Sep 17 00:00:00 2001 From: Puru <5674762+tuladhar@users.noreply.github.com> Date: Fri, 20 Nov 2026 16:25:50 +0545 Subject: [PATCH 3/3] Archive a user-readable directory in the shutil example /etc/ssh contains root-only host keys, so make_archive raised PermissionError for normal users (caught by testing in the playground). Co-Authored-By: Claude Opus 5.5 --- chapters/07-shutil-and-glob.md | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/chapters/07-shutil-and-glob.md b/chapters/07-shutil-and-glob.md index 04a10a6..9f78e45 100644 --- a/chapters/07-shutil-and-glob.md +++ b/chapters/07-shutil-and-glob.md @@ -31,10 +31,12 @@ Two modules replace most of the file-shuffling you do with `cp`, `mv`, `rm -r`, >>> total, used, free = shutil.disk_usage("/") >>> f"{used / total:.0%} used" '63% used' ->>> shutil.make_archive("/tmp/etc-backup", "gztar", "/etc/ssh") -'/tmp/etc-backup.tar.gz' +>>> shutil.make_archive("/tmp/home-backup", "gztar", ".") # archive the current directory +'/tmp/home-backup.tar.gz' ``` +> Copying or archiving system directories like `/etc/ssh` raises `PermissionError` as a normal user, because some files (such as SSH host keys) are readable only by root. Run the script with `sudo`, or catch the error and skip those files. + ## Example: alert when the disk is almost full ```python