Last updated on August 8, 2020 by Dan Nanni
There are circumstances where you want to test if a file exists somewhere on a remote Linux server (e.g., /var/run/test_daemon.pid
), without logging in to the server interactively. For example, you may want your script to behave differently depending on whether or not a specific file exists on a remote server.
In this tutorial, I will show you how to check if a remote file exists in different script languages (e.g., bash shell, Perl, Python).
The approach described here will use ssh to access a remote host. You first need to enable key-based SSH authentication to the remote host, so that your script can access a remote host in non-interactive batch mode. You also need to make sure that SSH login has read permission on the file to check. Assuming that you have finished these two steps, you can write scripts like the following examples.
#!/bin/bash ssh_host="xmodulo@remote_server" file="/var/run/test.pid" if ssh $ssh_host test -e $file; then echo $file exists else echo $file does not exist fi
#!/usr/bin/perl my $ssh_host = "xmodulo@remote_server"; my $file = "/var/run/test.pid"; system "ssh", $ssh_host, "test", "-e", $file; my $rc = $? >> 8; if ($rc) { print "$file doesn't existn"; } else { print "$file existsn"; }
#!/usr/bin/python import subprocess import pipes ssh_host = 'xmodulo@remote_server' file = '/var/run/test.pid' resp = subprocess.call( ['ssh', ssh_host, 'test -e ' + pipes.quote(file)]) if resp == 0: print ('%s exists' % file) else: print ('%s does not exist' % file)
This website is made possible by minimal ads and your gracious donation via PayPal or credit card
Please note that this article is published by Xmodulo.com under a Creative Commons Attribution-ShareAlike 3.0 Unported License. If you would like to use the whole or any part of this article, you need to cite this web page at Xmodulo.com as the original source.
Xmodulo © 2021 ‒ About ‒ Write for Us ‒ Feed ‒ Powered by DigitalOcean