某公司因为网站服务经常出现异常,需要你开发一个脚本对服务器上的服务进行监控;检测目标服务器上是否存在nginx软件(提供web服务的软件),如果不存在则安装(服务器可能的操作系统Ubuntu24/RedHat9);如果nginx软件存在则检査nginx服务是否启动,如果没有启动则启动该服务(为了确认是否启动成功,需要在自己浏览器中访问服务器ip地址对应的URL是否能看到nginx启动页面)
import paramiko
def execute_remote_command(host, username, password, command):
try:
# 建立远程连接
ssh = paramiko.SSHClient()
# 忽略known_hosts 文件限制
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy)
# 连接服务器
ssh.connect(host, username=username, password=password)
# 执行命令
stdin, stdout, stderr = ssh.exec_command(command)
# 读取命令执行结果
result = stdout.read().decode().strip()
# 关闭连接
ssh.close()
# 返回结果
return result
except Exception as e:
print("出现了异常:", e)
def ensure_nginx_installed(host, username, password):
# 定义在不同操作系统中检查和安装Nginx的命令
commands = {
'Ubuntu24': {
'check': 'dpkg -l | grep nginx',
'install': ['sudo apt update', 'sudo apt install nginx -y']
},
'RedHat9': {
'check': 'rpm -qa | grep nginx',
'install': ['sudo dnf install nginx -y']
}
}
# 使用paramiko连接到远程服务器
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect(host, username=username, password=password)
# 根据操作系统执行相应的命令
for os_name, os_commands in commands.items():
# 检查Nginx是否已安装
stdin, stdout, stderr = client.exec_command(os_commands['check'])
output = stdout.read().decode('utf-8').strip()
error = stderr.read().decode('utf-8').strip()
if output:
print(f"Nginx已经安装于{os_name}系统")
else:
print(f"Nginx没有安装在{os_name}系统. 正在安装...")
# 安装Nginx
for install_command in os_commands['install']:
stdin, stdout, stderr = client.exec_command(install_command)
install_output = stdout.read().decode('utf-8').strip()
install_error = stderr.read().decode('utf-8').strip()
if install_output:
print(f"Installation output on {os_name}: {install_output}")
if install_error:
print(f"Installation error on {os_name}: {install_error}")
# 关闭连接
client.close()
#检测是否安装了Nginx,若未安装则安装
ensure_nginx_installed(
host = '192.168.5.129',
username = 'ys',
password = '123456'
)
#检测是否开启了nginx服务
res =execute_remote_command(
host = '192.168.5.129',
username = 'ys',
password = '123456',
command = 'systemctl status nginx'
)
if res == "inactive":
print("nginx 服务未启动")
# 调用函数启动nginx服务
execute_remote_command(
host="192.168.0.200",
username="root",
password="root",
command="systemctl start nginx"
)
else:
print("nginx web服务检测正常,无需重启")