需求:机房、线上有多台主机,为了保障安全,需要定期修改密码。若手动修改,费时费力易出错。

程序应该满足如下需求 :

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) == "":
eh.gen_new_password_excel() elif str(inp) == "":
updatepassword() elif inp == "exit":
exit()
else:
continue

代码下载:https://github.com/liaogs/changepassword.git

python实现批量修改服务器密码的更多相关文章

  1. Python自动批量修改服务器密码

    工作中,我们经常会定期更换服务器密码,如果手动去修改,不仅费时,而且容易出错.下面提供了一种思路,可以实现批量.自动修改服务器密码. 大致思路:首先,为每一台服务器设定一个唯一标识:其次,将每台服务器 ...

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

    搭建环境 centos 7.4 使用脚本 python 批量修改connect用户的密码 生成密码为随机密码 保存为xls文档   passwd_chang #!/usr/bin/env python ...

  3. saltstack+python批量修改服务器密码

    saltstack安装:略过 python脚本修改密码: # -*- coding utf-8 -*- import socket import re import os import sys imp ...

  4. Ansible playbook 批量修改服务器密码 先普通后root用户

    fsckzy   Ansible playbook 批量修改服务器密码 客户的需求:修改所有服务器密码,密码规则为Rfv5%+主机名后3位 背景:服务器有CentOS6.7,SuSE9.10.11,r ...

  5. ansible批量修改服务器密码

    看了一下网上代码大多数是ansible-playbook实现的,需要写一个脚本,或者手动传递变量进去. 以前用python tcp模块写过客户端主动上报修改密码脚本 今天写一个ansible主控客户端 ...

  6. (转)linux passwd批量修改用户密码

    linux passwd批量修改用户密码  原文:http://blog.csdn.net/xuwuhao/article/details/46618913 对系统定期修改密码是一个很重要的安全常识, ...

  7. linux passwd批量修改用户密码

    linux passwd批量修改用户密码 对系统定期修改密码是一个很重要的安全常识,通常,我们修改用户密码都使用 passwd user 这样的命令来修改密码,但是这样会进入交互模式,即使使用脚本也不 ...

  8. python批量修改ssh密码

    由于工作需要本文主结合了excel表格,对表格中的ssh密码进行批量修改 以下是详细代码(python3): #!/usr/bin/env python#-*-coding:utf-8-*- impo ...

  9. 批量修改Linux密码脚本(Python)

    搭建环境 centos 7.4 使用脚本 python 批量修改connect用户的密码 生成密码为随机密码 保存为xls文档 #!/usr/bin/env python # -*- coding: ...

随机推荐

  1. 使用Photoshop+960 Grid System模板进行网页设计

    前几天彬Go和大家一起讨论了960 Grid System这个CSS网格系统框架的基本原理和使用方法.今天,暴风彬彬将教大家使用Photoshop结合960 Grid System模板来设计一个真正符 ...

  2. ios position:fixed 上滑下拉抖动

    ios position:fixed 上滑下拉抖动 最近呢遇到一个ios的兼容问题,界面是需要一个头底部的固定的效果,用的position:fixed定位布局,写完测试发现安卓手机正常的,按时ios上 ...

  3. 纯css制作三级菜单

    <!DOCTYPE html> <html> <head> <title>三级菜单</title> <meta charset=&qu ...

  4. [笔记]Laravel TDD 胡乱记录

    TDD: 测试驱动开发(Test-Driven Development),TDD的原理是在开发功能代码之前,先编写单元测试用例代码,测试代码确定需要编写什么产品代码. -- 载自TDD百度百科 参考 ...

  5. 帆软报表PC端实施报表心得体会

    1.报表制作完成后,预览时自动显示查询内容,在控件处设置: 2.求一列数据的最小值(除去0),并对最小值字体加粗标绿,需要对对应单元格设置条件属性,并插入公式:C6 = min(greparray(C ...

  6. Windows 关闭win32 控制台

    {     fclose(pf); BOOL ret = FreeConsole(); }

  7. .net core, docker 在vs2019开发过程中的问题以及解决办法

    .net core, docker 在vs2019开发过程中的问题以及解决办法 记录下来,帮助Ta人~ 1.vs调试,快Build完后提示Docker 端口:xxxx,xxxx,xxxx占用 解决办法 ...

  8. 在.net core上,Web网站调用微信支付-统一下单接口(xml传参)一直返回错误:mch_id参数格式错误

    这是 微信支付-统一下单 接口文档 一.问题描述 在调用统一下单接口时,报mch_id参数格式错误,但商户ID确实是10位数字正确的,可就是一直报这个错误 返回的错误xml如下: 二.排错过程 1.多 ...

  9. openstack实战部署

    简介:Openstack系统是由几个关键服务组成,他们可以单独安装,这些服务根据你的云需求工作在一起,这些服务包括计算服务.认证服务.网络服务.镜像服务.块存储服务.对象存储服务.计量服务.编排服务和 ...

  10. <python基础>封装,继承,多态,重写,重载

    什么是封装? 所谓的面向对象就是将我们的程序模块化,对象化,把具体事物的特性属性和通过这些属性来实现一些动作的具体方法放到一个类里面,这就是封装.封装是我们所说的面相对象编程的特征之一.除此之外还有继 ...