Argelbargel
Argelbargel

Reputation: 6210

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.

Upvotes: 478

Views: 1244167

Answers (22)

KevinS
KevinS

Reputation: 8627

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/ homebrew
  • brew install sshpass

Upvotes: 772

dahe
dahe

Reputation: 846

Working fine with powershell and Posh-SSH. Powershell core should be supported

Import-Module "C:\tmp\Posh-SSH\3.0.8\Posh-SSH.psd1" # https://github.com/darkoperator/Posh-SSH/releases

# Connect with pubkey authentication, providing the Passphrase non-interactive, and accepting any remote pubkey
$sftpSession = New-SFTPSession -ComputerName example.com -Credential $keyFilePassphrase -KeyFile "C:\Path\To\private_key" -AcceptKey

# Write file to remote
Set-SFTPItem -SessionId $sftpSession.SessionID -Path C:\tmp\test.txt -Destination "/home/user/"

You could also use expect:

#!/usr/bin/expect

spawn scp user@host:/source user@host2:/target
expect "password"
send -- "$PASSWORD\n"
interact

Install expect and run the script

sudo apt install expect -y
chmod +x /usr/local/bin/update-file.exp
/usr/local/bin/update-file.exp

Upvotes: 0

randompast
randompast

Reputation: 693

Since not using key based auth isn't in the title, the following steps will help users who can switch to key based auth. It skips passwords for scp and ssh.

Copy your ssh public key to the server (careful about not overwriting authorized keys)

scp ~/.ssh/id_rsa.pub user@remoteIP:~/.ssh/authorized_keys

Change the permissions:

chmod 600 authorized_keys

Follow a guide like this for more details: https://idratherbewriting.com/jekylldoctheme-separate-outputs/mydoc/mydoc_no_password_prompts_scp.html

Upvotes: -1

Rakesh Raushan
Rakesh Raushan

Reputation: 1

One easy way I do this:

Use the same scp cmd as you use with ssh keys i.e

scp -C -i <path_to opens sshkey> <'local file_path'> user@<ip_address_VM>: <'remote file_path’>

for transferring file from local to remote

but instead of providing the correct <path_to_opensshkey>, use some garbage path. Due to wrong key path you will be asked for password instead and you can simply pass the password now to get the work done!

Upvotes: -2

vishal sahu
vishal sahu

Reputation: 29

You can use below steps. This works for me!

Step1- create a normal file suppose "fileWithScpPassword" which contains the ssh password for the destination server.

Step2- use sshpaas -f followed by password file name and then normal scp command.

sshpass -f "fileWithScpPassword" scp /filePathToUpload user@ip:/destinationPath/

Upvotes: -1

Sudheer Mareddy
Sudheer Mareddy

Reputation: 9

copy files from one server to other server ( on scripts)

Install putty on ubuntu or other Linux machines. putty comes with pscp. we can copy files with pscp.

apt-get update
apt-get install putty 
echo n |  pscp -pw "Password@1234" -r user_name@source_server_IP:/copy_file_path/files /path_to_copy/files

For more options see pscp help.

Upvotes: 0

Espo
Espo

Reputation: 41909

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;
}

Upvotes: 10

Sachin Rastogi
Sachin Rastogi

Reputation: 477

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

Upvotes: -2

Finesse
Finesse

Reputation: 10801

  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
    

Upvotes: 0

JohnMudd
JohnMudd

Reputation: 13813

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

Upvotes: 3

Yash
Yash

Reputation: 15

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/

Upvotes: -6

Pat Notz
Pat Notz

Reputation: 214176

You can script it with a tool like expect (there are handy bindings too, like Pexpect for Python).

Upvotes: 42

MBerg
MBerg

Reputation: 551

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/

Upvotes: 55

melatonin15
melatonin15

Reputation: 2269

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.

Upvotes: 3

galushka
galushka

Reputation: 85

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

Upvotes: 6

gWay
gWay

Reputation: 1235

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.

Upvotes: 65

Shen JI
Shen JI

Reputation: 137

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"

Upvotes: 12

mustafaturan
mustafaturan

Reputation: 2341

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

Upvotes: 73

Kevin Chui
Kevin Chui

Reputation: 167

  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

Upvotes: 0

valk
valk

Reputation: 9874

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.

Upvotes: -12

Prabhjeet
Prabhjeet

Reputation: 259

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.

Upvotes: 24

rjray
rjray

Reputation: 6653

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.

Upvotes: -3

Related Questions