且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用Python检查远程SSH服务器上的文件是否存在

更新时间:2023-08-21 20:06:58

os.path中功能只对文件上工作同一台电脑。它们在路径上运行,而 ubuntu@serverB.com:b.jpeg 不是路径。



为了做到这一点,您将需要远程执行一个脚本。像这样的东西可以工作,通常:

$ $ p $ def exists_remote(host,path):
文件存在于可通过SSH访问的主机上的路径上。
status = subprocess.call(
['ssh',host,'test -f {}'。format(pipes.quote(path ))])
if status == 0:
return True
if status == 1:
return False
异常('SSH失败')

所以你可以得到一个文件是否存在于另一台服务器上:

 如果exists_remote('ubuntu@serverB.com','b.jpeg'):
#它存在...

请注意,这可能会很慢,甚至可能超过100毫秒。

$ b

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.

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

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.

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.