[linux] How to pass password to scp?

I know it is not recommended, but is it at all possible to pass the user's password to scp?

I'd like to copy a file via scp as part of a batch job and the receiving server does, of course, need a password and, no, I cannot easily change that to key-based authentication.

This question is related to linux scp io-redirection

The answer is


All the solutions mentioned above can work only if you the app installed or you should have the admin rights to install except or sshpass.

I found this very useful link to simply start the scp in Background.

$ nohup scp file_to_copy user@server:/path/to/copy/the/file > nohup.out 2>&1

https://charmyin.github.io/scp/2014/10/07/run-scp-in-background/


Nobody mentioned it, but Putty scp (pscp) has a -pw option for password.

Documentation can be found here: https://the.earth.li/~sgtatham/putty/0.67/htmldoc/Chapter5.html#pscp


Here is an example of how you do it with expect tool:

sub copyover {
    $scp = Expect->spawn("/usr/bin/scp ${srcpath}/$file $who:${destpath}/$file");
    $scp->expect(30,"ssword: ") || die "Never got password prompt from $dest:$!\n";
    print $scp 'password' . "\n";
    $scp->expect(30,"-re",'$\s') || die "Never got prompt from parent system:$!\n";
    $scp->soft_close();
    return;
}

Once you set up ssh-keygen as explained above, you can do

scp -i ~/.ssh/id_rsa /local/path/to/file [email protected]:/path/in/remote/server/

If you want to lessen typing each time, you can modify your .bash_profile file and put

alias remote_scp='scp -i ~/.ssh/id_rsa /local/path/to/file [email protected]:/path/in/remote/server/

Then from your terminal do source ~/.bash_profile. Afterwards if you type remote_scp in your terminal it should run the scp command without password.


An alternative would be add the public half of the user's key to the authorized-keys file on the target system. On the system you are initiating the transfer from, you can run an ssh-agent daemon and add the private half of the key to the agent. The batch job can then be configured to use the agent to get the private key, rather than prompting for the key's password.

This should be do-able on either a UNIX/Linux system or on Windows platform using pageant and pscp.


If you are connecting to the server from Windows, the Putty version of scp ("pscp") lets you pass the password with the -pw parameter.

This is mentioned in the documentation here.


curl can be used as a alternative to scp to copy a file and it supports a password on the commandline.

curl --insecure --user username:password -T /path/to/sourcefile sftp://desthost/path/

  1. Make sure password authentication is enabled on the target server. If it runs Ubuntu, then open /etc/ssh/sshd_config on the server, find lines PasswordAuthentication=no and comment all them out (put # at the start of the line), save the file and run sudo systemctl restart ssh to apply the configuration. If there is no such line then you're done.
  2. Add -o PreferredAuthentications="password" to your scp command, e.g.:
    scp -o PreferredAuthentications="password" /path/to/file user@server:/destination/directory
    

I found this really helpful answer here.

rsync -r -v --progress -e ssh user@remote-system:/address/to/remote/file /home/user/

Not only you can pass there the password, but also it will show the progress bar when copying. Really awesome.


  1. make sure you have "expect" tool before, if not, do it

    # apt-get install expect

  2. create the a script file with following content. (# vi /root/scriptfile)

    spawn scp /path_from/file_name user_name_here@to_host_name:/path_to

    expect "password:"

    send put_password_here\n;

    interact

  3. execute the script file with "expect" tool

    # expect /root/scriptfile


just generate a ssh key like:

ssh-keygen -t rsa -C "[email protected]"

copy the content of ~/.ssh/id_rsa.pub and lastly add it to the remote machines ~/.ssh/authorized_keys

make sure remote machine have the permissions 0700 for ~./ssh folder and 0600 for ~/.ssh/authorized_keys


Here's a poor man's Linux/Python/Expect-like example based on this blog post: Upgrading simple shells to fully interactive TTYs. I needed this for old machines where I can't install Expect or add modules to Python.

Code:

(
    echo 'scp [email protected]:./install.sh .'
    sleep 5
    echo 'scp-passwd'
    sleep 5
    echo 'exit'
) |

python -c 'import pty; pty.spawn("/usr/bin/bash")'

Output:

scp [email protected]:install.sh .
bash-4.2$ scp [email protected]:install.sh .
Password: 
install.sh                                 100%   15KB 236.2KB/s   00:00    
bash-4.2$ exit
exit

steps to get sshpass For rhel/centos 6 :

# wget http://epel.mirror.net.in/epel/6/i386/epel-release-6-8.noarch.rpm
# rpm -ivh epel-release-6-8.noarch.rpm
# yum install sshpass

source: https://community.mapr.com/thread/9040


You can use the 'expect' script on unix/terminal

For example create 'test.exp' :

#!/usr/bin/expect
        spawn scp  /usr/bin/file.txt root@<ServerLocation>:/home
        set pass "Your_Password"
        expect {
        password: {send "$pass\r"; exp_continue}
                  }

run the script

expect test.exp 

I hope that helps.


You may use ssh-copy-id to add ssh key:

$which ssh-copy-id #check whether it exists

If exists:

ssh-copy-id  "user@remote-system"

In case if you observe a strict host key check error then use -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null options.

The complete example is as follows sshpass -p "password" scp -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null [email protected]:/tmp/from/psoutput /tmp/to/psoutput


Use sshpass:

sshpass -p "password" scp -r [email protected]:/some/remote/path /some/local/path

or so the password does not show in the bash history

sshpass -f "/path/to/passwordfile" scp -r [email protected]:/some/remote/path /some/local/path

The above copies contents of path from the remote host to your local.

Install :

  • ubuntu/debian
    • apt install sshpass
  • centos/fedora
    • yum install sshpass
  • mac w/ macports
    • port install sshpass
  • mac w/ brew
    • brew install https://raw.githubusercontent.com/kadwanev/bigboybrew/master/Library/Formula/sshpass.rb

Examples related to linux

grep's at sign caught as whitespace How to prevent Google Colab from disconnecting? "E: Unable to locate package python-pip" on Ubuntu 18.04 How to upgrade Python version to 3.7? Install Qt on Ubuntu Get first line of a shell command's output Cannot connect to the Docker daemon at unix:/var/run/docker.sock. Is the docker daemon running? Run bash command on jenkins pipeline How to uninstall an older PHP version from centOS7 How to update-alternatives to Python 3 without breaking apt?

Examples related to scp

Copying files from server to local computer using SSH How to copy a file from remote server to local machine? scp files from local to remote machine error: no such file or directory How to download a file from my server using SSH (using PuTTY on Windows) Using putty to scp from windows to Linux SCP Permission denied (publickey). on EC2 only when using -r flag on directories scp copy directory to another server with private key auth Run local python script on remote server Send password when using scp to copy files from one server to another How does `scp` differ from `rsync`?

Examples related to io-redirection

UTF-8 output from PowerShell Redirecting Output from within Batch file Redirect stderr to stdout in C shell Bash write to file without echo? What is /dev/null 2>&1? How to redirect both stdout and stderr to a file Redirect all output to file in Bash Send string to stdin Find and replace in file and overwrite file doesn't work, it empties the file How do I capture all of my compiler's output to a file?