Skip to content

Utiliser Python pour l'administration système

1. Built-in functions

1.1 Python open function

1.1.1 Open a file

See
- official doc
- Official tutorial

1.1.2 Manipulate file object

See
- official tutorial

2. Default Librairies

2.1 sys

2.1.1 Introduction

sys library gives us some infos about the system we are working on.

Import it in your code with import sys

2.1.2 Usage

function result
sys.getwindowsversion()  Return a named tuple describing the Windows version currently running.
sys.modules¶ a dictionary that maps module names to modules which have already been loaded.
sys.platform a platform identifier ( aix | linux | win32 | cygwin | darwin)
sys.stdout stdout
sys.stdin stdin
sys.stderr interpreter’s own prompts and its error messages
sys.version¶ version number of the Python interpreter

2.1.3 Ressources for sys lib

See
- official doc

2.2 platform

Access to underlying platform’s identifying data

2.2.1 Usage

function result
platform.machine() Returns the machine type, e.g. i386
platform.processor() Returns the (real) processor name, e.g. amdk6
platform.release() Returns the system’s release, e.g. 2.2.0 or NT
platform.system() Returns the system/OS name, such as Linux, Darwin, Java, Windows
platform.win32_ver() return a tuple (release, version, csd, ptype) referring to OS release, version number, CSD level (service pack) and OS type (multi/single processor)
platform.mac_ver() Get Mac OS version information and return it as tuple (release, versioninfo, machine)
platform.linux_distribution() Tries to determine the name of the Linux OS distribution name.

2.2.2 Ressources for platform lib

See
- official doc

2.3 os

2.3.1 Import os lib

import os

2.3.2 Unix-like commands

unix python
ls os.listdir
rmdir os.rmdir
mkdir os.mkdir
rm os.remove
chmod os.chmod
chown os.chown
cd os.chdir
pwd os.getcwd
uname os.uname
mv os.replace
ln -s os.symlink
kill os.kill
wait os.wait

2.3.3 Scan a dir

2.3.3.1 Example
with os.scandir(path) as it:
    for entry in it:
        if not entry.name.startswith('.') and entry.is_file():
            print(entry.name)
2.3.3.2 Doc

See
- official doc

2.3.4 Doc for os lib

See
- official doc

2.4 os.path

2.4.1 Import os.path lib

import os

2.4.2 Usage

syntax résultat
os.path.basename(path) Renvoie le nom de base du chemin d'accès path.
os.path.dirname(path) Return the directory name of pathname path.
os.path.isfile(path) Return true if path is an existing regular file `
os.path.isdir(path) Return true if path is an existing directory `
os.path.islink(path) Return true if path is asymbolinc link reffering to an existing directory `
os.path.ismount(path) Return true if path is a mountpoint `
os.path.join(path, *paths) Join one or more path components intelligently.
os.path.split(path) Split the pathname path into a pair, (head, tail)

2.4.3 Doc for os.path lib

See
- official doc

2.5 shutils

shutils offers high-level operations on files.

2.5.1 Usage

unix python
cp shutils.copy
cp -R shutils.copytree
rm -R shutils.rmtree
mv shutils.move
df shutils.disk_usage

2.5.2 Doc for shutils lib

See
- official doc

2.6 Rechercher un fichier

2.6.1 Avec fnmatch

2.6.1.1 Exemple
import fnmatch
import os

for file in os.listdir('.'):
    if fnmatch.fnmatch(file, '*.txt'):
        print(file)
2.6.1.2 Ressources

See:
- official doc

2.6.2 Avec glob

2.6.2.1 Example
>>> os.listdir(".")
['main.py', '.git', 'debian.py', 'README.md']
>>> 
>>> glob.glob('*.py')
['main.py', 'debian.py']
2.6.2.2 Ressources

See:
- official doc

2.7 Gérer les processus

2.7.1 Utilisation de subprocess

>>> import subprocess as sub
>>> a = sub.run(['ls', '-l'],capture_output=True,text=True)
>>> print(a.stdout)
total 8
-rw-r--r-- 1 makayabou makayabou  0 nov.   5 01:54 debian.py
-rw-r--r-- 1 makayabou makayabou 34 nov.   4 20:47 main.py
-rw-r--r-- 1 makayabou makayabou 79 nov.   4 19:46 README.md

>>> print(a.returncode)
0

2.7.2 Utilisation de shlex

To avoid bash injection, it's good to use shlex to pass shell commands in a python script.

>>> import shlex
>>> 
>>> command = "grep -irn python ."
>>> 
>>> split_command = shlex.split(command)
>>> 
>>> print(split_command)
['grep', '-irn', 'python', '.']
>>> 
>>> sub.run(split_command)

2.7.3 Ressources

See:
- official doc for subprocess
- official doc for shlex

2.8 Network library: socket

2.8.1 Usage

command result
socket.getfqdn([name]) Return a fully qualified domain name for name.
socket.gethostbyname(hostname) Translate a host name to IPv4 address format.
socket.gethostbyname_ex(hostname) Translate a host name to IPv4 address format, extended interface.
socket.gethostname() Return a string containing the hostname of the machine where the Python interpreter is currently executing.
socket.gethostbyaddr(ip_address) Return a triple (hostname, aliaslist, ipaddrlist)
socket.bind(address) Bind the socket to address.
socket.connect(address) Connect to a remote socket at address.

2.8.2 Ressources

See:
- official doc for socket

2.9 Créer une TUI

Les TUI (Text User Interface) sont des interfaces en ligne de commande, qui permettent de proposer un dialogue clair avec l'utilisateur.

On utilisera la librairie curses, équivalent de ncurses en bash.

2.9.1 Installation

import curses

2.9.2 Ressources

See:
- official doc for curses
- official how-to for curses
- a tutorial on devdungeon.com

3. Other modules to go further

PsUtil

psutil (process and system utilities) is a cross-platform library for retrieving information on running processes and system utilization (CPU, memory, disks, network, sensors.

pip install psutil

3.2 PsDash

psdash is a system information web dashboard for linux using data mainly served by psutil

pip install psdash

3.3 Remote Resources MaNaGeMeNT

Remote Resources MaNaGeMeNT (rrmngmt) helps you manage remote machines and services running on that. It is targeted to Linux based machines. All is done via SSH connection, that means SSH server must be running there already.

pip install python-rrmngmnt