之前写过一个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
:: The command pwd result is: /root ----------------------------------------------------------------------
192.168.3.3
[Errno ] Connection refused
----------------------------------------------------------------------
192.168.3.250
:: The command pwd result is: /root ----------------------------------------------------------------------
192.168.14.31
[Errno ] Connection refused
----------------------------------------------------------------------
192.168.3.3
[Errno ] Connection refused
----------------------------------------------------------------------
192.168.10.3
[Errno ] Connection timed out
----------------------------------------------------------------------
192.168.10.3
[Errno ] 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 ] 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 ] 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 ] 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 ] 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 ] Connection timed out
Data Transmission :
----------------------------------------------------------------------

参考文档:

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

linux下远程服务器批量执行命令及SFTP上传文件 -- python实现的更多相关文章

  1. Python 实现远程服务器批量执行命令

    paramiko 远程控制介绍 Python paramiko是一个相当好用的远程登录模块,采用ssh协议,可以实现linux服务器的ssh远程登录.首先来看一个简单的例子 import parami ...

  2. C#远程执行Linux系统中Shell命令和SFTP上传文件

    一.工具:SSH.Net 网址:https://github.com/sshnet/SSH.NET 二.调用命令代码: Renci.SshNet.SshClient ssh = "); ss ...

  3. 在linux下一般用scp这个命令来通过ssh传输文件

    在linux下一般用scp这个命令来通过ssh传输文件. 1.从服务器上下载文件scp username@servername:/path/filename /var/www/local_dir(本地 ...

  4. 使用SFTP上传文件到服务器的简单使用

    最近用到SFTP上传文件查找了一些资料后自己做了一点总结,方便以后的查询 /** * 将文件上传到服务器 * * @param filePath * 文件路径 * @param channelSftp ...

  5. linux 执行远程linux上的shell脚本或者命令以及scp 上传文件到ftp--免密码登陆

    场景:在linux A 上执行Linux B上的shell脚本和命令 步骤1.设置ssh免登陆 1.SSH无密码登录 # 本地服务器执行(A机器):生成密钥对 ssh-keygen -t dsa -P ...

  6. shell脚本批量执行命令----必需判断上一步执行结果--没有捷径

    # 注意:shell脚本批量执行命令,不能只写一个函数,然后把所有命令复制进去,之前试过这样是不行的.必须要有一个判断命令执行成功与否的语句 # 简单的命令可以不加结果判断符号,但是遇到解压包.sed ...

  7. git连接远程客户端,命令行窗口上传文件

    1.git官网,下载安装git客户端 2.配置全局的name和email,生成key git config --global user.name  XXX git config --global us ...

  8. 用sftp上传文件至linux服务器

    1.项目环境 框架:springmvc    项目管理工具:maven 2.必须使用的jar com.jcraft jsch 0.1.27 test 3.新建一个FileUpDown工具类,在类中添加 ...

  9. Linux使用sz、rz命令下载、上传文件

    1.安装服务 yum -y install lrzsz 2.上传命令:rz 使用rz命令,会调用系统的资源管理器,选择文件进行上传即可.上传的文件默认保存linux当前所在目录 3.下载命令:sz 根 ...

随机推荐

  1. 基于Java的四大开源测试工具

    摘要:成功的应用程序离不开测试人员和QA团队反复地测试,应用程序在进行最后的部署之前,需要通过测试来确保它的负载管理能力以及在特殊情况下的工作条件和工作加载情况. %R[)vA t]N0 测试是应用程 ...

  2. ajax传值给php

    test.php <script type="text/javascript"> function selectInput(oSelect) { var value= ...

  3. 获取FirefoxProfile配置文件以及使用方法介绍

    使用默认方式构建的(WebDriver)FirefoxDriver实例: WebDriver driver = new FirefoxDriver(); 这种方式下,打开的Firefox浏览器将是不带 ...

  4. 第三百零五节,Django框架,Views(视图函数),也就是逻辑处理函数里的各种方法与属性

    Django框架,Views(视图函数),也就是逻辑处理函数里的各种方法与属性 Views(视图函数)逻辑处理,最终是围绕着两个对象实现的 http请求中产生两个核心对象: http请求:HttpRe ...

  5. e636. Listening to All Key Events Before Delivery to Focused Component

    Registering a key event dispatcher with the keyboard focus manager allows you to see all key events ...

  6. e686. 显示打印窗口

    The print dialog allows the user to change the default printer settings such as the default printer, ...

  7. Erlang TCP Socket的接收进程的2种方案

    转自:http://blog.csdn.net/summerhust/article/details/8740973 一旦打开了一个使用TCP连接的套接字,它就始终保持打开状态,直至任何一方关闭它或因 ...

  8. SQL Server 删除数据库所有表和所有存储过程

    场景: SQL Server中,需要删除所有表或所有存储过程时,手动的方式只能逐个进行删除,耗个人时间,所以想弄个语句来实现这样的需求.   如果由于外键约束删除table失败,则先删除所有约束: - ...

  9. JQuery 选择器 xpath 语法应用

    比如下面html代码 <ul> <li class="aaaa" title="ttt">li-1</li> <li ...

  10. AI逻辑实现-取舍行为树还是状态机

    AI逻辑实现-选择行为树还是状态机? 关注AI的朋友可能会看过赖勇浩翻译的<有限状态机时代终结的10大理由> ,里面谈到了状态机的诸多弊端.同时在ppt(附上下载地址)中述说了行为树的诸多 ...