Python to świetny język programowania do automatyzacji zadań administracyjnych systemu w systemach Linux. Dzięki szerokiemu wyborowi różnych bibliotek, wiele z nich można wykorzystać do poprawy wydajności różnych zadań. Korzystając z poniższych przykładów, możesz łatwo uruchamiać polecenia systemu Linux, pracować z plikami i katalogami, wykonywać zadania sieciowe i automatyzować procesy uwierzytelniania w ciągu zaledwie kilku sekund.
Co to jest Python?
Python najlepiej można opisać jako język programowania ogólnego przeznaczenia. Został opracowany przez holenderskiego informatyka Guido van Rossuma pod koniec lat 80. i na początku lat 90. jako dynamicznie typowany język programowania i następca języka programowania „ABC”.
Obecnie jest powszechnie uważany za jeden z najpopularniejszych języków programowania na świecie, z przypadkami użycia od dowolnego tworzenia stron internetowych po złożone obliczenia matematyczne i naukowe. Jest również ceniony za elegancką składnię i za to, że jest stosunkowo łatwy do nauczenia.
Instalowanie Pythona w systemie Linux
Wiele dystrybucji Linuksa ma już domyślnie zainstalowanego Pythona. Aby sprawdzić, czy Twój system ma zainstalowany Python 3, czy nie, możesz uruchomić python3
polecenie z --version
flaga:

Jeśli zainstalowano Python, polecenie wyświetli wersję Twojej konfiguracji Pythona.
Aby zainstalować Pythona na systemach Ubuntu i Debian:
sudo apt update && sudo apt upgrade -y sudo apt install python3.10
Alternatywnie, Piton można go również pobrać jako plik „.tgz” lub „.xz”.
Korzystanie z modułu „os”
Jedną z najlepszych bibliotek Pythona dla administratorów systemu Linux jest moduł „os”. Możesz go użyć do zautomatyzowania wielu różnych typów zadań, takich jak obsługa katalogów i plików. Możesz także uruchamiać polecenia systemowe.
Jako przykład możesz użyć modułu do stworzenia nowego katalogu:
#Import the OS module import os #Name of the new directory dir_name = "example" try: #Creates the new directory os.mkdir(dir_name) #Prints the result, if the directory was successfully created print(f"Directory '{dir_name}' created successfully") #Prints the result, in case the directory already exists except FileExistsError: print(f"Directory '{dir_name}' already exists")

Możesz również usunąć katalog za pomocą modułu:
#Import the OS module import os #Name of the directory to be deleted dir_name = "example" try: #Deletes the directory os.rmdir(dir_name) #Prints the result, if the directory was successfully deleted print(f"Directory '{dir_name}' deleted successfully") #Prints the result, if the directory doesn't exist except FileNotFoundError: print(f"Directory '{dir_name}' doesn't exist")

Możesz zmieniać nazwy plików i katalogów:
#Import the OS module import os #Current name of the directory or file current_name = "example" new_name = "example2.0" try: #Renames the directory or file content = os.rename(current_name, new_name) #Prints the contents of the directory print(f"Directory/File '{current_name}' was successfully renamed to '{new_name}'") #Print the error message, if the directory or file doesn't exist except FileNotFoundError: print(f"Directory/File '{current_name}' doesn't exist")

Pliki można łatwo wyodrębnić za pomocą modułu:
#Import the OS module import os #Name of the file to be deleted file_name = "example.txt" try: #Deletes the file os.remove(file_name) #Prints the result, if the file was successfully deleted print(f"File '{file_name}' deleted successfully") #Prints the result, if the file doesn't exist except FileNotFoundError: print(f"File '{file_name}' doesn't exist")

Bieżący katalog roboczy można łatwo wydrukować:
#Import the OS module import os try: #Gets the current working directory cwd = os.getcwd() #The name of the current working directory is printed out print(cwd) #If an error occurs, it is printed out except: print("An error occurred")

