#!/usr/bin/python#-- coding: utf-8 --from random import choiceimport string,sys,timeimport paramiko,
#!/usr/bin/python#-- coding: utf-8 --from random import choiceimport string,sys,timeimport paramiko,jsonfrom fabric.api import env,run,cd,task,roles
env.roledefs = {'test':['[email protected]:22','[email protected]:22'],'live':['[email protected]:22','[email protected]:22']}
class Ch_passwd():def init(self,user):#self.ip = ipself.user = userself.passwd = []######产生随机密码###"""function to generate a passwd"""def get_passwd(self,passwd_length=10): ####默认值passwd_seed = string.digits + string.ascii_lowercase + string.ascii_letters
- 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)