linuxisperfect 2020-06-08
#!/usr/bin/env python # -*- coding: utf-8 -*- ############################################ #通过脚本批量修改Linux主机密码并保存到xls中 #雪文龙 2018-5-18 V1 # #修改者:xxx #修改时间:2018-xx-xx #修改内容:修改内容描述 ############################################ import random import string,os import pexpect import xlrd,xlwt from xlwt import Style from xlutils.copy import copy def passwd_creat(): salt = ‘‘.join(random.sample(string.ascii_letters + string.digits, 8)) return salt def passwd_change(userip, oldpasswd, newpasswd): child = pexpect.spawn(‘ssh ‘+userip) ###connect 用户可改root fout = file(‘/home/shell/passwd/newpasslog.txt‘,‘a‘) ##定义日志文件, child.logfile = fout index = child.expect([‘password:‘,‘continue connecting (yes/no)?‘]) if index == 0: child.sendline(oldpasswd) elif index == 1: child.sendline(‘yes‘) child.expect(‘password:‘) child.sendline(oldpasswd) child.expect(‘$‘) child.sendline(‘sudo -i‘) child.expect(‘#‘) child.sendline(‘echo ‘+newpasswd+‘ | passwd --stdin connect‘) ### connect 用户可改root child.expect(‘#‘) child.sendline(‘exit‘) def open_excel(passwdfile): data = xlrd.open_workbook(passwdfile) return data def get_coldata(passwdfile,sheet_name,num): data = open_excel(passwdfile) table = data.sheet_by_name(sheet_name) coldata = table.row_values(num) return coldata def get_rownum(passwdfile,sheet_name): data = open_excel(passwdfile) table = data.sheet_by_name(sheet_name) rowsNum = table.nrows #获取总行数 colsNum = table.ncols #获取总列数 return rowsNum,colsNum def add_newpwd(row, col, str): rb = xlrd.open_workbook(passwdfile, formatting_info=True) wb = copy(rb) ws = wb.get_sheet(0) ws.write(row, col, str) wb.save(passwdfile) if __name__ == "__main__": passwdfile = "/home/shell/passwd/newpasswd.xls" #文档读取输出路径 sheet_name = "Sheet1" rowsNum, colsNum = get_rownum(passwdfile,sheet_name) add_newpwd(0,colsNum,‘newpasswd‘) for i in range(1,rowsNum): newpasswd = passwd_creat() coldata = get_coldata(passwdfile,sheet_name,i) passwd_change(coldata[0], coldata[1], newpasswd) add_newpwd(i,colsNum,newpasswd)