51工具盒子

依楼听风雨
笑看云卷云舒,淡观潮起潮落

利用Python脚本登录服务器并执行命令:进阶实践指南

在之前的文章中,我们介绍了如何使用Paramiko模块建立SSH连接,执行远程命令以及进行文件传输。本文将进一步探讨如何优化现有脚本,引入更多功能和模块,以提升远程服务器操作的效率和灵活性。

优化巡检脚本

读取执行结果保存本地

通过 stdout.read().decode()结合 with open将执行结果读取并保存到指定文本文件。代码如下:
* * * *

output = stdout.read().decode()local_file_path = r'C:\Users\ralap\Desktop\Python\服务器巡检结果.txt'  #原始字符串字面值 r'',这样可以确保路径中的反斜杠 \ 不被转义,从而避免出现意外的错误with open(local_file_path, 'w') as file: #使用 with 语句打开本地文件 local_file_path,以写入模式 'w' 打开文件,并将文件对象赋给 file 变量    file.write(output)   #在打开的本地文件中,使用 write() 方法将从远程服务器获取的输出内容 output 写入文件中

增加时间戳

在现有脚本的基础上,我们可以添加时间戳功能,记录每次巡检的时间,方便后续对比和分析。代码如下:
* * * * * *

import datetimecurrent_time = datetime.datetime.now()timestamp = current_time.strftime("%Y-%m-%d-%H-%M-%S")save_path = r'C:\Users\ralap\Desktop\Python\服务器巡检结果-' + timestamp + '.txt'with open(save_path, 'w') as file:    file.write(output)

增加登录判断

在连接服务器的部分,我们可以增加登录判断,以处理可能出现的身份验证错误或连接异常。代码如下:
* * * * * * * * * * * * *

import sys  ##引入内置模块sys,提供与 Python 解释器及其环境交互的功能try:   ##try-except 是 Python 中的异常处理结构,try 用于包裹可能引发异常的代码块,except 用于捕获并处理这些异常,确保程序在出现问题时不会崩溃。    client.connect(hostname, username=username, password=password, port=port)    print("登录成功!")except paramiko.AuthenticationException as auth_exception:    print("认证失败: 身份验证错误,请检查用户名和密码是否正确。")    sys.exit(1) #sys.exit(1) 表示以状态码 1 退出程序,0为正常退出except paramiko.SSHException as ssh_exception:    print(f"SSH连接错误: {ssh_exception}")    sys.exit(1)except Exception as error:  ##未预见异常输出    print(f"发生异常: {error}")    sys.exit(1)

整体代码

整体如下所示: * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *

import paramikoimport sysimport datetime# 填写远程服务器的IP地址、用户名和密码hostname = '172.16.5.223'username = 'root'password = '12345'port = 22
# 创建SSH客户端client = paramiko.SSHClient()client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
#登录状态检测try:    client.connect(hostname, username=username, password=password, port=port)    print("登录成功!")except paramiko.AuthenticationException as auth_exception:    print(f"认证失败:身份验证错误,请检查用户名和密码是否正确。")    sys.exit(1)except paramiko.SSHException as ssh_exception:    print(f"SSH连接错误: {ssh_exception}")    sys.exit(1)except Exception as error:    print(f"发生异常: {error}")    sys.exit(1)
# 执行Shell脚本stdin, stdout, stderr = client.exec_command('''
time=$(date)echo "巡检时间$time"                                      

echo "##CPU使用情况##"function cpu(){usedcpu=$(vmstat|awk '{if (NR==3)print $13+$14}')IOwait=$(vmstat|awk '{if (NR==3)print $16}')echo "cpu使用率$usedcpu%,IO等待响应$IOwait%"}

echo "##内存使用情况##"mem=$(free -h |grep Mem |awk '{print $2}')free=$(free -h |grep Mem |awk '{print $4}')used=$(free -h |grep Mem |awk '{print $3}')echo "总内存为 $mem ,已使用$used ,剩余$free "

echo "##硬盘使用情况##"disk=`df -h |grep ^/dev`echo "磁盘使用情况如下:$disk"  ''')
# 读取执行结果output = stdout.read().decode()#获取当前时间current_time = datetime.datetime.now()#添加时间戳timestamp = current_time.strftime("%Y-%m-%d-%H-%M-%S")save_path = r'C:\Users\ralap\Desktop\Python\服务器巡检结果-' + timestamp + '.txt'with open(save_path, 'w') as file:    file.write(output)# 关闭SSH连接client.close()                                         
print('巡检完成,结果已保存至' + save_path)
赞(4)
未经允许不得转载:工具盒子 » 利用Python脚本登录服务器并执行命令:进阶实践指南