ChatGPT解决这个技术问题 Extra ChatGPT

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.

See also (later) question: stackoverflow.com/questions/1462284/… where one answer mentions another possible way to do this. (NB: this is not a duplicate question - it is the original which the other duplicates.)
Very closely related: Pass a password to ssh in pure bash
Instead of login via scp and copy, you can first setup a master connection with ssh, then run scp to copy the file via the master connection, without password. See unix.stackexchange.com/a/2869/17823

j
jbaums

Use sshpass:

sshpass -p "password" scp -r user@example.com:/some/remote/path /some/local/path

or so the password does not show in the bash history

sshpass -f "/path/to/passwordfile" scp -r user@example.com:/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

apt install sshpass

centos/fedora yum install sshpass

yum install sshpass

mac w/ macports port install sshpass

port install sshpass

mac w/ brew brew install https://raw.githubusercontent.com/kadwanev/bigboybrew/master/Library/Formula/sshpass.rb

brew install https://raw.githubusercontent.com/kadwanev/bigboybrew/master/Library/Formula/sshpass.rb


On Ubuntu 12.04 it only worked for me with single quotes over the password (e.g. 'password' instead of "password").
@odedfos, yes you need to use single quotes because some password generated chars can have a special interpretation in double quoted string interpolation
This is how you install sshpass apt-get install sshpass
On CentOS it's yum -y install sshpass
The most secure way to do this is with a password file, like this: sshpass -f passwdfile` scp [...]. This way, the password won't show up in ps` listings, etc. and you can protect the password with file permissions.
m
mustafaturan

just generate a ssh key like:

ssh-keygen -t rsa -C "your_email@youremail.com"

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


As I wrote: No, I cannot easily switch to key-based authentication.
Do you mean .authorized_keys rather than . authorization_keys?
A valid use for this would be a bash script that does multiple scp/ssh calls to a server where you want to ask the user for the password for the remote server. The password will then not show in history and you still have the befit of challenging for the password... but only once. I don't want to use a key file because I want to still authenticate the script user.
Another valid use would be if you cannot easily enable key-based authentication on the target. Example: One of the main NAS producers - Synology with their DSM 6.0 - does not support it even in 2016. Sure, you could mess with configuration files and hope an update won't just overwrite it again (updating DSM frequently does break custom modifications). Sometimes - especially when the OP expressly writes they're already aware it's not optimal - people just need a solution.
You should use ssh-copy-id -i ~/.ssh/id_rsa.pub <remote_server> to copy the key on the remote server
H
Haldean Brown

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.


Show an example, please.
Also, might want to add C:\Program Files (x86)\PuTTY to your path to use these commands.
@SDsolar here's a syntax example: pscp -pw 'MyPa$$word' username@servername:/somedir/somefile ~/somedest (I hate using putty like this, but it works)
@geneorama password worked for me but only without the single quotations.. thanks..
j
joelittlejohn

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


Link to expect.nist.gov is broken. Maybe this?: expect.sourceforge.net
sudo apt-get install expect
>> brew info sshpass Error: No available formula with the name "sshpass" We won't add sshpass because it makes it too easy for novice SSH users to ruin SSH's security. ;)
M
MBerg

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/

It quite slower than 'scp' but it does the job fine.
I found this to be faster when the destination is configured with a huge password prompt delay. scp has to wait 30+ seconds to let me put in a password, but curl worked immediately.
@Ghost8472 configured yes, but sometimes this delay is resolving the hostname, and also happens for sftp.
I got "curl: (1) Protocol "sftp" not supported or disabled in libcurl"
I got an error saying that curl doesn't recognize -T as a parameter.
P
Prabhjeet

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.


Prerequisite: sudo apt-get install expect
R
RomanHotsiy

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"

Superb. Simple, works, and no 3rd-party packages or ssh-keygen setup required.
g
glenn jackman

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

This is in perl, sorry i didn't write that. (5 years ago :) )
S
SDsolar

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


It was mentioned in user524607's answer 5 years ago.
Found it, and am adding C:\Program Files (x86)\PuTTY to my path.
Under WINE ? on Windows use plink. BTW people putty-tools is a package.
h
hi15

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

scp -i ~/.ssh/id_rsa /local/path/to/file remote@ip.com:/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 remote@ip.com:/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.


F
Finesse

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. Add -o PreferredAuthentications="password" to your scp command, e.g.: scp -o PreferredAuthentications="password" /path/to/file user@server:/destination/directory


How do you indicate the actual password though?
@Osmar You'll be prompted for password when you run the command
J
JohnMudd

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 jmudd@mysite.com:./install.sh .'
    sleep 5
    echo 'scp-passwd'
    sleep 5
    echo 'exit'
) |

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

Output:

scp jmudd@mysite.com:install.sh .
bash-4.2$ scp jmudd@mysite.com:install.sh .
Password: 
install.sh                                 100%   15KB 236.2KB/s   00:00    
bash-4.2$ exit
exit

K
Kevin Chui

make sure you have "expect" tool before, if not, do it # apt-get install expect 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 execute the script file with "expect" tool # expect /root/scriptfile


R
Robert

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.


S
Sachin Rastogi

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 root@domain-name.com:/tmp/from/psoutput /tmp/to/psoutput


R
Rakesh Raushan

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 , 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!


v
vishal sahu

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/


r
rjray

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.


The question said he can't use key-based authentication.
Also, if it were me, I assume I can't alter the other server - all I want is to copy a file.
Y
Yash

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/


How would running the scp in the background input the password??
C
Community

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.


and how exactly are you providing password here?