借助Python工具从数据库读取主机的基本信息(IP、账号、密码),然后验证ssh登录情况,并在主机上执行shell命令查询主机上的操作系统、rpm包等相关信息,将查询结果插入到数据库。
import paramiko
import mysql.connector
import time
db_connection = mysql.connector.connect(
user="admin",
password="password",
host="192.168.87.79",
database="hosts_info"
)
cursor = db_connection.cursor()
cursor.execute('SELECT * FROM host_tmp')
result = cursor.fetchall()
try:
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(hostname=row[0], username=row[1], password=row[2])
print(f"Successfully logged into {row[0]}");
stdin, stdout, stderr = ssh.exec_command("cat /etc/redhat-release")
os_results = stdout.read().decode('utf-8')
stdin, stdout, stderr = ssh.exec_command("hostname")
hostname_results = stdout.read().decode('utf-8')
stdin, stdout, stderr = ssh.exec_command("rpm -qa openssh")
openssh_results = stdout.read().decode('utf-8')
stdin, stdout, stderr = ssh.exec_command("rpm -qa openssl")
openssl_results = stdout.read().decode('utf-8')
stdin, stdout, stderr = ssh.exec_command("rpm -qa ntp")
ntp_results = stdout.read().decode('utf-8')
time1 = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
sql = "INSERT INTO host_info (ip,is_reachable,is_login,os,hostname,username,password,openssh,openssl,ntp,time) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)"
val = (row[0],'1','1',os_results,hostname_results,row[1],row[2],openssh_results,openssl_results,ntp_results,time1)
cursor.execute(sql, val)
ssh.close()
except paramiko.AuthenticationException:
print(f"Failed to log into {row[0]}")
except Exception as e:
print(f"Error connecting to {row[0]}: {e}")
db_connection.commit()
cursor.close()
db_connection.close()