fabric是基于paramiko的ssh远程命令的再次封装,功能更强大,不少功能能够直接调用,避免重复造轮子。python
脚本不是很完善,只是实现了基本功能,使用以前请慎重。使用方式要用fabric提供的fab命令,能够本身再用shell封装一层,使执行方式更加友好。git
功能:shell
支持批量命令api
批量上传下载文件并发
批量修改密码(密码字段自动生成随机码,默认16位,能够修改脚本中的pass_len变量作控制)app
支持日志记录(默认日志为当前目录下的logs/datetime/下,能够修改脚本中logdir的值自定义)dom
支持并发(fabric自身功能,默认200并发,并发数量能够加执行参数调整)ssh
使用方式:socket
全部方式均可以加 -P -z 并发数 来控制并发,不指定默认批量命令是并发200,其它功能是串行执行。
ide
批量命令
fab info:host_file,cmd_file go
批量修改密码:
fab info:host_file passwd
批量上传文件:
fab info:host_file upload:local_file,remote_file
批量下载文件
fab info:host_file download:remote_file,local_file
主机列表格式
IP PORT PASSWORD
脚本:
#!/usr/bin/python import os,sys,time,string,random,copy from fabric.api import * from fabric.colors import * import socket pass_len=16 t = time.strftime('%Y%m%d-%H%M%S',time.localtime(time.time())) logdir='logs/'+t def mkdir(path): path=path.strip() isExists=os.path.exists(path) if not isExists: print 'log is in '+path os.makedirs(path) return True else: print path+'logdir is exist' return False mkdir(logdir) def log(logdir,results,type='1',name=None): if type=='1': logfile=open(logdir+'/'+env.host,'a') logfile.write(results) logfile.close() else: logfile=open(logdir+'/'+name,'a') logfile.write(results) logfile.close() def GenPassword(length=pass_len): chars=string.ascii_letters+string.digits return ''.join([random.choice(chars) for i in range(length)]) @task def info(arg1,arg2=None): hosts_file=arg1 cmd_file=arg2 global command for line in open(hosts_file,'r'): line_host = 'root@%s:%s'%(line.split()[0],line.split()[1]) env.hosts.append(line_host) env.passwords[line_host]=line.split()[2] if arg2: command=open(cmd_file,'r').read() @task @parallel(pool_size=200) def go(): results=run(command,quiet=True) print (green('\n\n'+'='*10+'This is '+env.host+' Results....'+'='*10+'\n\n')) print results log(logdir,results) @task def upload(local_path,remote_path): put(local_path, remote_path, use_sudo=False, mirror_local_mode=False, mode=None) @task def download(remote_path, local_path=None): get(remote_path, local_path) @task def passwd(): password=GenPassword() run('echo %s | passwd root --stdin;history -c' % password) newpass_info='%s\t%s\n'%(env.host,password) log(logdir,newpass_info,type=2,name='pass_info') print(green("Life is short,you need Python....."))