当前位置: 首页 > news >正文

python自动化运维 通过paramiko库和time库实现服务器自动化管理

目录

一.前言 

二. 代码实现以及解析 

2.1导入必要的库 

2.2定义服务器信息 

2.3创建 SSH 客户端连接函数 

2.4执行远程命令函数 

2.5获取系统信息函数 

2.6重启服务函数

2.7 主函数

三.致谢


一.前言 

在数字化时代,IT 基础设施的规模和复杂性不断增长,传统的手动管理方法已不再适用。自动化运维,作为 IT 运维管理的新范式,正变得越来越重要。它不仅能够显著提升运维效率,降低人为错误,还能确保业务连续性和系统的高可用性。

Python,以其简洁的语法和强大的功能,成为自动化运维的优选语言。借助 Python,我们可以快速开发出灵活且强大的自动化脚本,以应对各种运维场景。

在本文中,我们将探讨如何使用 Python 的 paramiko 库来实现 SSH 连接和远程命令执行,以及如何利用 time 库来处理时间相关操作,从而实现服务器的自动化管理。这些库的结合使用将使我们能够编写出功能丰富、健壮且易于维护的自动化脚本。


 


二. 代码实现以及解析 

import paramiko
import time# 定义服务器信息
hostname = 'your_server_hostname_or_ip'
port = 22
username = 'your_username'
password = 'your_password'# 创建 SSH 客户端连接
def connect_to_server():ssh_client = paramiko.SSHClient()ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())try:ssh_client.connect(hostname, port, username, password)print(f"Connected to {hostname} successfully.")return ssh_clientexcept Exception as e:print(f"Error connecting to {hostname}: {str(e)}")return None# 执行远程命令
def run_command(ssh_client, command):stdin, stdout, stderr = ssh_client.exec_command(command)output = stdout.read().decode('utf-8')error = stderr.read().decode('utf-8')if error:print(f"Error executing command '{command}': {error.strip()}")else:print(f"Command '{command}' executed successfully. Output:\n{output.strip()}")# 获取系统信息示例
def get_system_info(ssh_client):run_command(ssh_client, 'uname -a')run_command(ssh_client, 'df -h')run_command(ssh_client, 'free -m')# 重启服务示例
def restart_service(ssh_client, service_name):run_command(ssh_client, f'sudo systemctl restart {service_name}')time.sleep(5)  # 等待一段时间以确保服务重启完成run_command(ssh_client, f'sudo systemctl status {service_name}')# 主函数
def main():ssh_client = connect_to_server()if ssh_client:get_system_info(ssh_client)restart_service(ssh_client, 'apache2')  # 以 Apache2 为例,可以根据需要替换成你的服务名ssh_client.close()print("Script execution completed.")else:print("Exiting script due to connection error.")if __name__ == "__main__":main()

2.1导入必要的库 
 
import paramiko
import time
  • paramiko 是一个用于 SSH2 协议的 Python 库,用于远程操作服务器。
  • time 是 Python 标准库,用于在执行操作之间添加延迟,如等待服务重启完成。

 


2.2定义服务器信息 
 
hostname = 'your_server_hostname_or_ip'
port = 22
username = 'your_username'
password = 'your_password'
  • 这些变量包括远程服务器的主机名(或IP地址)、SSH端口号、登录用户名和密码。实际应用中,密码应该通过安全的方式进行管理,如使用环境变量或密钥认证。
     
2.3创建 SSH 客户端连接函数 

 
def connect_to_server():ssh_client = paramiko.SSHClient()ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())try:ssh_client.connect(hostname, port, username, password)print(f"Connected to {hostname} successfully.")return ssh_clientexcept Exception as e:print(f"Error connecting to {hostname}: {str(e)}")return None
  • connect_to_server() 函数通过 paramiko.SSHClient() 创建一个 SSH 客户端对象。
  • set_missing_host_key_policy(paramiko.AutoAddPolicy()) 设置自动添加新主机密钥的策略,适用于首次连接服务器时。
  • ssh_client.connect() 方法尝试连接远程服务器,并打印连接成功或失败的信息。

 

