Scp какой порт

Обновлено: 04.07.2024

Closed 4 years ago .

I'm trying to copy a folder from one system to another using scp (secure copy) however I cannot work out how to specify the port.

I understand that to scp, I can.

however I have changed the destination system's SSH port so I get get this error.

ssh: connect to host ..*.*** port 22: Connection refused lost connection

Is there some sort of -p command I can use to specify port number?

I also tried adding the port like this.

Updated with solution.

I was struggling not only with using the wrong -P but also where to place. I know understand and this works for me.


Это неинтерактивная передача файлов, которая использует только оболочку и удаленную команду для безопасной передачи файлов между двумя компьютерами. Это безопасная версия предыдущего RCP, и FTP использует протокол SSH для аутентификации, но с аналогичным синтаксисом командной строки. Хотя он строго основан на утилите SFTP, SCP обычно является более подходящим вариантом при использовании сценариев для настройки автоматической передачи файлов.

Команду можно использовать для отправки или получения файла на сервер и с сервера. По сути, он записывает байты файлов в туннель SSH и позволяет SSH иметь дело с более сложным процессом, таким как целостность и сжатие.

SCP также можно использовать с подстановочными операторами при передаче нескольких файлов на основе выбранных вами критериев. Эти подстановочные знаки также могут использоваться для отправки и получения файлов.

Он также копирует файлы между компьютерами (локальными и удаленными) или между одним удаленным хостом и другим.

6 Answers 6

I don't know of any way to copy the file directly in one single command, but if you can concede to running an SSH instance in the background to just keep a port forwarding tunnel open, then you could copy the file in one command.

Note that you connect as user2@localhost in the actual scp command, because it is on port 1234 on localhost that the first ssh instance is listening to forward connections to remote2 . Note also that you don't need to run the first command for every subsequent file copy; you can simply leave it running.


23.8k 2 2 gold badges 47 47 silver badges 86 86 bronze badges Thanks! I had to change -p 45678 to -p 22 as my remote1 SSH is listening to port 22

Какой из них использовать для передачи файлов: SCP или SFTP?

Хотя у них есть свои сходства и различия, говорить, что одно лучше другого, было бы несправедливо. Оба передаваемых файла имеют схожие функции безопасности, поскольку они работают по SSH. Выбранная вами утилита будет основана на том, что лучше всего соответствует требованиям вашей среды: скорость, функциональность и безопасность.

SCP сравнение с SFTP: какой из них использовать для передачи файлов

SCP сравнение с SFTP: какой из них использовать для передачи файлов Reviewed by Admin on марта 14, 2019 Rating: 5

I'm trying to scp a file from a remote server to my local machine. Only port 80 is accessible.

but got this error: cp: 80: No such file or directory

How do I specify the port number in a scp command?

19.6k 22 22 gold badges 64 64 silver badges 101 101 bronze badges

12 Answers 12

Unlike ssh, scp uses the uppercase P switch to set the port instead of the lowercase p:

The lowercase p switch is used with scp for the preservation of times and modes.

Here is an excerpt from scp's man page with all of the details concerning the two switches, as well as an explanation of why uppercase P was chosen for scp:

-P port Specifies the port to connect to on the remote host. Note that this option is written with a capital 'P', because -p is already reserved for preserving the times and modes of the file in rcp(1).

-p Preserves modification times, access times, and modes from the original file.

Bonus Tip: How can I determine the port being used by the/an SSH daemon to accept SSH connections?

This question can be answered by using the netstat utility, as follows:

Or, using the far more readable word based netstat option names:

The output you will see, assuming your ssh daemon is configured with default values its listening ports, is shown below (with a little trimming of the whitespace in between columns, in order to get the entire table to be visible without having to scroll):

For the above examples, sudo was used to run netstat with administrator privs, in order to be able to see all of the Program Names. If you run netstat as a regular user (i.e., without sudo and assuming you don't have admin rights granted to you, via some other method), you will only see program names shown for sockets that have your UID as the owner. The Program Names for sockets belonging to other users will not be shown (i.e., will be hidden and a placeholder hyphen will be displayed, instead):

Update and aside to address one of the (heavily upvoted) comments:

With regard to Abdull's comment about scp option order, what he suggests:

. intersperses options and parameters, since the -r switch takes no additional arguments and some_directory is treated as the first parameter to the command, making -P and all subsequent command line arguments look like additional parameters to the command (i.e., hyphen prefixed arguments are no longer considered as switches).

getopt(1) clearly defines that parameters must come after options (i.e., switches) and not be interspersed with them, willy-nilly:

The parameters getopt is called with can be divided into two parts: options which modify the way getopt will do the parsing (the options and the optstring in the SYNOPSIS), and the parameters which are to be parsed (parameters in the SYNOPSIS). The second part will start at the first non-option parameter that is not an option argument, or after the first occurrence of '--'. If no '-o' or '--options' option is found in the first part, the first parameter of the second part is used as the short options string.

Since the -r command line option takes no further arguments, some_directory is "the first non-option parameter that is not an option argument." Therefore, as clearly spelled out in the getopt(1) man page, all succeeding command line arguments that follow it (i.e., -P 80 . ) are assumed to be non-options (and non-option arguments).

So, in effect, this is how getopt(1) sees the example presented with the end of the options and the beginning of the parameters demarcated by gray text:

scp -r some_directory -P 80 .

This has nothing to do with scp behavior and everything to do with how POSIX standard applications parse command line options using the getopt(3) set of C functions.

For more details with regard to command line ordering and processing, please read the getopt(1) manpage using:

I wonder if there is a way for me to SCP the file from remote2 host directly from my local machine by going through a remote1 host.

The networks only allow connections to remote2 host from remote1 host. Also, neither remote1 host nor remote2 host can scp to my local machine.

Is there something like:

First window: ssh remote1 , then scp remot2:file . .

Second shell: scp remote1:file .

First window: rm file; logout

I could write a script to do all these steps, but if there is a direct way, I would rather use it.

EDIT: I am thinking something like opening SSH tunnels but i'm confused on what value to put where.

At the moment, to access remote1 , i have the following in $HOME/.ssh/config on my local machine.

Once on remote1 , to access remote2 , it's the standard local DNS and port 22. What should I put on remote1 and/or change on localhost ?

12.1k 3 3 gold badges 34 34 silver badges 43 43 bronze badges 3,397 4 4 gold badges 25 25 silver badges 39 39 bronze badges

SFTP (безопасный протокол передачи файлов)

В отличие от SCP, который не является интерактивным, SFTP является интерактивным протоколом или программой передачи файлов, которая выполняет все операции через зашифрованный транспорт SSH.

Он использует несколько функций, таких как сжатие или аутентификация с открытым ключом, для подключения и входа на конкретный хост и входит в интерактивный командный режим.

SFTP может относиться либо к простому протоколу передачи файлов, либо к протоколу передачи файлов SSH. Последний предназначен для использования с SSH для безопасной передачи файлов, тогда как Simple File Transfer Protocol - это облегченная версия FTP, от которой отказались в пользу TFTP. Он работает на TCP-порту 115.

Он также используется для автоматического извлечения файлов, если вы используете неинтерактивный метод аутентификации; в противном случае он извлекает их после успешной интерактивной аутентификации.

Хотя он работает со многими протоколами, SFTP обычно использует SSH для безопасной аутентификации.

Примечание. SFTP - это не FTP через SSH, а новый протокол.

Double ssh

Even in your complex case, you can handle file transfer using a single command line, simply with ssh ;-)
And this is useful if remote1 cannot connect to localhost :