Zawartość katalogu, taką jak pliki i podkatalogi, można łatwo sprawdzić:
#Import the OS module import os #Name of the directory dir_name = "example" try: #Gets the contents of the directory content = os.listdir(dir_name) #Prints the contents of the directory print(content) #Prints the error, if the directory doesn't exist except FileNotFoundError: print(f"Directory '{dir_name}' doesn't exist")

Użyj modułu, aby wydrukować bieżącego użytkownika:
#Import the OS module import os try: #Gets the name of the current user user = os.getlogin() #Prints the name of the current user print(user) #Prints an error message, in case it occurs except: print("An error occurred")
Uruchom także polecenia powłoki systemu Linux za pomocą modułu:
#Import the OS module import os #The shell command to run command = "sudo apt update && sudo apt upgrade -y" try: #Runs the system command result = os.system(command) #Prints the result of the command print(result) #Prints an error message, in case an error occurs except: print("An error occurred")

Wykonywanie zadań sieciowych za pomocą modułu „socket”
Python ma moduł przeznaczony do wykonywania różnych zadań sieciowych i tworzenia złożonych narzędzi związanych z siecią, takich jak skanery portów i serwery gier. Nic dziwnego, że moduł „socket” może być również używany do wykonywania podstawowych i typowych zadań sieciowych w twoim systemie.
Możesz na przykład sprawdzić adres IP i nazwę hosta swojego systemu:
#Import the socket module import socket try: #Getting the hostname host = socket.gethostname() #Getting the IP address of the host ip = socket.gethostbyname(host) #Prints the IP address print(f"IP address: {ip}") #Prints the hostname print(f"Hostname: {host}") #Prints an error message, if an error occurs except: print("An error occurred")
Za pomocą modułu możesz również sprawdzić adres IP strony internetowej:
#Import the socket module import socket try: #Domain to be checked domain = "duckduckgo.com" #Getting the IP address of the domain ip = socket.gethostbyname(domain) #Prints the IP address print(f"IP address: {ip}") #Prints an error message, if an error occurs except: print("An error occurred")
Używanie Paramiko do logowania się do serwera SSH i uruchamiania poleceń
Jeśli chcesz zautomatyzować proces logowania do konfiguracji serwera SSH i uruchamiania tam poleceń, niezwykle pomocna będzie biblioteka Pythona „Paramiko”.
Najpierw pobierz bibliotekę za pomocą Pythona pip3
kierownik ds. opakowań:

Użyj modułu, aby zalogować się do serwera SSH i uruchomić polecenia:
#Importing the Paramiko library import paramiko #Specifying the IP and credentials ip = '127.0.0.1' port = 22 user = 'example' password = 'example' command = "uname -a" try: #Initiating the Paramiko client ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) #Connecting to the SSH server ssh.connect(ip, port, user, password) #Running a command on the system stdin, stdout, stderr = ssh.exec_command(command) #Prints the result of the command print(stdout.read().decode()) #Prints an error message, in case an error occurs except: print("An error occurred")
Częste pytania
1. Czy potrzebuję Pythona 3 do korzystania z tych modułów i bibliotek?
Chociaż większość tych bibliotek i modułów współpracuje z Pythonem 2, istnieje różnica w składni i te fragmenty kodu nie będą działać. Po kilku zmianach możesz dostosować je do działania w Pythonie 2. Jednak Python 2 jest przestarzały, więc powinieneś zamiast tego użyć Pythona 3.
2. Czy muszę instalować moduły „os” i „socket”?
Generalnie nie. Większość instalacji Pythona jest dostarczana z tymi modułami po wyjęciu z pudełka.
3. Czy mogę używać Paramiko do logowania się do systemów innych niż Unix?
Według twórcy Paramiko, w tej chwili biblioteka nie może być używana do logowania się do systemów nieuniksowych za pomocą SSH.
Czy ten artykuł jest przydatny?