批量修改Linux密碼腳本(Python)


搭建環境

centos 7.4

使用腳本

python
批量修改connect用戶的密碼
生成密碼為隨機密碼 保存為xls文檔
 
#!/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 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.1 創建轉到腳本,模塊包存放地址。
1.2安裝上傳工具。
1.3上傳模塊包腳本。
rz上傳
sz下載

安裝所需要的模塊

2.1 解壓gz包。
2.2 cd到解壓文件目錄下
2.3 執行腳本安裝模塊
目錄下的所有gz包都要安裝過程略過

執行腳本測試實驗

3.1創建一個connect用戶並設置密碼。並登陸測試。
 
3.2創建文檔(文檔名需要和腳本里的名稱一樣)
3.3上傳文檔到定義的路徑下
 
3.4執行腳本測試
3.5
sz下載表格查看密碼
 
3.6 使用新密碼登陸測試
 
 
 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM