- Use SCP to move files to and from a Linux VM
- Quick commands
- Detailed walkthrough
- SSH key pair authentication
- SCP a file to a Linux VM
- SCP a directory from a Linux VM
- Использование SCP для перемещения файлов на виртуальную машину Linux и из нее
- Быстрые команды
- Подробное пошаговое руководство
- Аутентификация с помощью пары ключей SSH
- Копирование файла на виртуальную машину Linux с помощью SCP
- Копирование каталога с виртуальной машины Linux с помощью SCP
- Linux Copy File Command [ cp Command Examples ]
- cp Command Syntax
- Linux Copy File Examples
- Copy a file to another directory
- Verbose option
- Preserve file attributes
- Copying all files
- Recursive copy
- Linux copy file command with interactive option
- Verbose output with cp command
- Conclusion
- 2 Ways to Copy Files from Windows 10 to Windows Sub-System for Linux
- Distribution Package of Windows Sub-System for Linux
- Copy Files
- Method 1 – Manual Copy-Paste
- Method 2 – Windows System Drive as a Mount point
- Video Tutorial
- My New Book : PowerShell Scripting Guide to Python
Use SCP to move files to and from a Linux VM
Applies to: вњ”пёЏ Linux VMs вњ”пёЏ Flexible scale sets
This article shows how to move files from your workstation up to an Azure Linux VM, or from an Azure Linux VM down to your workstation, using Secure Copy (SCP). Moving files between your workstation and a Linux VM, quickly and securely, is critical for managing your Azure infrastructure.
For this article, you need a Linux VM deployed in Azure using SSH public and private key files. You also need an SCP client for your local computer. It is built on top of SSH and included in the default Bash shell of most Linux and Mac computers and PowerShell.
Quick commands
Copy a file up to the Linux VM
Copy a file down from the Linux VM
Detailed walkthrough
As examples, we move an Azure configuration file up to a Linux VM and pull down a log file directory, both using SCP and SSH keys.
SSH key pair authentication
SCP uses SSH for the transport layer. SSH handles the authentication on the destination host, and it moves the file in an encrypted tunnel provided by default with SSH. For SSH authentication, usernames and passwords can be used. However, SSH public and private key authentication are recommended as a security best practice. Once SSH has authenticated the connection, SCP then begins copying the file. Using a properly configured
/.ssh/config and SSH public and private keys, the SCP connection can be established by just using a server name (or IP address). If you only have one SSH key, SCP looks for it in the
/.ssh/ directory, and uses it by default to log in to the VM.
For more information on configuring your
/.ssh/config and SSH public and private keys, see Create SSH keys.
SCP a file to a Linux VM
For the first example, we copy an Azure configuration file up to a Linux VM that is used to deploy automation. Because this file contains Azure API credentials, which include secrets, security is important. The encrypted tunnel provided by SSH protects the contents of the file.
The following command copies the local .azure/config file to an Azure VM with FQDN myserver.eastus.cloudapp.azure.com. If you don’t have an FQDN set, you can also use the IP address of the VM. The admin user name on the Azure VM is azureuser. The file is targeted to the /home/azureuser/ directory. Substitute your own values in this command.
SCP a directory from a Linux VM
For this example, we copy a directory of log files from the Linux VM down to your workstation. A log file may or may not contain sensitive or secret data. However, using SCP ensures the contents of the log files are encrypted. Using SCP to transfer the files is the easiest way to get the log directory and files down to your workstation while also being secure.
The following command copies files in the /home/azureuser/logs/ directory on the Azure VM to the local /tmp directory:
The -r flag instructs SCP to recursively copy the files and directories from the point of the directory listed in the command. Also notice that the command-line syntax is similar to a cp copy command.
Источник
Использование SCP для перемещения файлов на виртуальную машину Linux и из нее
Применимо к: ✔️ виртуальные машины Linux ✔️ гибкие масштабируемые наборы
В этой статье показано, как перемещать файлы между рабочей станцией и виртуальной машиной Azure под управлением Linux, используя протокол SCP. Быстрое и безопасное перемещение файлов между рабочей станцией и виртуальной машиной с Linux является важной частью управления инфраструктурой Azure.
Для этой статьи необходима виртуальная машина Linux, развернутая в Azure с помощью файлов открытого и закрытого ключей SSH. Кроме того, нужен клиент SCP для локального компьютера. Он создан на основе SSH и включен в стандартную оболочку Bash на большинстве компьютеров Linux и Mac, а также в PowerShell.
Быстрые команды
Копирование файла на виртуальную машину под управлением Linux
Копирование файла с виртуальной машины под управлением Linux
Подробное пошаговое руководство
В качестве примера мы переместим файл конфигурации Azure на виртуальную машины Linux и извлечем каталог файлов журнала, используя SCP и ключи SSH.
Аутентификация с помощью пары ключей SSH
SCP использует SSH на транспортном уровне. Протокол SSH осуществляет аутентификацию на целевом узле, перемещая файл в зашифрованный канал, который по умолчанию предоставляется для SSH-подключения. Для аутентификации SSH можно использовать имена пользователей и пароли. Тем не менее по соображениям безопасности рекомендуется использовать аутентификацию с открытым и закрытым ключами SSH. После аутентификации подключения с помощью SSH инструмент SCP начинает копирование файла. При использовании правильно настроенного файла
/.ssh/config , а также открытого и закрытого ключей SSH подключение SCP можно установить, указав только имя сервера (или IP-адрес). При наличии только одного ключа SSH инструмент SCP будет искать его в каталоге
/.ssh/ и использовать по умолчанию для входа на виртуальную машину.
Дополнительные сведения о настройке файла
Копирование файла на виртуальную машину Linux с помощью SCP
В первом примере файл конфигурации Azure копируется на виртуальную машину Linux, которая используется для автоматизации развертывания. Так как этот файл содержит учетные данные API Azure, в том числе секреты, важно обеспечить его безопасность. Зашифрованный туннель, предоставляемый SSH-подключением, защищает содержимое файла.
Следующая команда копирует локальный файл .azure/config на виртуальную машину Azure с полным доменным именем myserver.eastus.cloudapp.azure.com. Если полное доменное имя не задано, можно также использовать IP-адрес виртуальной машины. Имя пользователя администратора на этой виртуальной машине Azure — azureuser. Файл копируется в каталог /home/azureuser. Подставьте собственные значения в эту команду.
Копирование каталога с виртуальной машины Linux с помощью SCP
В этом примере выполняется копирование каталога с файлами журнала с виртуальной машины Linux на вашу рабочую станцию. Файл журнала может содержать или не содержать секретные данные. Однако применение SCP гарантирует шифрование содержимого файлов журналов. Самый простой способ передать каталог и файлы журналов на рабочую станцию — использовать SCP для безопасной передачи файлов.
Следующая команда копирует файлы из каталога /home/azureuser/logs/ на виртуальной машине Azure в локальный каталог /tmp.
Если в командной строке указан флаг -r , SCP рекурсивно копирует файлы и каталоги, начиная с указанного в команде места в иерархии каталогов. Обратите также внимание, что синтаксис для командной строки аналогичен синтаксису команды копирования cp .
Источник
Linux Copy File Command [ cp Command Examples ]
cp Command Syntax
Tutorial details | |
---|---|
Difficulty level | Easy |
Root privileges | No |
Requirements | Terminal app/Shell prompt |
Est. reading time | 3 mintues |
The syntax is as follows to copy files and directories using the cp command:
cp SOURCE DEST
cp SOURCE DIRECTORY
cp SOURCE1 SOURCE2 SOURCE3 SOURCEn DIRECTORY
cp [OPTION] SOURCE DEST
cp [OPTION] SOURCE DIRECTORY
Where,
- In the first and second syntax you copy SOURCE file to DEST file or DIRECTORY.
- In the third syntax you copy multiple SOURCE(s) (files) to DIRECTORY.
Note: You need to type the cp command at the dollar sign ($) prompt. This prompt means that the shell is ready to accept your typed commands. Do not type the dollar ($) sign. You need to open the Terminal app to use cp command on a Linux.
Linux Copy File Examples
To make a copy of a file called file.doc in the current directory as newfile.doc, enter:
$ cp file.doc newfile.doc
$ ls -l *.doc
Sample outputs:
You can copy multiple files simultaneously into another directory. In this example, copy the files named main.c, demo.h and lib.c into a directory named backup:
$ cp main.c demo.h libc. backup
If backup is located in /home/project, enter:
$ cp main.c demo.h libc. /home/project backup
Copy a file to another directory
To copy a file from your current directory into another directory called /tmp/, enter:
$ cp filename /tmp
$ ls /tmp/filename
$ cd /tmp
$ ls
$ rm filename
Verbose option
To see files as they are copied pass the -v option as follows to the cp command:
Preserve file attributes
To copy a file to a new file and preserve the modification date, time, and access control list associated with the source file, enter:
$ cp -p file.txt /dir1/dir2/
$ cp -p filename /path/to/new/location/myfile
This option ( -p ) forces cp to preserve the following attributes of each source file in the copy as allowed by permissions:
- Modification time/date
- Access time
- File flags
- File mode
- User ID (UID)
- Group ID (GID)
- Access Control Lists (ACLs)
- Extended Attributes (EAs)
Copying all files
The star wildcard represents anything i.e. all files. To copy all the files in a directory to a new directory, enter:
$ cp * /home/tom/backup
The star wildcard represents anything whose name ends with the .doc extension. So, to copy all the document files (*.doc) in a directory to a new directory, enter:
$ cp *.doc /home/tom/backup
Recursive copy
To copy a directory, including all its files and subdirectories, to another directory, enter (copy directories recursively):
$ cp -R * /home/tom/backup
Linux copy file command with interactive option
You can get prompt before overwriting file. For example, if it is desired to make a copy of a file called foo and call it bar and if a file named bar already exists, the following would prompt the user prior to replacing any files with identical names:
cp -i foo bar
- No ads and tracking
- In-depth guides for developers and sysadmins at Opensourceflare✨
- Join my Patreon to support independent content creators and start reading latest guides:
- How to set up Redis sentinel cluster on Ubuntu or Debian Linux
- How To Set Up SSH Keys With YubiKey as two-factor authentication (U2F/FIDO2)
- How to set up Mariadb Galera cluster on Ubuntu or Debian Linux
- A podman tutorial for beginners – part I (run Linux containers without Docker and in daemonless mode)
- How to protect Linux against rogue USB devices using USBGuard
Join Patreon ➔
Verbose output with cp command
If you pass the -v to the cp, it makes tells about what is going on. That is verbose output:
cp -v file1 file2
cp -avr dir2 /backups/
Conclusion
This page explained cp command that is used for copying files under Linux and Unix-like systems. For more info see man pages: ls(1).
🐧 Get the latest tutorials on Linux, Open Source & DevOps via
Источник
2 Ways to Copy Files from Windows 10 to Windows Sub-System for Linux
Today we are going to discuss about how to copy file from your Windows 10 machine to Windows Sub-System for Linux.
Distribution Package of Windows Sub-System for Linux
First thing first, before you can even begin you have to understand where all the Linux files are placed in your Windows 10 machine. To avoid any accidental tampering Microsoft stores all you Linux files under the following hidden folder:
Here you can find your Linux distribution packages (distro) , double-click on the folder for your distribution, following is name of distribution package and folder name mapping:
Distribution Package | Folder Name |
---|---|
Ubuntu | CanonicalGroupLimited.UbuntuonWindows_79rhkp1fndgsc |
openSUSE Leap 42 | 46932SUSE.openSUSELeap42.2_022rs5jcyhyac |
SUSE Linux Enterprise Server 12 | 46932SUSE.SUSELinuxEnterpriseServer12SP2_022rs5jcyhyac |
For Ubuntu which I’m using, I’ll look for CanonicalGroupLimited.UbuntuonWindows_79rhkp1fndgsc and then navigate to folder navigate to .\LocalState\rootfs\ folder. This is the root file share where all you files are placed
Copy Files
Method 1 – Manual Copy-Paste
You can simply move or copy-paste files inside one of these Linux directories,
but the files won’t appear in you Windows Sub-system for Linux Bash Shell until you restart it.
Method 2 – Windows System Drive as a Mount point
Windows Sub-System for Linux provides you access to the Windows 10 system drive by mounting the C:\ . On Linux if you go to you root directory and list all directories, then you will notice a /mnt/c/ which is Windows 10 C:\ mounted on Linux
Now simply use copy command ( cp ) to copy files over to your Linux Subsystem.
Video Tutorial
If you like this article read more similar articles under ‘N – Ways to’ category
My New Book : PowerShell Scripting Guide to Python
This PowerShell Scripting guide to Python is designed to make readers familiar with syntax, semantics and core concepts of Python language, in an approach that readers can totally relate with the concepts of PowerShell already in their arsenal, to learn Python fast and effectively, such that it sticks with readers for longer time.
“Use what you know to learn what you don’t. ” also known as Associative learning.
Book follows a comparative method to jump start readers journey in Python, but who is the target audience? and who should read this book –
- Any System Administrator who want to step into Development or Programming roles, and even if you don’t want to be a developer, knowledge of another scripting language will make your skill set more robust.
- Python Developers who want to learn PowerShell scripting and understand its ease of user and importance to manage any platform.
Python is one of the top programming languages and in fast changing IT scenarios to DevOps and Cloudto the future – Data Science, Artificial Intelligence (AI) and Machine Learning Python is a must know.
But this PowerShell Scripting guide to Python would be very helpful for you if you already have some knowledge of PowerShell
NOTE! This is a Leanpub “Agile-published” book. That means the book is currently unfinished and in-progress. As I continue to complete the chapters, we will re-publish the book with the new and updated content. Readers will receive an email once a new version is published!
While the book is in progress, please review it and send any feedback or error corrections at [email protected]
Follow @SinghPrateik
Источник