求:機房、線上有多臺主機,為了保障安全,需要定期修改密碼。若手動修改,費時費力易出錯。
程序應該滿足如下需求 :
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"] 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
main
#_*_ 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實現批量修改服務器密碼的方法,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對腳本之家網站的支持!
如果你覺得本文對你有幫助,歡迎轉載,煩請注明出處,謝謝!
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
