【Python】基於fabric模塊批量遠程主機操作

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....."))



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章