python实现批量修改服务器密码的方法
作者:千米屠苏 时间:2021-09-11 01:23:09
求:机房、线上有多台主机,为了保障安全,需要定期修改密码。若手动修改,费时费力易出错。
程序应该满足如下需求 :
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) == "1":
eh.gen_new_password_excel()
elif str(inp) == "2":
updatepassword()
elif inp == "exit":
exit()
else:
continue
代码下载:https://github.com/liaogs/changepassword.git
总结
以上所述是小编给大家介绍的python实现批量修改服务器密码的方法,网站的支持!
如果你觉得本文对你有帮助,欢迎转载,烦请注明出处,谢谢!
来源:https://www.cnblogs.com/kilometerwine/p/9723335.html
标签:python,服务器,密码
0
投稿
猜你喜欢
windows下安装python paramiko模块的代码
2021-05-11 03:11:23
Python中类的继承代码实例
2023-11-26 05:29:14
django 2.2和mysql使用的常见问题
2024-01-27 17:40:02
Python通过命令开启http.server服务器的方法
2022-10-08 01:42:41
sql中的 where 、group by 和 having 用法解析
2024-01-14 05:12:13
PyQt5实现将Matplotlib图像嵌入到Scoll Area中显示滚动条效果
2021-12-21 05:40:39
Firebox 3 后退后按钮 diasabled 状态不恢复的一个解决方案
2008-11-06 12:28:00
SQL 优化
2024-01-16 10:50:40
po+selenium+unittest自动化测试项目实战
2022-05-03 14:46:46
javascript 数组去重复(在线去重工具)
2024-04-16 09:14:51
python使用正则表达式的search()函数实现指定位置搜索功能
2023-08-08 09:26:01
python互斥锁、加锁、同步机制、异步通信知识总结
2023-10-08 21:17:16
Python ValueError: invalid literal for int() with base 10 实用解决方法
2023-06-18 17:00:40
python+requests接口自动化框架的实现
2022-11-25 04:03:40
使用Python将Mysql的查询数据导出到文件的方法
2024-01-17 21:36:22
Django的models模型的具体使用
2022-08-13 07:57:04
SQLServer2008存储过程实现数据插入与更新
2024-01-19 06:01:21
mysql 5.7.14 下载安装、配置与使用详细教程
2024-01-15 14:39:25
PHP日期和时间函数的使用示例详解
2023-06-28 07:28:25
PyTorch一小时掌握之图像识别实战篇
2023-01-28 00:08:01