How to filter files when using scp to copy dir recursively?

前端 未结 9 1282
醉酒成梦
醉酒成梦 2021-01-29 20:00

I need to copy all the .class files from server to local with all dir reserved. e.g. server:/usr/some/unknown/number/of/sub/folders/me.class will be /usr/proj

相关标签:
9条回答
  • 2021-01-29 20:30

    If you indeed wanna use scp, there's a indirect way.Say we want to copy all .jpg file under local folder '/src' to folder '/dst' in remote server 10.1.1.2:

    #make a clean temp folder
    mkdir /tmp/ttt
    #copy all .jpg file and retain folder structure as-is
    find /src -type f -name *.jpg -exec cp --parents \{\} /tmp/ttt \;
    #copy to remote target folder as-is and retain original time attributes
    scp -rp /tmp/ttt/* 10.1.1.2:/dst
    #if copy ok, remove temp folder
    rm -rf /tmp/ttt
    
    0 讨论(0)
  • 2021-01-29 20:35

    Since you can scp you should be ok to ssh,
    either script the following or login and execute...

    # After reaching the server of interest
    cd /usr/some/unknown/number/of/sub/folders
    tar cfj pack.tar.bz2 $(find . -type f -name *.class)
    

    return back (logout) to local server and scp,

    # from the local machine
    cd /usr/project/backup/some/unknown/number/of/sub/folders
    scp you@server:/usr/some/unknown/number/of/sub/folders/pack.tar.bz2 .
    tar xfj pack.tar.bz2
    

    If you find the $(find ...) is too long for your tar change to,

    find . -type f -name *.class | xargs tar cfj pack.tar.bz2
    

    Finally, since you are keeping it in /usr/project/backup/,
    why bother extraction? Just keep the tar.bz2, with maybe a date+time stamp.

    0 讨论(0)
  • 2021-01-29 20:35

    With ssh key based authentication enabled, the following script would work.

    for x in `ssh user@remotehost 'find /usr/some -type f -name *.class'`; do y=$(echo $x|sed 's/.[^/]*$//'|sed "s/^\/usr//"); mkdir -p /usr/project/backup$y; scp $(echo 'user@remotehost:'$x) /usr/project/backup$y/; done
    
    0 讨论(0)
提交回复
热议问题