In Python, how to write a string to a file on a remote machine?

后端 未结 5 1630
甜味超标
甜味超标 2020-12-16 00:11

On Machine1, I have a Python2.7 script that computes a big (up to 10MB) binary string in RAM that I\'d like to write to a disk file on Machine2, which is a remote machine.

5条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-16 00:35

    Paramiko supports opening files on remote machines:

    import paramiko
    
    def put_file(machinename, username, dirname, filename, data):
        ssh = paramiko.SSHClient()
        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        ssh.connect(machinename, username=username)
        sftp = ssh.open_sftp()
        try:
            sftp.mkdir(dirname)
        except IOError:
            pass
        f = sftp.open(dirname + '/' + filename, 'w')
        f.write(data)
        f.close()
        ssh.close()
    
    
    data = 'This is arbitrary data\n'.encode('ascii')
    put_file('v13', 'rob', '/tmp/dir', 'file.bin', data)
    

提交回复
热议问题