2.4执行远程命令函数 

 
def run_command(ssh_client, command):stdin, stdout, stderr = ssh_client.exec_command(command)output = stdout.read().decode('utf-8')error = stderr.read().decode('utf-8')if error:print(f"Error executing command '{command}': {error.strip()}")else:print(f"Command '{command}' executed successfully. Output:\n{output.strip()}")
  • run_command() 函数接收一个 SSH 客户端对象 ssh_client 和要执行的命令 command
  • 使用 exec_command() 方法在远程服务器上执行命令,并获取标准输入、输出和错误流。
  • 输出结果进行解码(通常为UTF-8),并根据执行情况打印成功或失败的信息。

 

2.5获取系统信息函数 
def get_system_info(ssh_client):run_command(ssh_client, 'uname -a')run_command(ssh_client, 'df -h')run_command(ssh_client, 'free -m')
  • get_system_info() 函数调用 run_command() 函数来获取系统信息:
    • uname -a:获取操作系统的详细信息。
    • df -h:获取磁盘空间使用情况。
    • free -m:获取内存使用情况。
2.6重启服务函数
def restart_service(ssh_client, service_name):run_command(ssh_client, f'sudo systemctl restart {service_name}')time.sleep(5)  # 等待一段时间以确保服务重启完成run_command(ssh_client, f'sudo systemctl status {service_name}')

 

  • restart_service() 函数接收一个服务名 service_name,使用 sudo systemctl 命令重启指定的服务,并检查服务状态以确认是否重启成功。
     
2.7 主函数
 
def main():ssh_client = connect_to_server()if ssh_client:get_system_info(ssh_client)restart_service(ssh_client, 'apache2')  # 以 Apache2 为例,可以根据需要替换成你的服务名ssh_client.close()print("Script execution completed.")else:print("Exiting script due to connection error.")if __name__ == "__main__":main()
  • main() 函数是脚本的入口点。
  • 在 main() 函数中,首先调用 connect_to_server() 连接到远程服务器。
  • 如果连接成功,则依次调用 get_system_info() 和 restart_service() 函数来执行任务。
  • 最后关闭 SSH 连接并打印执行完成的信息;如果连接失败,则打印连接错误信息并退出脚本。



     

三.致谢
 

非常感谢您阅读我的博客!如果您有任何问题、建议或想了解特定主题,请随时告诉我。您的反馈对我非常重要,我将继续努力提供高质量的内容。

如果您喜欢我的博客,请考虑订阅我们的更新,这样您就不会错过任何新的文章和信息。同时,欢迎您分享我们的博客给更多的朋友和同事,让更多人受益。

再次感谢您的支持和关注!如果您有任何想法或需求,请随时与我们联系。祝您生活愉快,学习进步!

http://www.lryc.cn/news/406852.html

相关文章:

  • HTML常用的转义字符——怎么在网页中写“<div></div>”?
  • shell-awk文本处理工具
  • 如何在测试中保护用户隐私!
  • ARCGIS PRO DSK GraphicsLayer创建文本要素
  • 看板项目之vue代码分析
  • lua 游戏架构 之 游戏 AI (七)ai_dead
  • 前端开发知识(一)-html
  • 身份证如何查验真伪?C#身份证二要素、三要素接口集成
  • C++ | Leetcode C++题解之第290题单词规律
  • Pytorch使用教学7-张量的广播
  • 生成式AI:对话系统(Chat)与自主代理(Agent)的和谐共舞
  • 唯众物联网(IOT)全功能综合实训教学解决方案
  • 24证券从业考试报名『个人信息表』填写模板❗
  • 深度学习系列70:模型部署torchserve
  • 算法日记day 20(中序后序遍历序列构造二叉树|最大、合并、搜索二叉树)
  • 【科研】# Taylor Francis 论文 LaTeX template模版 及 Word模版
  • Linux网络配置及常见命令!
  • linux之shell脚本实战
  • 文件上传漏洞(ctfshow web151-161)
  • 小猪佩奇.js
  • 人工智能AI合集:Ollama部署对话语言大模型-网页访问
  • CentOS搭建Apache服务器
  • CDGA|数据治理:安全如何贯穿数据供给、流通、使用全过程
  • 32单片机bootloader程序
  • MongoDB - 数组更新操作符:$、$[]、$pop、$pull、$push、$each、$sort、$slice、$position
  • 多GPU并行处理[任务分配、进程调度、资源管理、负载均衡]
  • 项目部署到服务器
  • Idea2024 创建Meaven项目没有src文件夹
  • LeetCode 2766.重新放置石块:哈希表
  • 基于STM32的农业大棚温湿度采集控制系统的设计