user670809
user670809

Reputation: 181

How to copy file from remote server in shell script?

I need write script for copy remote server files to here automatically on server backend. something like below:

#!/usr/bin/expect -f   
  spawn /usr/local/bin/scpdata.sh
  set timeout 3000
  expect "[email protected]'s password:"
  set timeout 3000
  send "xxxx"
  set timeout 3000
  send "exit\r"
  expect eof

scpdata.sh file

#!/bin/bash
  scp [email protected]:/tmp/11-03-15_03:00:01.tar.gz /tmp

But this not work, where is problem and how to do it? Please help

Upvotes: 2

Views: 9759

Answers (2)

glenn jackman
glenn jackman

Reputation: 246807

  1. You never "hit enter" when you send the password: send "xxxx\r"
  2. set timeout 3000 does not actually pause -- it sets the timeout value to 3000 seconds (50 minutes). If you need to pause, sleep 3.
    • If your expect patterns are correct, you almost never need to explicitly sleep. Use exp_internal 1 to debug your patterns.
  3. Set up ssh keys and you don't need the expect script at all.

Upvotes: 0

Jan Hudec
Jan Hudec

Reputation: 76266

I'd suggest you use public key authentication instead (generate public/private keypair with ssh-keygen on the client, add the public (.ssh/id.pub by default) key to .ssh/authorized_keys on the server—see the man page). Than you can either:

  • Give the passphrase for the key in advance using ssh-agent, or
  • use a key without passphrase.

In the later case I suggest you limit the key to a particular command. I am not sure how to set a command for scp, but

ssh [email protected] 'cat /tmp/11-03-15_03:00:01.tar.gz' > /tmp/11-03-15_03:00:01.tar.gz

is equivalent. You just write command="the command" in front of your key in .ssh/authorized_keys. Than the ssh server, when authorized with this key, will always run specified command no matter what was given on ssh command line. This limits the damage an attacker could do if they got access to your passphrase-less key.

If you need the name of file to get to vary, you will need to write a script on the server side, that will pull out the name of $SSH_ORIGINAL_COMMAND (that's where the server-side script gets whatever was given on ssh command-line), check that it's one of the permitted files and cat it.

Upvotes: 2

Related Questions