linux下遠程服務器批量執行命令及SFTP上傳文件 -- python實現


之前寫過一個python遠程執行命令的腳本,但在一個性能測試中,要將程序批量分發到不同服務器,程序無法使用,再將之前的腳本更新,加入批量上傳的功能。之前腳本地址:http://www.cnblogs.com/landhu/p/4961##coding:utf-8

#------------------ #Author:Hu #Created:2016-02-29 #------------------ import paramiko,os,time,sys from optparse import OptionParser #使用optparse做命令行解析 parser = OptionParser(usage="usage:%prog [optinos] dest",version='Hu 3.0_20160229') parser.add_option('-f','--filename',dest='filename',default='ip.txt',help='The Servers info TXT') parser.add_option('-c','--command',dest='cmd',help='You want execute command') parser.add_option('-u','--upload',dest='upload',help='You want to upload file') #parser.add_option('-d','--download',dest='download',help='You want to download file') #parser.add_option('')  (options,args)=parser.parse_args()
#上傳中顯示進度,使用的是paramiko put中的callback選項

def callback(a=10,b=10):
 sys.stdout.write('Data Transmission %10f M [%3.2f%%]\r') % (a/1024./1024,a*100./int(b)))
sys.stdout.flush()
''' 將功能封裝 ''' class bat(object): def __init__(self,ip,pt,pw,us): self.ip=ip self.pt=pt self.pw=pw self.us=us print self.ip def command(self,comm): self.comm=comm try: ssh = paramiko.SSHClient() ssh.load_system_host_keys() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect(self.ip,port=self.pt,username=self.us,password=self.pw) for COMM in self.comm: stdin,stdout,stderr = ssh.exec_command(COMM) print "%s The command %s result is:\n" % (time.strftime("%Y%m%d %H:%M:%S"),COMM) read = stdout.read() print read print '-'*70 ssh.close() except Exception,e: print e print '-'*70 def upload(self,filename): self.ufilename=filename try: #print self.ip,self.pt client = paramiko.Transport((self.ip, self.pt)) client.connect(username = self.us, password = self.pw) sftp = paramiko.SFTPClient.from_transport(client) sftp.put(localpath=self.ufilename,remotepath=self.ufilename,callback=callback) client.close() except Exception,e: print e #本想寫個從服務器批量下載的功能能,但實際上用不上,先不添加,后期再豐富 def download(self,filename): self.dfilename=filename try: client = paramiko.Transport((self.ip, self.pt)) client.connect(username = self.us, password = self.pw) sftp = paramiko.SFTPClient.from_transport(client) sftp.get(self.dfilename, self.dfilename) client.close() except: print 'Error' if __name__ == '__main__': if os.path.exists(options.filename): filename=options.filename else: print 'Please check %s and ip.txt is exits' % options.server exit(-1) print "-"*70 #批量執行命令與上傳不能同時存在 if options.cmd and options.upload: parser.error("options -c and -u are mutually exclusive") elif options.cmd: open_ip = open(filename) command=[] command=options.cmd.split(',') for line in open_ip.readlines(): ip,user,passwd,port=line.strip().split() port=int(port) dd=bat(ip=ip,pt=port,pw=passwd,us=user) dd.command(command) elif options.upload: fullpwd=os.path.abspath(options.upload) open_ip = open(filename) for line in open_ip.readlines(): ip,user,passwd,port=line.strip().split() port=int(port) dd=bat(ip=ip,pt=port,pw=passwd,us=user) print "You want upload file is : %s " % fullpwd dd.upload(options.upload) print 'Data Transmission :' print '-'*70 else: print 'Arg is error,Use "-h" to help!' ''' elif options.download: fullpwd=os.path.abspath(options.download) open_ip = open(filename) for line in open_ip.readlines(): ip,user,passwd,port=line.strip().split() port=int(port) dd=bat(ip=ip,pt=port,pw=passwd,us=user) print "You want download file is : %s " % fullpwd dd.download(options.download) print 'Data Transmission :' print '-'*60 '''

默認讀取ip.txt中的服務器信息,信息的格式:

IP 用戶 密碼 端口

192.168.3.200 root  rr@#$zlb 36003
192.168.3.250 root rr@#250 22
192.168.14.31 root rr@#31 22
192.168.10.3 root 111 22
192.168.10.3 root 111 22

運行如下:

[root@localhost tools]# python remote.py -h
Usage: usage:remote.py [optinos] dest

Options:
  --version             show program's version number and exit
  -h, --help            show this help message and exit
  -f FILENAME, --filename=FILENAME
                        The Servers info TXT
  -c CMD, --command=CMD
                        You want execute command
  -u UPLOAD, --upload=UPLOAD
                        You want to upload file

 

[root@localhost tools]# python remote.py -c pwd
------------------------------------------------------------
192.168.3.200
20160229 15:07:39 The command pwd result is:

/root

----------------------------------------------------------------------
192.168.3.3
[Errno 111] Connection refused
----------------------------------------------------------------------
192.168.3.250
20160229 15:07:50 The command pwd result is:

/root

----------------------------------------------------------------------
192.168.14.31
[Errno 111] Connection refused
----------------------------------------------------------------------
192.168.3.3
[Errno 111] Connection refused
----------------------------------------------------------------------
192.168.10.3
[Errno 110] Connection timed out
----------------------------------------------------------------------
192.168.10.3
[Errno 110] Connection timed out
----------------------------------------------------------------------

兩個命令不能沖突:

[root@localhost tools]# python remote.py -c pwd -u ip.txt
------------------------------------------------------------
Usage: usage:remote.py [optinos] dest

remote.py: error: options -c and -u are mutually exclusive

上傳時有一個特別的功能,上傳時的進度顯示,這里使用的是paramiko put中的callback參數

效果如下:

結果如下:

[root@localhost tools]# python remote.py -u bms.war 
------------------------------------------------------------
192.168.3.200
You want upload file is : /tools/bms.war 
Data Transmission :77.198704 M [100.00%]
----------------------------------------------------------------------
192.168.3.3
You want upload file is : /tools/bms.war 
Unable to connect to 192.168.3.3: [Errno 111] Connection refused
Data Transmission :
----------------------------------------------------------------------
192.168.3.250
You want upload file is : /tools/bms.war 
Data Transmission :77.198704 M [100.00%]
----------------------------------------------------------------------
192.168.14.31
You want upload file is : /tools/bms.war 
Unable to connect to 192.168.14.31: [Errno 111] Connection refused
Data Transmission :
----------------------------------------------------------------------
192.168.3.3
You want upload file is : /tools/bms.war 
Unable to connect to 192.168.3.3: [Errno 111] Connection refused
Data Transmission :
----------------------------------------------------------------------
192.168.10.3
You want upload file is : /tools/bms.war 
Unable to connect to 192.168.10.3: [Errno 110] Connection timed out
Data Transmission :
----------------------------------------------------------------------
192.168.10.3
You want upload file is : /tools/bms.war 
Unable to connect to 192.168.10.3: [Errno 110] Connection timed out
Data Transmission :
----------------------------------------------------------------------

 

參考文檔:

paramiko SFTP:http://paramiko-docs.readthedocs.org/en/latest/api/sftp.html

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM