▼Q
pythonコードを検討しています。
引数でホスト名を与え、そのホスト名でjsonファイル内を検索して、同時に、
そのホストのIDとPWも同様にjsonファイルに記載されているので、それを使用して
paramikoでログインします。そして、「uname -a」か「/etc/redhat-release」で
ログインしたホストのバージョンかわかるように表示します。
具体的には下記のように表示します。
ホスト名:OSバージョン:確認日時
また、jsonファイルの名前は「hostList.json」です。
どのようなコードになりますか。
▼A
以下は、Pythonコードの例です。
このコードは、引数として与えられたホスト名を元に`hostList.json`ファイルを読み取り、
対応するホストのIDとPWを取得し、Paramikoを使用してリモートホストにSSH接続して
指定されたコマンドを実行し、結果を表示します。
```python
import json
import paramiko
from datetime import datetime
def get_host_credentials(host_name):
with open('hostList.json', 'r') as file:
data = json.load(file)
if host_name in data:
return data[host_name]['id'], data[host_name]['pw']
else:
raise ValueError(f"Host {host_name} not found in hostList.json")
def ssh_connect_and_execute(host_name, username, password, command):
try:
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect(host_name, username=username, password=password)
stdin, stdout, stderr = client.exec_command(command)
result = stdout.read().decode('utf-8').strip()
return result
finally:
client.close()
def main(host_name):
try:
username, password = get_host_credentials(host_name)
# Connect to the remote host and execute the command
result = ssh_connect_and_execute(host_name, username, password, 'uname -a')
# Extract OS version information from the result
os_version = result.split('\n')[0]
# Display the information
current_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
print(f"ホスト名: {host_name} / OSバージョン: {os_version} / 確認日時: {current_time}")
except Exception as e:
print(f"エラー: {str(e)}")
if __name__ == "__main__":
host_name_input = input("ホスト名を入力してください: ")
main(host_name_input)
```
このコードは、`paramiko`ライブラリを使用してSSH接続を行います。
また、`get_host_credentials`関数は指定されたホスト名の認証情報を
`hostList.json`から取得します。`ssh_connect_and_execute`関数はSSH接続を確立し、
指定されたコマンドを実行します。
`main`関数はこれらの関数を呼び出して結果を表示します。
[0回]