- 10 Примеров: Копирование файлов через SSH
- Копирование файлов и запуск команд через SSH
- Работаем на ОС семейства Linux
- Работаем на ОС семейства Windows
- Запуск команд на удаленном сервере через SSH-подключение
- Работаем на ОС семейства Linux
- Работаем на ОС семейства Windows
- Copying a local file from Windows to a remote server using scp [closed]
- 7 Answers 7
- Copy Files Over SSH task
- Prerequisites
- YAML snippet
- Arguments
- Supported algorithms
- Key pair algorithms
- Encryption algorithms
- See also
- Open source
- What key formats are supported for the SSH tasks?
- Do I need an agent?
- I’m having problems. How can I troubleshoot them?
- I can’t select a default agent pool and I can’t queue my build or release. How do I fix this?
- My NuGet push task is failing with the following error: «Error: unable to get local issuer certificate». How can I fix this?
- Is this task supported for target machines running operating systems other than Linux?
- I use TFS on-premises and I don’t see some of these features. Why not?
10 Примеров: Копирование файлов через SSH
SCP (Secure CoPy) — программа для удаленного копирования фалов по сети между хостами.
Она использует SSH для передачи данных, ту же аутентификацию и те же меры безопасности, что и SSH.
Во время копирования исходного фала в файл назначения, который уже существует, SCP перезаписывает файл назначения. Если файл назначения еще не существует, тогда создается пустой файл, ему задается имя файла назначения и уже в него записывается содержимое копируемого файла.
Пример 1: Копируем файл «file.txt» из удаленного сервера на локальный компьютер.
Пример 2: Копируем файл «file.txt» с локального компьютера на удаленный сервер.
Пример 3: Копируем папку «dir1» с локального хоста в директорию «dir2» на удаленном хосте.
Пример 4: Копируем файл «file.txt» с одного удаленного сервера «remote.host1» на другой удаленный сервер «remote.host2».
Пример 5: Копируем файлы «file1.txt» и «file2.txt» с локального компьютера в Ваш домашний каталог на удаленном сервере.
Пример 6: Копируем файл «file.txt» с локального хоста на удаленный хост, используя порт 2222.
Пример 7: Копируем файл «file.txt» с локального компьютера в Ваш домашний каталог на удаленном сервере. Сохраняем время изменения и время доступа и права копируемого фала.
Пример 8: Копируем файл «file.txt» с локального компьютера в Ваш домашний каталог на удаленном сервере. Увеличиваем скорость работы SCP изменяя алгоритм шифрования с AES-128 (по умолчанию) на Blowfish.
Пример 9: Копируем файл «file.txt» с локального компьютера в Ваш домашний каталог на удаленном сервере. Ограничиваем ширину канала используемого командой SCP до 100 Kbit/s.
Пример 10: Копируем несколько файлов с удаленного хост в текущую директорию на Вашем локальном хосте.
Копирование файлов и запуск команд через SSH
Подключение к серверу посредством SSH – один из основных методов управления *nix серверами. Довольно часто возникает необходимость загрузить файл на удаленный сервер, либо выгрузить, и других средств кроме SSH-подключения нет. К счастью, копирование файлов через защищенное соединение – одна из штатных функций этого протокола и реализуется с помощь отдельной команды scp в Linux-системах, либо с помощью pscp.exe, входящей в состав SSH-клиента Putty для операционной системы Windows.
Работаем на ОС семейства Linux
Используем следующий формат команд:
scp [модификатор] [источник] [место_назначения]
Если в качестве источника или места назначения указывается удаленный сервер, то формат параметра такой:
После запуска команды потребуется ввести пароль от указанной учетной записи удаленного сервера.
Если собрать все вместе, то скопировать локальный файл /home/user/file.tgz в домашний каталог пользователя root удаленного сервера 123.123.123.123 можно командой:
scp /home/user/file.tgz root@123.123.123.123:/root
Чтобы скачать этот же файл с удаленного сервера:
scp root@123.123.123.123:/root/file.tgz /home/user
За одну операцию можно скопировать несколько файлов, для этого необходимо указать их в качестве источника, разделив пробелом – местом назначения будет считаться последний указанный параметр. Например, загрузить файлы file1.tgz и file2.tgz из локального каталога на удаленный сервер позволит команда:
scp file1.tgz file2.tgz root@123.123.123.123:/root
Для копирования каталога потребуется задействовать модификатор команды –r. Копируем локальный каталог /home/user/dir на удаленный сервер:
scp –r /home/user/dir root@123.123.123.123:/root
В тех случаях, когда SSH-сервер работает на нестандартном порту, поможет опция –P. Если нужно подключиться через порт 10022:
scp –P 10022 /home/user/file.tgz root@123.123.123.123:/root
Чтобы узнать какие еще модификаторы поддерживает команда, можно просто запустить scp без параметров и прочитать краткую справку.
Работаем на ОС семейства Windows
При использовании операционной системы Windows и Putty в качестве клиента, формат команды остается тот же, меняется только название исполняемого файл и используется синтаксис указания путей к файлам и каталогам Windows при указании источника или места назначения. Запускаем командную строку (cmd.exe) или PowerShell, переходим в каталог, где расположен файл pscp.exe вводим команду:
pscp.exe C:Tempfile.tgz root@123.123.123.123:/root
В случае запуска из какой-либо другой папки понадобится указать полный путь к pscp.exe. Если в каком-либо из путей присутствуют пробелы, используются двойные кавычки — “Путь к файлу”:
“C:Program FilesPuttypscp.exe” C:Tempfile.tgz root@123.123.123.123:/root
Как и в случае с scp, запустив pscp.exe без параметров, можно увидеть краткую справку по синтаксису команды и перечень поддерживаемых модификаторов.
Запуск команд на удаленном сервере через SSH-подключение
Протокол SSH, помимо работы в интерактивном режиме, поддерживает также разовый запуск команд или скриптов на удаленном сервере.
Работаем на ОС семейства Linux
ssh [пользователь]@[сервер] ‘[команда]’
При запросе вводим пароль указанного пользователя и в консоли получаем вывод команды, если таковой имеется.
Например, получим информацию об установленной на удаленном сервере операционной системе:
ssh root@123.123.123.123 ‘uname -a’
Чтобы запустить несколько команд за одно подключение, можно использовать символ “;” в качестве разделителя. Проверим сетевые настройки и активные сетевые подключения на удаленном сервере:
ssh root@123.123.123.123 ‘ifconfig; netstat -anp tcp’
В случае, если потребуется запустить на удаленном сервере локальный файла сценария, потребуется в SSH-подключении вызвать командный интерпретатор в режиме исполнения сценария (например, bash с ключом -s), и на стандартный ввод передать ему файл сценария. Выглядеть эта конструкция будет так:
ssh root@123.123.123.123 ‘bash -s’
В результате локальный файл /home/user/myscript.sh исполнится на удаленном сервере.
Запуск команды SSH без параметров позволит ознакомиться с краткой справкой по синтаксису и списком дополнительных модификаторов, которые позволяют расширить функциональность команды.
Работаем на ОС семейства Windows
Если мы подключаемся к удаленному серверу с компьютера, работающего на операционной системе Windows, то нам снова потребуется обратиться к терминальному клиенту Putty, в состав которого входит исполняемый файл plink.exe. Работать с этим файлом необходимо из командной строки (cmd.exe) или из PowerShell.
Для запуска команды на удаленном сервере используется следующий синтаксис:
plink.exe [сервер] -ssh -l [пользователь] “[команда]”
Проверим конфигурацию сетевых интерфейсов:
plink.exe 123.123.123.123 -ssh -l root “ifconfig”
Как и при работе с командой SSH в Linux, plink.exe позволяет использовать “;” в качестве разделителя для запуска нескольких команд:
plink.exe 123.123.123.123 -ssh -l root “ifconfig; netstat -anp tcp”
А запуск команд из локального файла можно реализовать с помощью дополнительного ключа —m:
Copying a local file from Windows to a remote server using scp [closed]
Want to improve this question? Update the question so it’s on-topic for Stack Overflow.
Closed 1 year ago .
So, I’m attempting to simply transfer folder of files from my local computer to a server via ssh and scp. After sudoing I’m using the command as follows:
I get the error:
ssh: C: Name or service not known
I’m guessing its my syntax for c:/desktop etc. Any ideas?
BTW I’m using putty + Windows 7.
7 Answers 7
If your drive letter is C, you should be able to use
scp -r \desktop\myfolder\deployments\ user@host:/path/to/whereyouwant/thefile
without drive letter and backslashes instead of forward slashes.
You are using putty, so you can use pscp. It is better adapted to Windows.
-r ./localdir user@host:»D:\remotedir» – serigado Jun 11 ’20 at 16:16
Drive letters can be used in the target like
where c is the drive letter. It’s treated like a directory.
Maybe this works on the source, too.
On windows you can use a graphic interface of scp using winSCP. A nice free software that implements SFTP protocol.
I see this post is very old, but in my search for an answer to this very question, I was unable to unearth a solution from the vast internet super highway. I, therefore, hope I can contribute and help someone as they too find themselves stumbling for an answer. This simple, natural question does not seem to be documented anywhere.
On Windows 10 Pro connecting to Windows 10 Pro, both running OpenSSH (Windows version 7.7p1, LibreSSL 2.6.5), I was able to find a solution by trial and error. Though surprisingly simple, it took a while. I found the required syntax to be
BY EXAMPLE INSTEAD OF MORE OBSCURE AND INCOMPLETE TEMPLATES:
Transferring securely from a remote system to your local system:
or going the other way around:
I also found that if spaces are in the path, the quotations should begin following the remote host name:
Also, for your particular case, I echo what Cornel says:
On Windows, use backslash, at least at conventional command console.
Copy Files Over SSH task
Azure Pipelines | Azure DevOps Server 2020 | Azure DevOps Server 2019 | TFS 2018 | TFS 2017
Use this task to copy files from a source folder to a target folder on a remote machine over SSH.
This task allows you to connect to a remote machine using SSH and copy files matching a set of minimatch patterns from specified source folder to target folder on the remote machine. Supported protocols for file transfer are SFTP and SCP via SFTP. In addition to Linux, macOS is partially supported (see FAQ).
In Microsoft Team Foundation Server (TFS) 2018 and previous versions, build and release pipelines are called definitions, runs are called builds, service connections are called service endpoints, stages are called environments, and jobs are called phases.
Prerequisites
- The task supports use of an SSH key pair to connect to the remote machine(s).
- The public key must be pre-installed or copied to the remote machine(s).
YAML snippet
Arguments
Argument | Description |
---|---|
SSH endpoint | The name of an SSH service connection containing connection details for the remote machine. — The hostname or IP address of the remote machine, the port number, and the user name are required to create an SSH service connection. — The private key and the passphrase must be specified for authentication. |
Source folder | The source folder for the files to copy to the remote machine. If omitted, the root of the repository is used. Names containing wildcards such as *.zip are not supported. Use variables if files are not in the repository. Example: $(Agent.BuildDirectory) |
Contents | File paths to include as part of the copy. Supports multiple lines of minimatch patterns. Default is ** which includes all files (including sub folders) under the source folder. — Example: **/*.jar \n **/*.war includes all jar and war files (including sub folders) under the source folder. — Example: ** \n !**/*.xml includes all files (including sub folders) under the source folder but excludes xml files. |
Target folder | Target folder on the remote machine to where files will be copied. Example: /home/user/MySite . Preface with a tilde ( ) to specify the user’s home directory. |
Advanced — Clean target folder | If this option is selected, all existing files in the target folder will be deleted before copying. |
Advanced — Overwrite | If this option is selected (the default), existing files in the target folder will be replaced. |
Advanced — Flatten folders | If this option is selected, the folder structure is not preserved and all the files will be copied into the specified target folder on the remote machine. |
Control options | See Control options |
Supported algorithms
Key pair algorithms
Encryption algorithms
- aes256-cbc
- aes192-cbc
- aes128-cbc
- blowfish-cbc
- 3des-cbc
- arcfour256
- arcfour128
- cast128-cbc
- arcfour
For OpenSSL v1.0.1 and higher (on agent):
For OpenSSL v1.0.1 and higher, NodeJS v0.11.12 and higher (on agent):
- aes128-gcm
- aes128-gcm@openssh.com
- aes256-gcm
- aes256-gcm@openssh.com
See also
Open source
This task is open source on GitHub. Feedback and contributions are welcome.
What key formats are supported for the SSH tasks?
The Azure Pipelines SSH tasks use the Node.js ssh2 package for SSH connections. Ensure that you are using the latest version of the SSH tasks. Older versions may not support the OpenSSH key format.
If you run into an «Unsupported key format» error, then you may need to add the -m PEM flag to your ssh-keygen command so that the key is in a supported format.
Do I need an agent?
You need at least one agent to run your build or release.
I’m having problems. How can I troubleshoot them?
I can’t select a default agent pool and I can’t queue my build or release. How do I fix this?
My NuGet push task is failing with the following error: «Error: unable to get local issuer certificate». How can I fix this?
This can be fixed by adding a trusted root certificate. You can either add the NODE_EXTRA_CA_CERTS=file environment variable to your build agent, or you can add the NODE.EXTRA.CA.CERTS=file task variable in your pipeline. See Environment variables for more details.
Is this task supported for target machines running operating systems other than Linux?
This task is intended for target machines running Linux.
- For copying files to a macOS machine, this task may be used, but authenticating with a password is not supported.
- For copying files to a Windows machine, consider using Windows Machine File Copy.
I use TFS on-premises and I don’t see some of these features. Why not?
Some of these features are available only on Azure Pipelines and not yet available on-premises. Some features are available on-premises if you have upgraded to the latest version of TFS.