python自动化运维 通过paramiko库和time库实现服务器自动化管理
创始人
2024-12-22 05:36:10
0

目录

一.前言 

二. 代码实现以及解析 

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_client     except 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_client     except 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 连接并打印执行完成的信息;如果连接失败,则打印连接错误信息并退出脚本。



     

三.致谢
 

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

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

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

相关内容

热门资讯

秒懂百科新众乐是如何购买的/牛... 秒懂百科新众乐是如何购买的/牛牛房卡批发的价格是多少! 微信牛牛房卡客服微信号微信游戏中心打开微信,...
玩家攻略互娱获取房卡教程/金花... 获取房卡教程是一款非常受欢迎的棋牌游戏,咨询房/卡添加微信:113857776许多玩家在游戏中会购买...
分享经验新漫游获得房卡链接渠道... 分享经验新漫游获得房卡链接渠道/牛牛房卡怎么弄!游戏中心打开微信,添加客服【113857776】,进...
玩家攻略新详心房卡领取码/牛牛... 第二也可以在游戏内商城:在游戏界面中找到 “微信金花,斗牛链接房卡”“商城”选项,选择房卡的购买选项...
1分秒分析新上游如何购买房卡/... 如何购买房卡是一款非常受欢迎的棋牌游戏,咨询房/卡添加微信:113857776许多玩家在游戏中会购买...
1分秒分析财神如何买房卡/卡农... 1分秒分析财神如何买房卡/卡农大厅房卡在哪里购买!微信房卡充值 添加房卡批售商:微【11385777...
秒懂普及新长虹哪里买低价获取/... 第二也可以在游戏内商城:在游戏界面中找到 “微信金花,斗牛链接房卡”“商城”选项,选择房卡的购买选项...
实测教程新卡农在哪里买房卡/超... 第二也可以在游戏内商城:在游戏界面中找到 “微信金花,斗牛链接房卡”“商城”选项,选择房卡的购买选项...
分享经验大众互娱房卡充值/皇豪... 分享经验大众互娱房卡充值/皇豪互娱房卡怎么购买!游戏中心打开微信,添加客服【113857776】,进...
秒懂百科圣游有挂吗/牛牛房卡如... 秒懂百科圣游有挂吗/牛牛房卡如何购买!微信房卡充值 添加房卡批售商:微【113857776】复制到微...
一分钟实测分享新鸿狐房卡详细充... 第二也可以在游戏内商城:在游戏界面中找到 “微信金花,斗牛链接房卡”“商城”选项,选择房卡的购买选项...
1分秒分析新财神房卡怎么弄/超... 1分秒分析新财神房卡怎么弄/超稳房卡可以开挂吗!微信房卡充值 添加房卡批售商:微【113857776...
秒懂普及新人海获取房卡教程/天... 来教大家如何使用获取房卡教程房卡充值 添加房卡批售商:微【113857775】复制到微信搜索、直接添...
玩家须知新好游在哪里买房卡/牛... 玩家须知新好游在哪里买房卡/牛牛房卡怎么弄!微信房卡充值 添加房卡批售商:微【113857776】复...
终于发现!微信群炸金花房卡到哪... 微信游戏中心:炸金花房卡,添加微信【71319951】,进入游戏中心或相关小程序,搜索“微信炸金花房...
实测分享新好游获取房卡教程/天... 获取房卡教程是一款非常受欢迎的棋牌游戏,咨询房/卡添加微信:113857776许多玩家在游戏中会购买...
终于发现!拼三张微信链接房卡,... 微信游戏中心:拼三张房卡,添加微信【56001354】,进入游戏中心或相关小程序,搜索“微信拼三张房...
秒懂百科新久情房卡购买/牛牛房... 秒懂百科新久情房卡购买/牛牛房卡批发的价格是多少! 微信牛牛房卡客服微信号微信游戏中心打开微信,添加...
终于发现!微信里上玩拼三张购买... 微信游戏中心:拼三张房卡,添加微信【66336574】,进入游戏中心或相关小程序,搜索“微信拼三张房...
一分钟实测分享九九房卡获取方式... 一分钟实测分享九九房卡获取方式/拼十房卡在哪里购买! 微信牛牛房卡客服微信号微信游戏中心打开微信,添...