Automate scp file transfer using a shell script

前端 未结 13 1016
误落风尘
误落风尘 2020-11-30 17:24

I have some n number of files in a directory on my unix system. Is there a way to write a shellscript that will transfer all those files via scp to a specified remote system

相关标签:
13条回答
  • 2020-11-30 17:54

    you could also use rsync. It seems to work better for multiple files than scp IMHO.

    rsync -avzh /path/to/dir/ user@remote:/path/to/remote/dir/

    Update

    You can use rsync via ssh by adding the '-e' switch:

    rsync -avzh -e ssh /path/do/dir/ user@remote:/path/to/remote/dir/
    0 讨论(0)
  • 2020-11-30 17:56
    #!/usr/bin/expect -f
    spawn scp -r BASE.zip abhishek@192.168.1.115:/tmp
    expect "password:"
    send "wifinetworks\r"
    expect "*\r"
    expect "\r"
    
    0 讨论(0)
  • 2020-11-30 17:58

    rsync is a program that behaves in much the same way that rcp does, but has many more options and uses the rsync remote-update protocol to greatly speed up file transfers when the destination file is being updated.

    The rsync remote-update protocol allows rsync to transfer just the differences between two sets of files across the network connection, using an efficient checksum-search algorithm described in the technical report that accompanies this package.


    Copying folder from one location to another

       #!/usr/bin/expect -f   
       spawn rsync -a -e ssh username@192.168.1.123:/cool/cool1/* /tmp/cool/   
       expect "password:"   
       send "cool\r"   
       expect "*\r"   
       expect "\r"  
    
    0 讨论(0)
  • 2020-11-30 18:02

    Instead of hardcoding password in a shell script, use SSH keys, its easier and secure.

    $ scp -i ~/.ssh/id_rsa *.derp devops@myserver.org:/path/to/target/directory/
    

    assuming your private key is at ~/.ssh/id_rsa and the files you want to send can be filtered with *.derp

    To generate a public / private key pair :

    $ ssh-keygen -t rsa
    

    The above will generate 2 files, ~/.ssh/id_rsa (private key) and ~/.ssh/id_rsa.pub (public key)

    To setup the SSH keys for usage (one time task) : Copy the contents of ~/.ssh/id_rsa.pub and paste in a new line of ~devops/.ssh/authorized_keys in myserver.org server. If ~devops/.ssh/authorized_keys doesn't exist, feel free to create it.

    A lucid how-to guide is available here.

    0 讨论(0)
  • 2020-11-30 18:06

    why don't you try this?

    password="your password"
    username="username"
    Ip="<IP>"
    sshpass -p "$password" scp /<PATH>/final.txt $username@$Ip:/root/<PATH>
    
    0 讨论(0)
  • 2020-11-30 18:08

    The command scp can be used like a traditional UNIX cp. SO if you do :

    scp -r myDirectory/ mylogin@host:TargetDirectory
    

    will work

    0 讨论(0)
提交回复
热议问题