passwd_chang
#!/usr/bin/env python
#-*- coding: utf-8 -*-import random
importstring,os
import pexpect
import xlrd,xlwtfromxlwt import Stylefromxlutils.copy import copy
def passwd_creat():
salt= ''.join(random.sample(string.ascii_letters + string.digits, 8))returnsalt
def passwd_change(userip, oldpasswd, newpasswd):
child= pexpect.spawn('ssh connect@'+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)returndata
def get_coldata(passwdfile,sheet_name,num):
data=open_excel(passwdfile)
table=data.sheet_by_name(sheet_name)
coldata=table.row_values(num)returncoldata
def get_rownum(passwdfile,sheet_name):
data=open_excel(passwdfile)
table=data.sheet_by_name(sheet_name)
rowsNum=table.nrows #获取总行数
colsNum=table.ncols #获取总列数returnrowsNum,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)