Python实现批量修改服务器密码的自动化方案
本文介绍使用Python实现批量修改服务器密码的完整方案。通过封装excelhandler类处理Excel文件的读取与生成,利用ChangePassword类结合paramiko库进行SSH远程连接并执行密码更新命令。方案包含生成新密码、执行更新及记录结果三个步骤,旨在解决手动修改密码效率低且易出错的问题,适用于机房或线上多台主机的定期安全维护场景。
批量修改服务器密码的背景与需求
在机房或线上环境中,通常存在多台主机。为了保障系统安全,需要定期修改服务器密码。如果采用手动方式逐一修改,不仅耗时费力,还容易因人为疏忽导致错误。
为此,我们需要设计一个程序来满足特定的自动化需求:
首先,程序需读取现有的包含密码的Excel表格,在原有数据的最后一个字段后生成新的随机密码,并将结果另存为一个新的Excel密码文件。
其次,程序依据生成的新Excel密码文件,自动更新对应服务器的登录密码,并将更新操作的结果(成功或失败)保存至另一个独立的Excel文件中。
原始Excel文件的字段格式如下,其中最后一个字段存储的是原始密码:
IP USER PORT pwd
生成的新密码文件字段格式如下,最后一个字段为新生成的密码:
IP USER PORT pwd pwd20180929
记录更新结果的Excel文件字段格式如下,最后一个字段用于标识密码更新是否成功:
IP PORT USERNAME OLDPASS NEWPASS FLAG
系统架构与类设计
基于面向对象编程的思想,我们可以设计两个核心类:excelhandler和ChangePassword。
excelhandler类主要负责Excel文件的读取、写入操作,以及生成包含新密码的Excel文件。
ChangePassword类则主要利用paramiko库登录服务器,执行密码更新命令。
以下是excelhandler类的具体实现代码:
Excel处理类实现
#_*_ coding: utf-8 _*_
'''
@author liaogs
'''
import json
import xlrd
import xlwt
import time
import datetime
import base64
import random
from xlutils.copy import copy
class excelhandler():
def __init__(self,path):
self.path = path
self.workbook = None
self.rows = 0
self.cols = 0
self.serverlist = []
def read_excel(self):
self.workbook = xlrd.open_workbook(self.path)
sh1 = self.workbook.sheet_by_index(0)
self.rows = sh1.nrows
self.cols = sh1.ncols
for row in range(1,sh1.nrows):
server = []
for col in [0,1,2,sh1.ncols-2,sh1.ncols-1]:
server.append(sh1.cell(row,col).value)
self.serverlist.append(server)
def gen_new_password_excel(self):
old_excel = xlrd.open_workbook(self.path)
new_excel = copy(old_excel)
ws = new_excel.get_sheet(0)
coldt = "pass"+ str(datetime.date.today())
ws.write(0,self.cols,coldt)
for row in range(1,self.rows):
ws.write(row,self.cols,self.gen_key())
dt = time.strftime("%Y%m%d%H%M%S",time.localtime())
new_excel.save(dt+self.path)
def write_excel(self,serverlist):
wb = xlwt.Workbook()
ws = wb.add_sheet(u'sheet1',cell_overwrite_ok=True)
header = ["IP","PORT","USERNAME","OLDPASS","NEWPASS","FLAG"]
for col in range(0,6):
ws.write(0,col,header[col])
for row in range(len(serverlist)):
for col in range(0,6):
ws.write(row+1,col,serverlist[row][col])
dt = time.strftime("%Y%m%d%H%M%S", time.localtime())
wb.save(dt+".xlsx")
def get_server_list(self):
return self.serverlist
def get_rows(self):
return self.rows
def get_cols(self):
return self.cols
def gen_key(self):
pool = "1234567890abcdefghijklmnopqrstuvwxyzQWERTYUIOPASDFGHJKLZXCVBNM"
length = len(pool)
key = ""
for i in range(28):
c = random.randint(0,length)
key += pool[c:c+1]
return key
以下是ChangePassword类的具体实现代码:
服务器密码更新类实现
#_*_ coding: utf-8 _*_
'''
@author liaogs
'''
import paramiko
import sys
class ChangePassword():
def __init__(self,hostip,port,username,oldpass,newpass):
self.hostip = hostip
self.port = port
self.username = username
self.oldpass = oldpass
self.newpass = newpass
self.updateflag = False
def run_change(self):
s = paramiko.SSHClient()
s.set_missing_host_key_policy(paramiko.AutoAddPolicy())
tasklist = []
try:
s.connect(hostname=self.hostip, port=self.port, username=self.username, password=self.oldpass)
print ('"%s" is updating password' % self.hostip)
stdin, stdout, stderr = s.exec_command('echo %s |passwd --stdin root' % self.newpass)
r_message = stdout.read()
if "successfully" in r_message:
self.updateflag = True
print('%s is successful' %self.hostip)
else:
print('%s is failed' %self.hostip)
self.updateflag = False
s.close()
except Exception:
self.updateflag = False
print("connection error")
tasklist = [self.hostip, self.port, self.username, self.oldpass, self.newpass, self.updateflag]
return tasklist
主程序逻辑如下:
主程序与交互逻辑
#_*_ coding: utf-8 _*_
'''
@author liaogs
'''
import re
import sys
from excelhandler import excelhandler
from changepassword import ChangePassword
if __name__ == '__main__':
if len(sys.argv) == 1:
eh = excelhandler("pass.xlsx")
else:
eh = excelhandler(sys.argv[1])
eh.read_excel()
def updatepassword():
ret = eh.get_server_list()
tasklist = []
for i in range(len(ret)):
print(ret[i][0],ret[i][2],ret[i][1],ret[i][3],ret[i][4])
cp = ChangePassword(hostip=ret[i][0],port=int(ret[i][2]),username=ret[i][1],oldpass=ret[i][3],newpass=ret[i][4])
task = cp.run_change()
tasklist.append(task)
print(tasklist)
eh.write_excel(tasklist)
while True:
inp = input("1、生成密码 2、更新密码>>")
if str(inp) == "1":
eh.gen_new_password_excel()
elif str(inp) == "2":
updatepassword()
elif inp == "exit":
exit()
else:
continue
完整代码下载链接:https://github.com/liaogs/changepassword.git
总结
以上介绍了使用Python实现批量修改服务器密码的方法,希望能对大家有所帮助。如有任何疑问,欢迎留言,小编会及时回复。感谢大家对本站的支持! 如果觉得本文对您有帮助,欢迎转载,请注明出处,谢谢!
本站声明
本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。













