Search code examples
sftp

Delete files older than one day with SFTP in remote server


I want to establish a cron job in order to delete some files from a remote server in which I have only SFTP access. I don't have any shell access. What is the best way to connect to the remote server and do that? I have installed sshpass and did something like this:

sshpass -p pass sftp user@host

But how can I pass commands in order to list the old files and delete them?


Solution

  • It's rather difficult to implement this using the OpenSSH sftp client.

    You would have to:

    • list the directory using ls -l command;
    • parse the results (in shell or other script) to find names and times;
    • filter the files you want;
    • generate another sftp script to remove (rm) the files you found.

    A way easier and more reliable would be to give up on the command-line sftp. Instead, use your favorite scripting language (Python, Perl, PHP) and its native SFTP implementation.

    For an example, see:
    Python SFTP download files older than x and delete networked storage