But you loose file properties (ownership, permissions. ).

However, tar is your friend to keep these file properties:

You can also compress to reduce network bandwidth:

And tar also allows you transferring a recursive directory through basic ssh :

ionice

If the file is huge and you do not want to disturb other important network applications, you may miss network throughput limitation provided by scp and rsync tools (e.g. scp -l 1024 user@remote:file does not use more than 1 Mbits/second).

But, a workaround is using ionice to keep a single command line:

Note: ionice may not be available on old distributions.


42.9k 26 26 gold badges 145 145 silver badges 185 185 bronze badges I agree this is a better solution than the accepted answer. This way, the connection is automatically cleaned up. Thank you, very nice answer! How about the other way around, copying from local to remote?

This will do the trick:

To SCP the file from the host remote2 directly, add the two options ( Host and ProxyCommand ) to your

/.ssh/config file (see also this answer on superuser). Then you can run:

from your local machine without having to think about remote1 .


3,942 3 3 gold badges 28 28 silver badges 39 39 bronze badges 12.8k 27 27 gold badges 74 74 silver badges 116 116 bronze badges

With openssh version 7.3 and up it is easy. Use ProxyJump option in the config file.

Commands to run to login or copy

ofcourse you can specify bastion Jump host using option "-J" to ssh command, if not configured in config file.

Note scp does not seems to support "-J" flag as of now. (i could not find in man pages. However above scp works with config file setting)

There is a new option in scp that add recently for exactly this same job that is very convenient, it is -3 .

TL;DR For the current host that has authentication already set up in ssh config files, just do:

Your scp must be from recent versions.

All other mentioned technique requires you to set up authentication from remote1 to remote2 or vice versa, which not always is a good idea.
Argument -3 means you want to move files from two remote hosts by using current host as intermediary, and this host actually does the authentication to both remote hosts, so they don't have to have access to each other.
You just have to setup authentication in ssh config files, which is fairly easy and well documented, and then just run the command in TL;DR

Различия между SCP и SFTP

Существует несколько сходств между обеими программами передачи файлов, поскольку обе используют TCP-порт 22 и работают по SSH, что делает их равными с точки зрения безопасности.

Они оба предлагают функции, включая шифрование для данных в движении и аутентификацию с открытым ключом. Кроме того, оба протокола поддерживают передачу больших файлов, поскольку у них нет ограничений на размер файла.

Основные различия между SCP и SFTP можно увидеть в их спецификациях и функциях.

Функциональность

SCP передает данные с защитой от перехвата, а SFTP выполняет функции доступа к файлам, их передачи и управления.

Таким образом, в то время как SCP лучше спроектирован для одноразовой передачи файлов между двумя сетевыми компьютерами или удаленно через Интернет, SFTP делает это, а также управляет этими данными.

Операции

SCP не может выполнять некоторые операции, такие как удаленный просмотр каталога или удаление файла; он может только передавать файлы. SFTP, с другой стороны, выполняет все, в том числе задачи удаления файлов и перечисления каталогов.

SFTP предлагает компонент с графическим интерфейсом для более удаленного администрирования и больше похож на файловую систему с удаленным доступом, но SCP этого не предлагает.

Скорость передачи файлов

SCP подтверждает полученные пакеты быстрее, чем SFTP, который должен подтверждать каждый крошечный пакет. Это особенно актуально в сетях с высокой задержкой.

Другое преимущество SCP состоит в том, что он использует более эффективный алгоритм для передачи файлов.

Возобновление прерванной передачи файла

SCP не поддерживает эту функцию, но SFTP поддерживает ее через клиента командной строки.

Командные строки

SCP неинтерактивен и не может читать командные сценарии, поэтому все должно быть написано в командной строке. SFTP, с другой стороны, является интерактивным, поэтому он может читать команды из файлов.

Читайте также: