搭建环境

centos 7.4 

使用脚本

python
批量修改connect用户的密码
生成密码为随机密码 保存为xls文档
passwd_chang

#!/usr/bin/env python
# -*- coding: utf-8 -*-
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 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)
    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)

 

 

1. 上传脚本,以及脚本需要的模块

Python脚本批量修改服务器密码

 

 2.安装所需要的模块。

2.1 解压gz包。
Python脚本批量修改服务器密码
2.2 cd到解压文件目录下
Python脚本批量修改服务器密码
2.3 执行脚本安装模块
Python脚本批量修改服务器密码
目录下的所有gz包都要安装过程略过
Python脚本批量修改服务器密码

3.执行脚本测试实验。

3.1创建一个connect用户并设置密码。并登陆测试。
Python脚本批量修改服务器密码
 
Python脚本批量修改服务器密码
3.2创建文档(文档名需要和脚本里的名称一样)
Python脚本批量修改服务器密码
3.3上传文档到定义的路径下
Python脚本批量修改服务器密码
 
Python脚本批量修改服务器密码
3.4执行脚本测试
Python脚本批量修改服务器密码
3.5
sz下载表格查看密码
Python脚本批量修改服务器密码
 
Python脚本批量修改服务器密码
3.6 使用新密码登陆测试
Python脚本批量修改服务器密码
 
 

相关文章: