在Python中,如何在远程机器上同步写入文件?

在Python中,如何在远程机器上同步写入文件?,python,ssh,paramiko,fsync,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(fullF

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

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'
如果我想强制文件同步写入磁盘,
我能做什么?

根据文档:

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()
()只能从python文件流中调用,并且您的
sftp.open()
返回的对象类型与
file.open()
返回的对象类型不同

如果我想立即强制将文件写入磁盘,我能做什么

如果我读对了,我会说您希望读取或读取行,然后将其写入一个单独的python文件对象,您将在您所在的机器上对其进行操作,然后将其写入一个SFTPFile,以执行正确的操作,并将其发回服务器。

os.fsync()不会将文件写入远程计算机上的磁盘。操作系统模块只能影响本地计算机的操作。如果您可以发出远程命令来同步远程计算机上的文件,那么您可以在“fileObject.flush()”之后发出该命令。类似这样的内容(这是从paramico docs[]直接复制和粘贴):


对不起,我的意思是我想问‘如果我想强制文件同步写入磁盘,我能做些什么?’所以,为了确保我理解,你的意思是同时写入磁盘和服务器文件?我想确保所有数据都写入远程机器的磁盘,而不是远程机器的缓存
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")