Search code examples
pythonscpos.system

How to get the latest file with os.system using scp in python?


I want to use python os.system library to get/scp the latest folder from a remote remote UNIX directory, which is a folder system with names including datetime such as :

[usr1@server1 stats_from_dir]$ pwd
/tmp/dir1/stats_from_dir

[usr1@server1 stats_from_dir]$ ls -alrth
drwxr-x---  2  23K Aug 28 12:50 pmexport_20200825
drwxr-x---  2  23K Aug 28 12:50 pmexport_20200826
drwxr-x---  2  21K Aug 28 12:50 pmexport_20200827

I can get all the folders like this ;

import os
    
get_files = 'scp -r [email protected]:/tmp/dir1/stats_from_dir/* /dir2/.'
    
os.system(get_files)

But how can I get only latest folder? Is there any way to do this within os.system library with paramters without using other libraries such as paramiko, subprocess ..etc ?


Solution

  • Try this one:

    import os
        
    get_files = "scp -r [email protected]:/tmp/dir1/stats_from_dir/$(ssh [email protected] 'ls -t /tmp/dir1/stats_from_dir/ | head -1') /dir2/."
        
    os.system(get_files)