在Python中,如何同步在远程计算机上编写文件?

时间:2015-10-08 03:01:47

标签: python ssh paramiko fsync

现在我需要打开一个远程文件来写东西,代码如下:

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'

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

2 个答案:

答案 0 :(得分: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进行正确的操作以回发到服务器。

答案 1 :(得分:1)

os.fsync()不会将文件写入远程计算机上的磁盘。 os模块只能影响本地机器的功能。如果您可以发出一个远程命令来同步远程计算机上的文件,那么您可以在“fileObject.flush()”之后发出它。这样的东西(这是paramico docs [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")