System information
System information
In the past chapters, we've discussed the basic building block of a (Python) program. While these blocks are integral to a useful script, there is an import part that we've not yet talked about: interacting with the operating system.
A script that is used within a system or network administration context must perforce communicate with the operating system. Reading variables, calling cli-commands, reading entire directories nad moving, copying or duplicating files are all tasks that are commonly required.
In this chapter we'll talk about how to do all of these. Because of the plethora of tools that are available in the standard Python library, this discussion will not be exhaustive. It will, however, contain an overview of the most commonly used methods and functions.
os, sys and platform
The standard library contains three modules that can tell you something about the system your script is running on: os, sys and platform. All of these have a similar but distinct purpose:
oslets the script interact with the operating system: files, folders, environment variables, the working directory, ...sysgives information about, and control over, the Python interpreter that is running the script. You've already used it in chapter 3 to print tosys.stderrand to stop the script withsys.exit().platformonly describes the machine and operating system: which Windows version, which processor, what the hostname is. It can't change anything, it only answers questions.
A simple rule of thumb: use os to do something with the system, sys to do something with Python itself, and platform to report on the system.
| Module | Purpose |
|---|---|
os | Interact with the operating system and retrieve information thereof. |
sys | Interact with the Python interpreter and retrieve information thereof. |
platform | Describe the machine (computer) and OS |
We'll use all of these modules to complete the welcome banner from chapter one.
User information
In chapter 1, we used the input function to ask the user to enter their name, this is of course not something one does in a production environment. We can retrieve the user's name via the getlogin function from the os module. [1]
#!/usr/bin/env python3
import os
# --- Configuration ---
username = os.getlogin()
configuration = {
"SERVER NAME": "CORE-DATABASE-01",
"ENVIRONMENT": "ENVIRONMENT",
"ADMIN CONTACT": "admin@thomasmore.be",
"OPERATING SYSTEM": "PLACEHOLDER",
}
warning_msg = "UNAUTHORIZED ACCESS IS STRICTLY PROHIBITED"
# --- Banner Execution ---
print("=" * 60)
# The ^ operator can be used to center text in an f-string.
# In this case text will be centered within 60 characters.
print(f"{'SYSTEM ACCESS CONTROL':^60}")
print("=" * 60, end="\n\n")
for key, value in configuration.items():
key = key + ':'
print(f"{key:<30}{value}")
print("\n" + "-" * 60)
print(f"{warning_msg:^60}")
print("-" * 60)
print(f"\nWelcome, {username}. Please ensure all changes are logged.")
print("=" * 60)Computer name
The os of the computer is currently hardcoded to "CORE-DATABASE-01", we'll replace this with a call to the node function from the platform module. This function returns the fully qualified domain name where possible and falls back to the machine name or an empty string (in that order).
#!/usr/bin/env python3
import os
import platform
# --- Configuration ---
username = os.getlogin()
configuration = {
"SERVER NAME": platform.node(),
"ENVIRONMENT": "ENVIRONMENT",
"ADMIN CONTACT": "admin@thomasmore.be",
"OPERATING SYSTEM": "PLACEHOLDER",
}
warning_msg = "UNAUTHORIZED ACCESS IS STRICTLY PROHIBITED"
# --- Banner Execution ---
print("=" * 60)
# The ^ operator can be used to center text in an f-string.
# In this case text will be centered within 60 characters.
print(f"{'SYSTEM ACCESS CONTROL':^60}")
print("=" * 60, end="\n\n")
for key, value in configuration.items():
key = key + ':'
print(f"{key:<30}{value}")
print("\n" + "-" * 60)
print(f"{warning_msg:^60}")
print("-" * 60)
print(f"\nWelcome, {username}. Please ensure all changes are logged.")
print("=" * 60)Environment variables
The script is currently hardcoded to say that it is run in a production environment. Typically, this type of information is set using environment variables.
We'll update the script to read the environment variable and default to production is the variable is not set. This can be achieved either through the environ variable or the getenv function from the os module.
We'll opt for getenv since this function allows us to set a default option rather than having to manually check if the variable is present.
#!/usr/bin/env python3
import os
import platform
import sys
# --- Configuration ---
username = os.getlogin()
configuration = {
"SERVER NAME": platform.node(),
"ENVIRONMENT": os.getenv('ENVIRONMENT', default="PRODUCTION"),
"ADMIN CONTACT": "admin@thomasmore.be",
"OPERATING SYSTEM": "PLACEHOLDER",
}
warning_msg = "UNAUTHORIZED ACCESS IS STRICTLY PROHIBITED"
# --- Banner Execution ---
print("=" * 60)
# The ^ operator can be used to center text in an f-string.
# In this case text will be centered within 60 characters.
print(f"{'SYSTEM ACCESS CONTROL':^60}")
print("=" * 60, end="\n\n")
for key, value in configuration.items():
key = key + ':'
print(f"{key:<30}{value}")
print("\n" + "-" * 60)
print(f"{warning_msg:^60}")
print("-" * 60)
print(f"\nWelcome, {username}. Please ensure all changes are logged.")
print("=" * 60)Info
To test the code above, you need to configure the ENVIRONMENT variable. You can do this as follows:
$env:ENVIRONMENT="A Test Value"export ENVIRONMENT="A Test Value"Determining the OS
While Python is cross-platform, not everything you do in the script is. Imagine that the script has to ping some servers and that we do this by calling the external ping program. The command is available on both *nix and Windows systems, but the parameters of the command differ. We must therefore be able to distinguish between operating systems. This can be done either through the os or sys module. The sys module is preferred since the result is more detailed and differentiates between *nix systems such as macOS, Android and Linux, whereas the os module only recognizes posix, nt (Windows) and java.
The sys.platform variable can return the following values (amongst others):
| System | Platform value |
|---|---|
| Android | "android" |
| FreeBSD | "freebsd" |
| iOS | "ios" |
| Linux | "linux" |
| macOS | "darwin" |
| Windows | "win32" |
#!/usr/bin/env python3
import os
import platform
import sys
# --- Configuration ---
username = os.getlogin()
configuration = {
"SERVER NAME": platform.node(),
"ENVIRONMENT": os.getenv('ENVIRONMENT', default="PRODUCTION"),
"ADMIN CONTACT": "admin@thomasmore.be",
"OPERATING SYSTEM": sys.platform,
}
warning_msg = "UNAUTHORIZED ACCESS IS STRICTLY PROHIBITED"
# --- Banner Execution ---
print("=" * 60)
# The ^ operator can be used to center text in an f-string.
# In this case text will be centered within 60 characters.
print(f"{'SYSTEM ACCESS CONTROL':^60}")
print("=" * 60, end="\n\n")
for key, value in configuration.items():
key = key + ':'
print(f"{key:<30}{value}")
print("\n" + "-" * 60)
print(f"{warning_msg:^60}")
print("-" * 60)
print(f"\nWelcome, {username}. Please ensure all changes are logged.")
print("=" * 60)