python实现批量修改服务器密码的方法实现批量修改服务器密码的方法
主要介绍了python实现批量修改服务器密码的方法,本文通过实例代码给大家介绍的非常详细,具有一定的参
考借鉴价值 ,需要的朋友可以参考下
求:机房、线上有多台主机,为了保障安全,需要定期修改密码。若手动修改,费时费力易出错。
程序应该满足如下需求 :
1、在现有的excel密码表格,在最后一个字段后面生成新的密码,另存为一个新的excel密码文件
2、根据新的excel密码文件,更新服务器密码,将更新后的结果保存到另外一个excel文件。
a、原始excel文件字段格式,最后一个字段为原始密码
IP USER PORT pwd
b、生成新的密码文件字段格式,最后一个字段为更新密码
IP USER PORT pwd pwd20180929
c、生成新的密码文件字段格式,最后一个字段为更新是否成功的标识
IP PORT USERNAME OLDPASS NEWPASS FLAG
按照面向对象编程的思想,可以设计2个类,excelhandler和ChangePassword
excelhandler主要负责excel文件的读取,写入,增加一个生成密码文件
ChangePassword主要利用paramiko登陆服务器进行密码更新
excelhandler类
#_*_ 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"]