python发送文件到服务器

需求:django后台收到文件后,将该文件发送到别的服务器上

第一次接触,功能感觉和linux中的scp命令一样,于是百度查了下python能否实现scp命令,发现是通过python中的paramiko模块来实现的,具体实现的代码如下:

# python连接远程服务器,发送文件
def ssh_scp_put(ip, port, user, password, local_file, remote_file):
    """
    
    :param ip: 服务器ip地址
    :param port: 端口(22)
    :param user: 用户名
    :param password: 用户密码
    :param local_file: 本地文件地址
    :param remote_file: 要上传的文件地址(例:/test.txt)
    :return: 
    """
    ssh = paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    ssh.connect(ip, port, user, password)

    sftp = ssh.open_sftp()
    sftp.put(local_file, remote_file)

具体的参数解释如上代码所示,直接运行即可将本地文件上传到服务器端

 

案例:上传文件到本地,然后再分发到服务器上

def test(request):
    if request.method == "POST":
        file = request.FILES.get("file")
        # BASE_DIR为项目路径,path为要保存文件路径
        path = os.path.join(BASE_DIR, 'begin\\static', 'file', file.name)
        # 二进制的方式写入文件
        with open(path, 'wb') as f:
            for i in file.chunks():
                f.write(i)
        ssh_scp_put('114.116.100.185', 22, 'root', '*****', path, '/{}'.format(file.name))
    return render(request, 'operation.html')

ps:paramiko使用出现CryptographyDeprecationWarning: encode_point has been deprecated on EllipticCurvePubl...

使用paramiko连接交换时出现 CryptographyDeprecationWarning 的警告,百度说依赖安装的 Cryptography 包版本高了,安装2.4.2 版本的

pip install cryptography==2.4.2

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值