基本的なLinuxシステム管理およびネットワークタスクにPythonを利用する方法
Pythonは、Linuxシステムでのシステム管理タスクを自動化するための優れたプログラミング言語です。さまざまなライブラリが豊富に用意されているため、それらの多くを使用してさまざまなタスクの効率を向上させることができます。以下の例を使用すると、Linuxシステムコマンドを簡単に実行し、ファイルとディレクトリを操作し、ネットワークタスクを実行し、認証プロセスをわずか数秒で自動化できます。
Pythonとは何ですか?
Pythonは、汎用プログラミング言語として最もよく説明できます。 1980年代後半から1990年代初頭にかけて、オランダのコンピューター科学者Guido van Rossumによって開発され、動的に型付けされたプログラミング言語であり、「ABC」プログラミング言語の後継言語となっています。
今日では、世界で最も人気のあるプログラミング言語の1つと広く見なされており、Web開発のあらゆるものから複雑な数学や科学計算まで、さまざまなユースケースがあります。また、そのエレガントな構文と比較的習得しやすいことも高く評価されています。
LinuxへのPythonのインストール
多くのLinuxディストリビューションには、デフォルトでPythonがすでにインストールされています。システムにPython3がインストールされているかどうかを確認するには、python3を実行します。 --versionを使用したコマンド フラグ:
python3 --version
Pythonがインストールされている場合、コマンドはPython構成のバージョンを表示します。
UbuntuおよびDebianシステムにPythonをインストールするには:
sudo apt update && sudo apt upgrade -y sudo apt install python3.10
または、Pythonを「.tgz」または「.xz」ファイルとしてダウンロードすることもできます。
Linuxシステム管理者に最適なPythonライブラリの1つは、「os」モジュールです。ディレクトリやファイルの処理など、さまざまな種類のタスクの自動化に使用できます。システムコマンドを実行することもできます。
例として、モジュールを利用して新しいディレクトリを作成できます。
#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")
モジュールを使用してディレクトリを削除することもできます:
#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")
ファイルとディレクトリの名前を変更できます:
#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")
モジュールを使用してファイルを簡単に削除できます:
#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")
現在の作業ディレクトリは簡単に印刷できます:
#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")
ファイルやサブディレクトリなどのディレクトリの内容は、簡単に確認できます。
#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")
モジュールを使用して、現在のユーザーを印刷します:
#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") また、モジュールを使用してLinuxシェルコマンドを実行します:
#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")
Pythonには、さまざまなネットワークタスクを実行し、ポートスキャナーやビデオゲームサーバーなどの複雑なネットワーク関連のユーティリティを作成するために構築されたモジュールがあります。 「ソケット」モジュールを使用して、システムで一般的で基本的なネットワークタスクを実行することもできます。
たとえば、システムのIPアドレスとホスト名を確認できます。
#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") このモジュールを使用して、WebサイトのIPアドレスを確認することもできます。
#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") SSHサーバーへのログインとコマンドの実行にParamikoを使用する
SSHサーバーのセットアップにログインしてそこでコマンドを実行するプロセスを自動化したい場合は、「Paramiko」Pythonライブラリが非常に役立ちます。
まず、Pythonのpip3を使用してライブラリをダウンロードします パッケージマネージャー:
pip3 install paramiko
モジュールを使用してSSHサーバーにログインし、コマンドを実行します。
#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") 1。これらのモジュールとライブラリを使用するにはPython3が必要ですか?
これらのライブラリとモジュールのほとんどはPython2で動作しますが、構文に違いがあり、これらのコードスニペットは実行されません。いくつかの変更を加えると、Python 2で実行するように調整できます。ただし、Python 2は古くなっているため、Python3を使用する必要があります。
2。 「os」モジュールと「socket」モジュールをインストールする必要がありますか?
一般的にはありません。 Pythonのほとんどのインストールには、これらのモジュールがすぐに付属しています。
3。 Paramikoを使用してUnix以外のシステムにログインできますか?
Paramikoの開発者によると、現時点では、ライブラリを使用してSSHを使用する非Unixシステムにログインすることはできません。
-
Windows 11 のシステムの復元:方法と対象
Windows Millenium Edition 以降のすべての以前のバージョンの Microsoft オペレーティング システムと同様に、2021 年の Windows 11 には、最後に実行可能なシステム状態を復元するオプションがあります。 . Windows 10 での復元ポイントの作成に関するチュートリアルを既に公開しています。この記事では、Windows 11 でこの機能を有効にするための短いが重要なマニュアルを提供します。 、自動モードで使用し、復元ポイントを手動で設定し、復元を行います。 なぜシステムの復元が必要なのですか? システム ロールバック オプションの存在を過大評価
-
Windows 10 でシステムの復元を有効にして使用する方法
Microsoft は、理由もなく PC で問題が発生する可能性があることを認識しているため、Windows 10 にシステムの復元と呼ばれる機能を追加しました。起動しません。これが、システムの復元が登場するときです。これにより、PC を完全に機能していた時点に復元できます。 次のガイドでは、Windows 10 でシステムの復元を行う方法について説明します。文字どおりに進めば、PC の多くの問題を解決できます。 パート 1:Windows 10 でシステムの復元を有効にする方法 パート 2:Windows 10 でシステムの復元ポイントを作成する方法 パート 3:Windows 10