【问题标题】:In Python, how to write a file on a remote machine synchronously?在 Python 中,如何在远程机器上同步写入文件?
【发布时间】:2015-10-08 03:01:46
【问题描述】:

现在我需要打开一个远程文件来写东西,代码是这样的:

client = paramiko.SSHClient()
client.load_system_host_keys()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect(myHost,myPort,myUser,myPassword)
sftp = client.open_sftp()
fileObject = sftp.open(fullFilePath,'wb')
for i in xrange(10000):
   fileObject.write(databuf)
fileObject.close()    

现在我想确保所有数据都实际写入磁盘 所以代码修改如下:

client = paramiko.SSHClient()
client.load_system_host_keys()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect(myHost,myPort,myUser,myPassword)
sftp = client.open_sftp()
fileObject = sftp.open(fullFilePath,'wb')
for i in xrange(10000):
   fileObject.write(databuf)
   fileObject.flush()
   os.fsync(fileObject.fileno())
fileObject.close()    

但是显示了消息:

  AttributeError: 'SFTPFile' object has no attribute 'fileno'

如果我想强制将文件同步写入磁盘, 我能做什么?

【问题讨论】:

    标签: python ssh paramiko fsync


    【解决方案1】:

    根据文档:

    http://docs.paramiko.org/en/1.15/api/sftp.html#paramiko.sftp_file.SFTPFile

    SFTPFile 没有您尝试调用的方法。唯一可用的方法如下:

    check(hash_algorithm, offset=0, length=0, block_size=0)
    chmod(mode)
    chown(uid, gid)
    close()
    flush()
    gettimeout()
    next()
    prefetch()
    read(size=None)
    readline(size=None)
    readlines(sizehint=None)
    readv(chunks)
    set_pipelined(pipelined=True)
    setblocking(blocking)
    settimeout(timeout)
    stat()
    tell()
    truncate(size)
    utime(times)
    write(data)
    writelines(sequence)
    xreadlines()
    

    file.fileno() (https://docs.python.org/2/library/stdtypes.html#file.fileno) 只能从 python 文件流中调用,并且您的 sftp.open() 不会返回与 file.open() 相同类型的对象。

    如果我想立即强制将文件写入磁盘,我该怎么办?

    如果我没看错的话,我会说你会想读,或者读行,然后把它写到一个单独的 python 文件对象中,你可以在你所在的机器上操作它,然后写它返回到 SFTPFile 以通过适当的操作回发到服务器。

    【讨论】:

    • 对不起,我的意思是我想问'如果我想强制将文件同步写入磁盘,我该怎么办?'
    • 所以,为了确保我理解,您是指磁盘和服务器文件?
    • 我想确保所有数据都写入远程机器的磁盘,而不是远程机器的缓存
    【解决方案2】:

    os.fsync() 不会将文件写入远程机器上的磁盘。 os 模块只能影响本地机器所做的事情。如果您可以发出一个远程命令来同步远程机器上的文件,那么您可以在“fileObject.flush()”之后发出它。像这样的东西(这是从 paramico 文档 [http://docs.paramiko.org/en/1.15/api/agent.html][1] 直接复制和粘贴):

    session = client.get_transport().open_session()
    # Forward local agent
    AgentRequestHandler(session)
    # Commands executed after this point will see the forwarded agent on
    # the remote end.
    session.exec_command("YOU SYNC COMMAND, TO BE EXECUTED REMOTELY, HERE")
    

    【讨论】:

      猜你喜欢
      • 2016-12-12
      • 1970-01-01
      • 2014-11-29
      • 2015-05-25
      • 2023-03-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多