Python使用Paramiko模块实现

发布时间:2019-09-10 08:47:24编辑:auto阅读(1419)

    paramiko是用python写的一个模块,遵循SSH2协议,支持以加密和认证的方式,进行远程服务器的连接。利用该模块,可以方便的进行ssh连接和sftp协议进行sftp文件传输以及远程命令执行。
    

    通过安装包安装:

    wget http://ftp.dlitz.net/pub/dlitz/crypto/pycrypto/pycrypto-2.6.tar.gz
    wget http://www.lag.net/paramiko/download/paramiko-1.7.7.1.tar.gz
    
    tar -zxvf pycrypto-2.6.tar.gz
    
    cd pycrypto-2.6/
    
    python setup.py build && python setup.py install
    
    
    wget http://www.lag.net/paramiko/download/paramiko-1.7.7.1.tar.gz
    
    tar xvzf paramiko-1.7.7.1.tar.gz
    
    cd paramiko-1.7.7.1/
    
    python setup.py build && python setup.py install
    

    yum安装,简单省事:

    yum install python-paramiko -y
    

    简单使用:从远程服务器拷贝文件:

    #coding=utf-8
    import paramiko, os
    def remote_scp(type, host_ip, remote_path, local_path, username, password):
        ssh_port = 22
        try:
            conn = paramiko.Transport((host_ip, ssh_port))
            conn.connect(username=username, password=password)
            sftp = paramiko.SFTPClient.from_transport(conn)
            if type == 'remoteRead':
                if not local_path:
                    fileName = os.path.split(remote_path)
                    local_path = os.path.join('/tmp', fileName[1])
                sftp.get(remote_path, local_path)
    
            if type == "remoteWrite":
                sftp.put(local_path, remote_path)
    
            conn.close()
            return True
    
        except Exception:
            return False

    通过传递操作类型,主机ip,远程路径和本地路径,用户名密码即可实现文件的远程拷贝

关键字