python寫的大量操作遠程主機指令碼(命令執行,上傳、下載檔案)

來源:互聯網
上載者:User

python寫的大量操作遠程主機指令碼(命令執行,上傳、下載檔案) 2011-04-28 12:53:44

標籤:伺服器

指令碼
ssh
python
集中化管理原創作品,允許轉載,轉載時請務必以超連結形式標明文章
原始出處 、作者資訊和本聲明。否則將追究法律責任。http://mayulin.blog.51cto.com/1628315/555459

最近在學習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[i-1] == '-h' or len(argv)==1:
            print """
            USAGE:
       -u [user]       Use this argument to specify the user,default is 'root'
       -H [host]       The host that you want to connect
       -f        The file content multiple ip address you want to connect
       -P [port]       The ssh port,default is 22
       -p [pwd|file]   You can specify password or a priviate key file to connect the host
       -c [command]    The command you want the host(s) to run
       -U [src,dst]    The local file that you want to upload to the remote host(s)
       -D [src,dst]    The remote file that you want to download to the local host
       -t [timeout]    The program running timeout,default is 1(s)
       -h              Print this help screen
            """

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

    SLP='sleep %s'%(timeout)

    if argv[i-1] == '-U':
        x=src=\'#\'" />         uSRC=x[0]
        uDST=x[1]

    if argv[i-1] == '-D':
        y=src=\'#\'" />         dSRC=y[0]
        dDST=y[1]           

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(':')[0])
        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(':')[0],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(':')[0],dDST)
            print "-------------------------------------------------"
            download()
            print "-------------------------------------------------"
 

 

###########################################################################################

指令碼執行效果:

顯示協助:

在多個遠程主機上執行shell命令:

將遠程主機上的檔案下載到本地目錄:

將本地檔案上傳到多個遠程主機上

本文出自 “夢~從這裡起航” 部落格,請務必保留此出處http://mayulin.blog.51cto.com/1628315/555459

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.