批量下载nginx服务
·
需求:某公司因为网站服务经常出现异常,需要你开发一个脚本对服务器上的服务进行监控;检测目标服务器上是否存在nginx软件(提供web服务的软件),如果不存在则安装(服务器可能的操作系统Ubuntu24/RedHat9);如果nginx软件存在则检查nginx服务是否启动,如果没有启动则启动该服务(为了确认是否启动成功,需要在自己浏览器中访问服务器ip地址对应的URL:$http://192.168.0.200$ 是否能看到nginx启动页面)
- 提示1:检测服务器操作系统,推荐命令:`uname -a`,从它里面提取关键字检测
- 提示2:unbutn安装命令`apt install 软件名称`,redhat安装命令`yum install 软件名称`
- 提示3:nginx是一个软件,启动之后就会是一个名称为nginx的服务,提供网站服务-启动之后能在80端口访问到一个默认页面`http://192.168.0.200:80`等价于`http://192.168.0.200`,因为`http://`协议默认端口-80端口;需要注意`https://`默认端口-443端口
import paramiko
from logging函数封装 import Logger
logging = Logger('example.log','example_logger')
logging.debug("开始执行脚本")
host = "192.168.80.143"
user = "root"
password = "123"
logging.info(f"主机为:{host}用户为:{user}")
ssh = paramiko.SSHClient()
logging.info("建立连接")
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy)
logging.info("忽略警告")
ssh.connect(host,username=user,password=password)
logging.info(f"建立的远程连接对象:{ssh}")
print("建立的远程连接对象:", ssh)
stdin, stdout, stderr = ssh.exec_command("systemctl is-active nginx")
result = stdout.read().decode().strip()
if result == "inactive":
print("nginx服务没有启动,正在启动中....")
ssh.exec_command("systemctl start nginx")
else:
print("nginx web服务检测..正常")
ssh.close()
import paramiko
# 定义SSH连接的参数
hostname = '192.168.80.143'
username = 'root'
password = '123'
# 创建SSH对象
ssh = paramiko.SSHClient()
# 设置自动添加主机名及主机密钥到本地HostKeys对象
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
# 连接服务器
ssh.connect(hostname, username=username, password=password)
# 执行命令
stdin, stdout, stderr = ssh.exec_command('whoami')
# 获取命令结果
result = stdout.read().decode().strip()
# 打印结果
print('当前用户名:', result)
logging.debug("脚本执行结束")
# 关闭连接
ssh.close()
#logger封装模块
# my_logger.py
import logging
class Logger:
def __init__(self, log_name, logger_name):
self.logger = logging.getLogger(logger_name)
self.logger.setLevel(logging.DEBUG)
# 创建一个handler,用于写入日志文件
fh = logging.FileHandler(log_name)
fh.setLevel(logging.DEBUG)
#
# # 创建一个handler,用于将日志输出到控制台
# ch = logging.StreamHandler()
# ch.setLevel(logging.DEBUG)
# 定义handler的输出格式
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
fh.setFormatter(formatter)
# ch.setFormatter(formatter)
# 给logger添加handler
self.logger.addHandler(fh)
# self.logger.addHandler(ch)
def debug(self, message):
self.logger.debug(message)
def info(self, message):
self.logger.info(message)
def warning(self, message):
self.logger.warning(message)
def error(self, message):
self.logger.error(message)
def critical(self, message):
self.logger.critical(message)
更多推荐




所有评论(0)