#!/usr/bin/python #-- coding: utf-8 -- from random import choice import string,sys,time import paramiko,json from fabric.api import env,run,cd,task,rolespython
env.roledefs = { 'test':['root@10.1.33.132:22','root@10.1.33.133:22'], 'live':['root@10.1.33.134:22','root@10.1.33.133:22'] }git
class Ch_passwd(): def init(self,user): #self.ip = ip self.user = user self.passwd = [] ######產生隨機密碼### """function to generate a passwd""" def get_passwd(self,passwd_length=10): ####默認值 passwd_seed = string.digits + string.ascii_lowercase + string.ascii_lettersjson
- string.punctuation.replace("'","").replace('"','') passwd = [] while len(passwd) < passwd_length: passwd.append(choice(passwd_seed)) password=''.join(passwd) password=password.replace("'","").replace('"','')###這裏是爲了去除單雙引> 號,避免出現沒必要要的錯誤 return password ####登陸服務器修改密碼 def cha_passwd(self,Ip): new_passwd = self.get_passwd() self.passwd.append(new_passwd) run("/bin/echo '%s'|passwd --stdin %s" %(new_passwd,self.user)) data = dict(zip(Ip,self.passwd)) with open('/mnt/passwd.txt','w') as f: json.dump(data,f,indent=4) ch_passwd = Ch_passwd('root') @task @roles('test') def get_host_test(): """ get hostname """ print time.strftime("%Y-%m-%d %H:%M:%S",time.localtime()) Ip = [] for ip in env.roledefs['test']: r1 = r"root@([\d+.]+):22" s = ''.join(re.findall(r1,ip)) Ip.append(s) ch_passwd.cha_passwd(Ip)