I have two servers A and B. I'm suppose to send, let said an image file, from server A to another server B. But before server A could send the file over I would like to check if a similar file exist in server B. I try using os.path.exists() and it does not work.
我有两个服务器A和B.我想发送一个图像文件,从服务器A发送到另一个服务器B.但是在服务器A可以发送文件之前,我想检查服务器中是否存在类似的文件B.我尝试使用os.path.exists()并且它不起作用。
print os.path.exists('ubuntu@serverB.com:b.jpeg')
The result return a false even I have put an exact file on server B. I'm not sure whether is it my syntax error or is there any better solution to this problem. Thank you
即使我在服务器B上放了一个确切的文件,结果也会返回false。我不确定这是我的语法错误还是有更好的解决方案来解决这个问题。谢谢
1 个解决方案
#1
16
The os.path
functions only work on files on the same computer. They operate on paths, and ubuntu@serverB.com:b.jpeg
is not a path.
os.path函数仅适用于同一台计算机上的文件。它们在路径上运行,并且ubuntu @ serverB.com:b.jpeg不是路径。
In order to accomplish this, you will need to remotely execute a script. Something like this will work, usually:
为了实现此目的,您需要远程执行脚本。这样的东西通常会起作用:
def exists_remote(host, path):
"""Test if a file exists at path on a host accessible with SSH."""
status = subprocess.call(
['ssh', host, 'test -f {}'.format(pipes.quote(path))])
if status == 0:
return True
if status == 1:
return False
raise Exception('SSH failed')
So you can get if a file exists on another server with:
因此,如果文件存在于另一台服务器上,您可以获得:
if exists_remote('ubuntu@serverB.com', 'b.jpeg'):
# it exists...
Note that this will probably be incredibly slow, likely even more than 100 ms.
请注意,这可能会非常慢,甚至可能超过100毫秒。
#1
16
The os.path
functions only work on files on the same computer. They operate on paths, and ubuntu@serverB.com:b.jpeg
is not a path.
os.path函数仅适用于同一台计算机上的文件。它们在路径上运行,并且ubuntu @ serverB.com:b.jpeg不是路径。
In order to accomplish this, you will need to remotely execute a script. Something like this will work, usually:
为了实现此目的,您需要远程执行脚本。这样的东西通常会起作用:
def exists_remote(host, path):
"""Test if a file exists at path on a host accessible with SSH."""
status = subprocess.call(
['ssh', host, 'test -f {}'.format(pipes.quote(path))])
if status == 0:
return True
if status == 1:
return False
raise Exception('SSH failed')
So you can get if a file exists on another server with:
因此,如果文件存在于另一台服务器上,您可以获得:
if exists_remote('ubuntu@serverB.com', 'b.jpeg'):
# it exists...
Note that this will probably be incredibly slow, likely even more than 100 ms.
请注意,这可能会非常慢,甚至可能超过100毫秒。