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/.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 new file mode 100644 index 0000000..5501bb4 --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,83 @@ +# 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 +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. + +## 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.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. +- 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. + +### 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). + +- 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/__pycache__/Network_Monitoring_and_Utilities.cpython-314.pyc b/__pycache__/Network_Monitoring_and_Utilities.cpython-314.pyc new file mode 100644 index 0000000..1268181 Binary files /dev/null and b/__pycache__/Network_Monitoring_and_Utilities.cpython-314.pyc differ diff --git a/chapters/01-set-up-your-lab.md b/chapters/01-set-up-your-lab.md new file mode 100644 index 0000000..0b545df --- /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.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: + +```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..54e05f1 --- /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. + +```text +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..45b7d0d --- /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, 11): + sys.exit(f"this script needs Python 3.11+, 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..9f78e45 --- /dev/null +++ b/chapters/07-shutil-and-glob.md @@ -0,0 +1,85 @@ +# 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/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 +#!/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..faae12c --- /dev/null +++ b/chapters/09-subprocess.md @@ -0,0 +1,152 @@ +# 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 +import subprocess +import sys + +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(["sort"], input="web-02\nweb-01\n", capture_output=True, text=True) +>>> result.stdout +'web-01\nweb-02\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..7d46207 --- /dev/null +++ b/chapters/10-argparse.md @@ -0,0 +1,165 @@ +# 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 +import argparse + +parser = argparse.ArgumentParser() + +# 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 +import argparse + +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..f79db39 --- /dev/null +++ b/chapters/12-csv.md @@ -0,0 +1,107 @@ +# 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`, e.g. `delimiter="\t"` or `delimiter=";"`: + +```python +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 + +`/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..7878537 --- /dev/null +++ b/chapters/13-sqlite.md @@ -0,0 +1,130 @@ +# 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 +role = "web" + +# 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..a2aeab4 --- /dev/null +++ b/chapters/14-socket.md @@ -0,0 +1,124 @@ +# 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=3): + try: + with socket.create_connection((host, port), timeout=timeout): + return True + except OSError: + return False + + +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 +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 + +```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 +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=1): + return target, True + except OSError: + return target, False + + +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") + + +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. + +## 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/__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 0000000..c8dd247 Binary files /dev/null and b/examples/__pycache__/Automating_System_Tasks_with_subprocess.cpython-314.pyc differ diff --git a/examples/__pycache__/Monitoring Disk Space and Sending Alerts.cpython-314.pyc b/examples/__pycache__/Monitoring Disk Space and Sending Alerts.cpython-314.pyc new file mode 100644 index 0000000..b629838 Binary files /dev/null and b/examples/__pycache__/Monitoring Disk Space and Sending Alerts.cpython-314.pyc differ diff --git a/examples/__pycache__/Multi-threading.cpython-314.pyc b/examples/__pycache__/Multi-threading.cpython-314.pyc new file mode 100644 index 0000000..6251b3d Binary files /dev/null and b/examples/__pycache__/Multi-threading.cpython-314.pyc differ diff --git a/examples/__pycache__/app.cpython-314.pyc b/examples/__pycache__/app.cpython-314.pyc new file mode 100644 index 0000000..c1feb76 Binary files /dev/null and b/examples/__pycache__/app.cpython-314.pyc differ diff --git a/examples/__pycache__/argv_01.cpython-314.pyc b/examples/__pycache__/argv_01.cpython-314.pyc new file mode 100644 index 0000000..14b120a Binary files /dev/null and b/examples/__pycache__/argv_01.cpython-314.pyc differ diff --git a/examples/__pycache__/argv_02.cpython-314.pyc b/examples/__pycache__/argv_02.cpython-314.pyc new file mode 100644 index 0000000..7effb2a Binary files /dev/null and b/examples/__pycache__/argv_02.cpython-314.pyc differ diff --git a/examples/__pycache__/backup_log.cpython-314.pyc b/examples/__pycache__/backup_log.cpython-314.pyc new file mode 100644 index 0000000..ea854fa Binary files /dev/null and b/examples/__pycache__/backup_log.cpython-314.pyc differ diff --git a/examples/__pycache__/capture_output.cpython-314.pyc b/examples/__pycache__/capture_output.cpython-314.pyc new file mode 100644 index 0000000..3a80d12 Binary files /dev/null and b/examples/__pycache__/capture_output.cpython-314.pyc differ diff --git a/examples/__pycache__/check_call.cpython-314.pyc b/examples/__pycache__/check_call.cpython-314.pyc new file mode 100644 index 0000000..00c93ba Binary files /dev/null and b/examples/__pycache__/check_call.cpython-314.pyc differ diff --git a/examples/__pycache__/disk_alert.cpython-314.pyc b/examples/__pycache__/disk_alert.cpython-314.pyc new file mode 100644 index 0000000..7e3c43e Binary files /dev/null and b/examples/__pycache__/disk_alert.cpython-314.pyc differ diff --git a/examples/__pycache__/filesizes.cpython-314.pyc b/examples/__pycache__/filesizes.cpython-314.pyc new file mode 100644 index 0000000..69b01c6 Binary files /dev/null and b/examples/__pycache__/filesizes.cpython-314.pyc differ diff --git a/examples/__pycache__/follow.cpython-314.pyc b/examples/__pycache__/follow.cpython-314.pyc new file mode 100644 index 0000000..cd3d618 Binary files /dev/null and b/examples/__pycache__/follow.cpython-314.pyc differ diff --git a/examples/__pycache__/github_stars.cpython-314.pyc b/examples/__pycache__/github_stars.cpython-314.pyc new file mode 100644 index 0000000..7ddd143 Binary files /dev/null and b/examples/__pycache__/github_stars.cpython-314.pyc differ diff --git a/examples/__pycache__/grep.cpython-314.pyc b/examples/__pycache__/grep.cpython-314.pyc new file mode 100644 index 0000000..276fd9a Binary files /dev/null and b/examples/__pycache__/grep.cpython-314.pyc differ diff --git a/examples/__pycache__/line_count.cpython-314.pyc b/examples/__pycache__/line_count.cpython-314.pyc new file mode 100644 index 0000000..a88fadc Binary files /dev/null and b/examples/__pycache__/line_count.cpython-314.pyc differ diff --git a/examples/__pycache__/nested_sequences_flattened.cpython-314.pyc b/examples/__pycache__/nested_sequences_flattened.cpython-314.pyc new file mode 100644 index 0000000..3d2a1cc Binary files /dev/null and b/examples/__pycache__/nested_sequences_flattened.cpython-314.pyc differ diff --git a/examples/__pycache__/port_check.cpython-314.pyc b/examples/__pycache__/port_check.cpython-314.pyc new file mode 100644 index 0000000..4424f4f Binary files /dev/null and b/examples/__pycache__/port_check.cpython-314.pyc differ diff --git a/examples/__pycache__/prune_backups.cpython-314.pyc b/examples/__pycache__/prune_backups.cpython-314.pyc new file mode 100644 index 0000000..291b517 Binary files /dev/null and b/examples/__pycache__/prune_backups.cpython-314.pyc differ diff --git a/examples/__pycache__/stdio.cpython-314.pyc b/examples/__pycache__/stdio.cpython-314.pyc new file mode 100644 index 0000000..0ef7dc0 Binary files /dev/null and b/examples/__pycache__/stdio.cpython-314.pyc differ diff --git a/examples/__pycache__/stopped_containers.cpython-314.pyc b/examples/__pycache__/stopped_containers.cpython-314.pyc new file mode 100644 index 0000000..3993946 Binary files /dev/null and b/examples/__pycache__/stopped_containers.cpython-314.pyc differ diff --git a/examples/__pycache__/sweep.cpython-314.pyc b/examples/__pycache__/sweep.cpython-314.pyc new file mode 100644 index 0000000..17c0f77 Binary files /dev/null and b/examples/__pycache__/sweep.cpython-314.pyc differ diff --git a/examples/__pycache__/sys_01.cpython-314.pyc b/examples/__pycache__/sys_01.cpython-314.pyc new file mode 100644 index 0000000..4648039 Binary files /dev/null and b/examples/__pycache__/sys_01.cpython-314.pyc differ 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 0000000..386d16c Binary files /dev/null and b/examples/__pycache__/tcp_port_checker.cpython-314.pyc differ diff --git a/examples/__pycache__/upper.cpython-314.pyc b/examples/__pycache__/upper.cpython-314.pyc new file mode 100644 index 0000000..f6543b0 Binary files /dev/null and b/examples/__pycache__/upper.cpython-314.pyc differ 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 0000000..4f96052 Binary files /dev/null and b/examples/__pycache__/users_to_csv.cpython-314.pyc differ diff --git a/examples/__pycache__/working_with_files_01.cpython-314.pyc b/examples/__pycache__/working_with_files_01.cpython-314.pyc new file mode 100644 index 0000000..361c800 Binary files /dev/null and b/examples/__pycache__/working_with_files_01.cpython-314.pyc differ 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/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/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..dd8298b --- /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=3): + try: + with socket.create_connection((host, port), timeout=timeout): + return True + except OSError: + return False + + +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/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/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/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..978e120 --- /dev/null +++ b/examples/sweep.py @@ -0,0 +1,31 @@ +#!/usr/bin/env python3 +# sweep.py +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=1): + return target, True + except OSError: + return target, False + + +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") + + +if __name__ == "__main__": + main(sys.argv[1:]) 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/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/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() 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 ]