使用paramiko模块远程登录并上传或下载文件

1.paramiko安装

1)安装PyCrypto2.6 for Python 2.7 64bit。地址:http://www.voidspace.org.uk/python/modules.shtml#pycrypto

直接双击安装

2)安装ecdsa-0.10.tar.gz,地址:https://pypi.python.org/packages/source/e/ecdsa/ecdsa-0.10.tar.gz 

解压缩后cd到目录下用python setup.py install命令安装

3)安装paramiko,地址:https://pypi.python.org/packages/source/p/paramiko/paramiko-1.12.1.tar.gz

同样用python setup.py install命令安装

2.使用paramiko远程登录到linux机器并执行命令

直接上代码

import paramiko

_default_port = 22
def ssh(cmd, ip, usernamer, passwd):
    """
    远程到目标机器并执行命令,返回执行结果
    """
    out = None  
    ssh = paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())    
    try:
        ssh.connect(ip,_default_port,username,passwd,timeout=5)
        stdin, stdout, stderr = ssh.exec_command(cmd)
        out = stdout.readlines()
    except Exception as e:
        print 'ssh to %s\tError\n reason:%s'%(ip,e)
    finally:
        if ssh:
            ssh.close()      
    return out

3.上传文件到目标机器

def upload(remotepath, localpath, ip, port, username, passwd):
    t = paramiko.Transport((ip, port))   
    try:     
        t.connect(username=username,password=passwd)        
        sftp = paramiko.SFTPClient.from_transport(t)       
        sftp.put(localpath,remotepath) 
    except Exception as e:
        print 'upload file to %s\tError\n reason:%s'%(ip,e) 
    finally:
        if t:
            t.close()

4.从目标机器下载文件

def download2(remotepath, localpath, ip, port, username, passwd):
    t = paramiko.Transport((ip, port))  
    try:      
        t.connect(username=username,password=passwd)        
        sftp = paramiko.SFTPClient.from_transport(t)      
        sftp.get(remotepath,localpath) 
    except Exception as e:
        print 'download file from %s\tError\n reason:%s'%(ip,e) 
    finally:
        if t:
            t.close()
paramiko没有直接上传下载文件夹的方法,可以用os.walk()等方法来遍历文件夹实现依次上传或下载。
posted @ 2016-07-20 15:18  zoro_robin  Views(321)  Comments(0Edit  收藏  举报