常青树 发表于 2017-5-7 15:21:18

python写的批量操作远程主机脚本(命令执行,上传、下载文件)

  最近在学习python,借助fabric模块写了个批量操作服务器的脚本,在此分享给大家,如有不足之处,欢迎大家指正
  准备工作:
  安装python 2.6.5:
  yum -y install readline*
  tar xf Python-2.6.5.tar.bz2
  cd Python-2.6.5
  将目录下Modules/Setup.dist文件中"readline readline.c -lreadline -ltermcap"行前的注释去掉
  编译安装:
  ./configure --enable-shared
  make -j8 && make install
  安装setuptools
  tar xf setuptools-0.6c11.tar.gz
  cd setuptools-0.6c11
  python setup.py install
  安装fabric
  执行安装时,软件会自动从网上查找依赖的安装包并进行安装
  tar xf fabric-0.9rc2.tar.gz
  cd goosemo-fabric-1eacbf2
  python setup.py install
  ############################################################################
  pyssh脚本:
#!/usr/bin/env python
# -*- coding: utf-8 -*-

#####################################################
# Author: mayulin – mayulin@cy2009.com
# Last modified: 2011-04-28 12:27
# Filename: pssh.py
#####################################################

from fabric.api import env,run,put,get
from os import path
from re import findall
from sys import argv
from fabric.context_managers import hide
from time import sleep

USER='root'
HOST,IP_LIST=[],[]
PORT='22'
PRI_KEY,PASSWORD,CMD,uSRC,uDST,dSRC,dDST='','','','','','',''
timeout=1

for i in range(1,len(argv)+1):
if argv == '-h' or len(argv)==1:
print """
USAGE:
-u Use this argument to specify the user,default is 'root'
-H The host that you want to connect
-f The file content multiple ip address you want to connect
-P The ssh port,default is 22
-p You can specify password or a priviate key file to connect the host
-c The command you want the host(s) to run
-U The local file that you want to upload to the remote host(s)
-D The remote file that you want to download to the local host
-t The program running timeout,default is 1(s)
-h Print this help screen
"""

if argv == '-u':
USER=argv
env.user='%s'%(USER)
else:
env.user='%s'%(USER)
if argv == '-H':
arg=findall('(\d+\.\d+\.\d+\.\d+|\s+\.{3,4})',argv)
for j in arg:
if type(j).__name__ !='NoneType':
HOST.append(j)
else:
print 'The HostIP input error'
if argv == '-P':
PORT=argv
if argv == '-f':
if path.isfile('%s'%(argv)) == True:
IP_LIST=open('%s'%(argv),'r').readlines()
if argv == '-p':
if path.isfile(argv) == True:
PRI_KEY=argv
env.key_filename='%s'%(PRI_KEY)
else:
PASSWORD=argv
env.password='%s'%(PASSWORD)
if argv == '-c':
CMD=argv
if argv=='-t':
timeout=argv

SLP='sleep %s'%(timeout)

if argv == '-U':
x=src=argv.split(',')
uSRC=x
uDST=x

if argv == '-D':
y=src=argv.split(',')
dSRC=y
dDST=y

else:
IP_PORT=[]
if len(IP_LIST)!=0:
for k in IP_LIST:
IP_PORT.append(k.strip()+':'+PORT)
if len(HOST)!=0:
for k in HOST:
IP_PORT.append(k.strip()+':'+PORT)
if CMD != '':
def command():
with hide('running'):
run("%s;%s" %(CMD,SLP))
for ip in IP_PORT:
env.host_string=ip

print "Execute command : \"%s\" at Host : %s" %(CMD,ip.split(':'))
print "-------------------------------------------------"
command()
print "-------------------------------------------------"

if uSRC and uDST !='':
def upload():
with hide('running'):
put("%s" %(uSRC),"%s" %(uDST))
for ip in IP_PORT:
env.host_string=ip
print "Upload local file : \"%s\" to Host : %s \"%s\"" %(uSRC,ip.split(':'),uDST)
print "-------------------------------------------------"
upload()
print "-------------------------------------------------"

if dSRC and dDST !='':
def download():
with hide('running'):
get("%s" %(dSRC),"%s" %(dDST))
for ip in IP_PORT:
env.host_string=ip
print "Download remote file : \"%s\" from Host : %s to local \"%s\"" %(dSRC,ip.split(':'),dDST)
print "-------------------------------------------------"
download()
print "-------------------------------------------------"
  ###########################################################################################
  脚本执行效果:
  显示帮助:
http://img1.iyunv.com/attachment/201104/28/1628315_1303966379B1bf.jpg
  在多个远程主机上执行shell命令:
http://img1.iyunv.com/attachment/201104/28/1628315_1303966380xe8N.jpg
http://img1.iyunv.com/attachment/201104/28/1628315_13039663807Ica.jpg
  将远程主机上的文件下载到本地目录:
http://img1.iyunv.com/attachment/201104/28/1628315_1303966380kpEK.jpg
  将本地文件上传到多个远程主机上
http://img1.iyunv.com/attachment/201104/28/1628315_1303966380IH86.jpg
  本文出自 “梦~从这里起航” 博客,请务必保留此出处http://mayulin.blog.iyunv.com/1628315/555459
页: [1]
查看完整版本: python写的批量操作远程主机脚本(命令执行,上传、下载文件)