fabric是基于paramiko的ssh远程命令的再次封装,功能更强大,很多功能可以直接调用,避免重复造轮子。
脚本不是很完善,只是实现了基本功能,使用之前请慎重。使用方式要用fabric提供的fab命令,可以自己再用shell封装一层,使执行方式更加友好。
功能:
支持批量命令
批量上传下载文件
批量修改密码(密码字段自动生成随机码,默认16位,可以修改脚本中的pass_len变量做控制)
支持日志记录(默认日志为当前目录下的logs/datetime/下,可以修改脚本中logdir的值自定义)
支持并发(fabric自身功能,默认200并发,并发数量可以加执行参数调整)
使用方式:
所有方式都可以加 -P -z 并发数 来控制并发,不指定默认批量命令是并发200,其它功能是串行执行。
批量命令
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....."))
转载于:https://blog.51cto.com/lustlost/1327961