- Копирование файлов scp
- Что такое SCP?
- Копирование файлов scp
- Выводы
- Как передать пароль в scp?
- 14 ответов
- Using scp with Passwords [duplicate]
- 2 Answers 2
- Send password when using scp to copy files from one server to another [duplicate]
- 6 Answers 6
- Doing Private Public Key Authentication on Windows
- How to pass password to scp command used in bash script? [duplicate]
- 6 Answers 6
Копирование файлов scp
Если у вас есть домашний сервер или сервер в интернете, то вам понадобится способ для безопасного перемещения файлов между машинами. Между локальными машинами мы могли бы просто переносить данные с помощью флешки, но на удаленный сервер нужно передавать данные только через сеть. Есть много способов реализации этой задачи.
В этой статье мы рассмотрим как выполняется копирование файлов с помощью утилиты scp (Secure Copy Command), а также что из себя представляет команда Linux scp. При передаче файлы шифруются, так что больше никто не сможет получить к ним доступ и самое интересное, что вам не нужно настраивать FTP или другое дополнительное программное обеспечение. Будет достаточно сервера SSH.
Что такое SCP?
Команда scp — это утилита, которая работает по протоколу SSH, а значит, все что вам нужно для передачи файла на компьютер, это чтобы на нем был запущен SSH сервер, а также вы должны знать логин и пароль для подключения к нему. С помощью команды scp вы можете не только перемещать файлы между локальной и удаленной системой, но и между двумя удаленными системами. Для этого тоже будет достаточно знать пароли от них. И в отличие от Rsync вам не нужно авторизоваться на одном из серверов.
Копирование файлов scp
Эта статья рассчитана в первую очередь на начинающих, поэтому я попытаюсь объяснять все как можно подробнее. Перед тем, как мы перейдем к практике, нужно рассмотреть общий синтаксис команды:
$ scp опции пользователь1@хост1 : файл пользователь2@хост2: файл
Опции утилиты больше касаются протокола SSH и настраивают общее ее поведение. Дальше следует адрес первого и второго файла. Каждый из них может быть расположен как на локальной, так и на удаленной машине. А теперь рассмотрим основные опции, которые могут нам понадобиться:
- -1 — использовать протокол SSH1;
- -2 — использовать протокол SSH2;
- -B — пакетный режим для передачи нескольких файлов;
- -C — включить сжатие;
- — l — установить ограничение скорости в кбит/сек;
- -o — задать нужную опцию SSH;
- -p — сохранять время модификации;
- -r — рекурсивное копирование директорий;
- -v — более подробный режим.
scp /home/sergiy/file root@losst.ru:/root/
В качестве пользователя нужно использовать любого пользователя, который есть на сервере. Вместо IP вы можете также домен сервера. Только необходимо, чтобы у выбранного пользователя были права записи в указанную папку.
С помощью опции -r вы можете скопировать на удаленную машину целый каталог. Команда будет выглядеть вот так:
scp -r /home/sergiy/photos root@losst.ru:/root/
Убедитесь, что у исходного каталога нет косой черты, а у каталога назначения она должна обязательно быть. Немного изменив синтаксис с косой чертой можно передать все файлы из каталога на удаленный сервер:
scp -r /home/sergiy/photos/* root@losst.ru:/root/
Если поменять местами локальный путь и сервер, то вы сможете копировать файлы scp c удаленного сервера на локальный компьютер:
scp root@losst.ru:/root/file /home/sergiy/
Таким же самым образом вы можете копирование файлов scp или папок с сервера:
scp -r root@losst.ru:/root/photos /home/sergiy/
Обратите внимание, что папка, в которую вы собираетесь копировать должна завершаться косой чертой, иначе папка, которую вы копируете запишется вместо той, в которую нужно скопировать.
Чтобы скачать файл scp из одного сервера на другой, просто необходимо указать данные аутентификации на каждом из них. Например, скопируем один файл:
scp root@losst.ru:/home/root/index.html root@losst.ru:/home/root/www/
Скопируем папку с того же удаленного сервера:
scp root@losst.ru:/root/photos root@losst.ru:/home/root/www/
Выводы
В этой статье мы рассмотрели как выполняется передача файлов scp, как это работает и что вы можете сделать с помощью этой утилиты. Как вы видите, перемещать файлы с одного сервера на другой очень просто. В Linux достаточно понять основы чтобы начать работать эффективнее! А команда scp один из таких инструментов.
Источник
Как передать пароль в scp?
Я знаю, что это не рекомендуется, но можно ли вообще передать пароль пользователя в scp?
Я хотел бы скопировать файл через scp как часть пакетного задания, и принимающий сервер, конечно, нуждается в пароле, и нет, я не могу легко изменить это на аутентификацию на основе ключей.
14 ответов
вы можете написать его с помощью такого инструмента, как ожидал (есть удобные привязки тоже, как Pexpect для Python).
или так пароль не отображается в истории bash
выше копирует содержимое пути с удаленного хоста на локальный.
установка :
- 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
просто создайте ssh-ключ, например:
/.ssh/id_rsa.pub и, наконец, добавьте его в удаленные машины
убедитесь, что удаленная машина имеет разрешения 0700 for
./ssh folder и 0600 for
Если вы подключаетесь к серверу из Windows, Версия Putty scp («pscp») позволяет передать пароль с помощью .
вы можете использовать скрипт «expect» в unix/terminal
например, create ‘ test.exp’:
надеюсь, это поможет.
вот пример того, как вы это делаете с :
curl может использоваться в качестве альтернативы scp для копирования файла и поддерживает пароль в командной строке.
никто не упоминал об этом, но шпаклевка scp (pscp) имеет опцию-pw для пароля.
документацию можно найти здесь:https://the.earth.li /
убедитесь, что у вас есть» ожидать » инструмент, прежде чем, если нет, сделать это
# apt-get install expect
создайте файл сценария a со следующим содержимым. (# vi / root / scriptfile)
spawn scp /path_from/file_name user_name_here@to_host_name:/path_to
выполнить файл сценария с помощью инструмента «ожидать»
вы можете использовать ssh-copy-id чтобы добавить ключ ssh:
как только вы настроите ssh-keygen как описано выше, вы можете сделать
/.ssh/id_rsa /local/path/to/file remote@ip.com:/path/in/remote/server/
если вы хотите уменьшить набирать каждый раз, вы можете изменить свой .bash_profile файл и поставить
тогда с вашего терминала сделайте source
/.bash_profile . После этого, если вы наберете remote_scp в вашем терминале следует запустить без пароля.
альтернативой будет добавление открытой половины ключа пользователя в файл авторизованных ключей в целевой системе. В системе, из которой вы инициируете передачу, вы можете запустить демон ssh-agent и добавить закрытую половину ключа к агенту. Затем пакетное задание можно настроить на использование агента для получения закрытого ключа, а не на запрос пароля ключа.
Это должно быть возможно в системе UNIX / Linux или на платформе Windows с помощью pageant и программе pscp.
Источник
Using scp with Passwords [duplicate]
Can I input the password as a parameter to SCP rather than be prompted for it?
How can I save password,when copy a file using SCP? This question is similar, but answers deal with doing away with SSH password completely.
2 Answers 2
There are several options:
- using sshpass
Execute the command:
sudo apt install sshpass
sshpass — noninteractive ssh password provider
sshpass is a utility designed for running ssh using the mode referred to as «keyboard-interactive» password authentication, but in non-interactive mode.
ssh uses direct TTY access to make sure that the password is indeed issued by an interactive keyboard user. Sshpass runs ssh in a dedicated tty, fooling it into thinking it is getting the password from an interactive user.
The command to run is specified after sshpass’ own options. Typically it will be «ssh» with arguments, but it can just as well be any other command. The password prompt used by ssh is, however, currently hardcoded into sshpass.
- Using expect (or other script)
write a script which will inject the password once it will identify the ssh password prompt
- Using ssh with key-pair (instead of using password)
IMHO — This is the most secure way, and it doesn’t require using passwords.
Using public/private key in order to perform ssh or scp operation without having to enter a password.
Источник
Send password when using scp to copy files from one server to another [duplicate]
using scp to copy files from 1 unix server to another regularly and performing certain actions. to do this quickly I wish to use a unix script which does the scp and inputs the password required to complete the scp.
I have tried the expect command to send the password throught the unix command line however unable to achieve this so far.
I get these errors:
am I missing something?
6 Answers 6
Just pass with sshpass -p «your password» at the beginning of your scp command
You should use better authentication with open keys. In these case you need no password and no expect.
If you want it with expect , use this script (see answer Automate scp file transfer using a shell script ):
Also, you can use pexpect (python module):
One of the ways to get around login issues with ssh , scp , and sftp (all use the same protocol and sshd server) is to create public/private key pairings.
Some servers may disallow this, but most sites don’t. These directions are for Unix/Linux/Mac. As always, Windows is a wee bit different although the cygwin environment on Windows does follow these steps.
- On your machine, create your public/private key using ssh-keygen . This can vary from system to system, but the program should lead you through this.
- When ssh-keygen is finished, you will have a $HOME/.ssh directory on your machine. This directory will contain a public key and a private key. There will be two more files that are generated as you go along. One is known_hosts which contains the fingerprints of all known hosts you’ve logged into. The second will be called either authorized_keys or authorized_keys2 depending upon your implementation.
- If it’s not there already, log into the remote host, and run ssh-keygen there too. This will generate a $HOME/.ssh directory there as well as a private/public key pair. Don’t do this if the $HOME/.ssh directory already exists and has a public and private key file. You don’t want to regenerate it.
- On the remote server in the $HOME/.ssh directory, create a file called authorized_keys . In this file, put your public key. This public key is found on your $HOME/.ssh directory on your local machine. It will end with *.pub . Paste the contents of that into authorized_keys . If authorized_keys already exists, paste your public key in the next line.
Now, when you log in using ssh , or you use scp or sftp , you will not be required to enter a password. By the way, the user IDs on the two machines do not have to agree. I’ve logged into many remote servers as a different user and setup my public key in authorized_keys and have no problems logging directly into that user.
Doing Private Public Key Authentication on Windows
If you use Windows, you will need something that can do ssh . Most people I know use PuTTY which can generate public/private keys, and do the key pairing when you login remotely. I can’t remember all of the steps, but you generate two files (one contains the public key, one contains the private key), and configure PuTTY to use both of those when logging into a remote site. If that remote site is Linux/Unix/Mac, you can copy your public key and put it into the authorized_keys file.
If you can use SSH Public/Private keys, you can eliminate the need for passwords in your scripts. Otherwise, you will have to use something like Expect or Perl with Net::SSH which can watch the remote host and enter the password when prompted.
Источник
How to pass password to scp command used in bash script? [duplicate]
I have a bash script that makes dump of DB then copies file from one server to another but it always asks for password before connection.
Is there a way to pass password directly into script ?
6 Answers 6
Rather than using root create an account just for this job. Use public keys without a passphrase instead of passwords.
By using a special account for the backup on the destination system you are not exposing your root password.
scp uses SSH to tunnel to a remote server and transfer files. SSH can authenticate users with a password, an SSH key or both (recommended).
To transfer files without a password, create an SSH key for the user you’re going to use (root is not recommended, use an unprivileged user instead and have a job on the target server as root to perform the privileged action).
Then you need to configure the target system’s SSH daemon to accept SSH key connections (also in above link).
Bear in mind that compromised SSH keys without a password are the same as compromised passwords — anybody can get in. For real users, it’s better to double the security and require the key and a password.
It’s better to set up ssh to used key-based authentication rather than trying to figure out how to send text to the login process with something like expect .
So, basically, run ssh-keygen -t dsa on the machine that will run your script. When it asks you for a passphrase, hit ENTER to accept a blank. You will get two files. If you followed the default suggestions, the files will be
/.ssh/id_dsa.pub. The first one is the private key. The second one is the public key.
Copy the public key to the second server using ssh-copy-id user@server2 . This will add the public key to the authorized_keys file of the user on server2.
You should now be able to run ssh from the first machine and log in without a password.
For copying the files, scp or rsync are fine. It depends on what you’re doing. rsync will use ssh by default, so will use the key-based authentication you just set up.
Источник