Сегодня короткая заметка об одном полезном иструменте под название SCP — утилита для копирования файлов в SSH сессии. Он доступен в Windows 10 как один из инструментов работы с SSH.
Копирование файла с компьютера Windows на удаленный компьютер Linux по SSH:
scp "C:\dir\file.zip" root@192.168.1.1:~/archives
file.zip
будет скопирован в каталог archives
в домашнем каталоге пользователя root
Можно копировать файлы используя маски в имени:
scp "C:\dir\*.zip" root@192.168.1.1:~/archives
все файлы c расширением zip
будут скопированы в каталог archives
в домашнем каталоге
С ключем -r
можно рекурсивно скопировать файлы и каталоги в каталог назначения:
scp -r "C:\dir\" root@192.168.1.1:~/archives
все файлы и каталоги будут скопированы в каталог archives
в домашнем каталоге
Копирование файла с удаленного компьютера Linux на компьютер Windows по SSH:
scp.exe root@192.168.1.1:~/archives/file.zip "C:\dir\"
Файл file.zip
будет скопирован в каталог C:\dir
Протокол SSH (Secure Shell) — это сетевой протокол для удаленного управления операционной системой через командную строку, который можно назвать стандартом для удаленного доступа к *nix-машинам. Позволяет производить защищенный вход на сервер, удаленно выполнять команды, управлять файлами (создавать, удалять, копировать и т.д.) и многое другое. Большинство облачных и хостинг-провайдеров требуют наличие SSH для доступа к своим сервисам. В этой статье рассмотрим копирование файлов по SSH в Windows и Linux-системах.
SSH способен передавать любые данные (звук, видео, данные прикладных протоколов) через безопасный канал связи. В отличие от устаревших и небезопасных протоколов telnet и rlogin, в SSH обеспечивается конфиденциальность передаваемых данных и подлинность взаимодействующих сторон — необходимые условия для сетевого взаимодействия в Интернете.
Рассмотрим алгоритм установки зашифрованного соединения между клиентом и сервером:
- Установка TCP-соединения. По умолчанию сервер слушает 22-й порт. В работе протокола используется набор алгоритмов (сжатие, шифрование, обмен ключами), поэтому стороны обмениваются списком поддерживаемых алгоритмов и договариваются, какие из них будут использовать.
- Чтобы третья сторона не смогла выдать себя за сервер или клиент, стороны должны удостоверится в подлинности друг друга (аутентификация). Для этого используются асимметричные алгоритмы шифрования и пара открытый-закрытый ключ. Вначале проверяется аутентичность сервера. Если соединение происходит впервые, пользователь увидит предупреждение и информацию о сервере. Список доверенных серверов и их ключей записывается в файл по адресу /home/<username>/.ssh/known_hosts.
- Как только клиент убедился в достоверности сервера, стороны генерируют симметричный ключ, с помощью которого происходит шифрования всех обмениваемых данных. Таким образом при перехвате данных, никто, кроме сторон не сможет узнать содержимое сообщений.
- Далее происходит аутентификация пользовательского сеанса. Для этого используется либо пароль, либо присланный клиентом публичный ключ, сохраняемый в файле /home/<username>/.ssh/authorized_keys на сервере.
Самая популярная реализация на Линукс, OpenSSH, предустанавливается практически на всех дистрибутивах: Ubuntu, Debian, RHEL-based и других. На Windows в качестве клиентов можно использовать программы PuTTY, MobaXterm. Начиная с WIndows 10 и Windows Server 2019 инструменты OpenSSH доступны и на Windows.
Подробнее об SSH и работе с ним мы писали в статье «Как пользоваться SSH».
VDS
Копирование файлов
Копирование файлов в Linux по SSH осуществляется с помощью двух основных программ: scp и sftp. Обе утилиты поставляются вместе с пакетом OpenSSH. Существуют две основные версии протокола SSH: 1 и 2. Оболочка OpenSSH поддерживает обе версии, однако первая применяется редко.
Настройка автодополнений
При работе с scp крайне удобно использовать tab для автодополнения путей на удаленной машине. Для этого нужно настроить аутентификацию пользователя по публичному ключу.
Для начала сгенерируем открытый и закрытый ключ:
ssh-keygen
Вывод:
Generating public/private rsa key pair.
Enter file in which to save the key (/home/user/.ssh/id_rsa):
Created directory '/home/user/.ssh'.
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /home/user/.ssh/id_rsa.
Your public key has been saved in /home/user/.ssh/id_rsa.pub.
The key fingerprint is:
SHA256:wJQ/XBZq69qXGHxseTuccUEpzWYHhsVVHcDXE3MrTHQ user@host
В конце вывода будет графическое представление ключа (key’s randomart image), которое легче запомнить, чем хэш ключа.
По умолчанию ключи (id_rsa.pub — открытый, id_rsa — закрытый) сохранятся в домашнем каталоге пользователя в директории .ssh. Также во время генерации программа попросит ввести пароль, которым будут защищены ключи. Если не хотите дополнительной защиты, нажмите два раза Enter.
Теперь копируем публичный ключ на удаленную машину:
ssh-copy-id [имя пользователя]@[ip-адрес]
Здесь [имя пользователя] — учетная запись пользователя, под которой будем логиниться на удаленной машине, [ip-адрес] — адрес удаленной машины (можно использовать доменное имя, если они локально резолвится). Далее вводим пароль пользователя. Если все прошло корректно, то в выводе будет команда для удаленного подключения:
Number of key(s) added: 1
Now try logging into the machine, with: "ssh '<имя пользователя>@<ip-адрес>'"
and check to make sure that only the key(s) you wanted were added.
Secure copy (SCP)
Для копирования небольших объемов информации (например, конфиги сервисов) лучше всего подойдет утилита scp.
Синтаксис команды для копирования с локальной машины на удаленный сервер:
scp [путь к файлу] [путь к файлу] [имя пользователя]@[ip-адрес]:[путь к файлу]
Попробуем скопировать файл на сервер:
scp test.txt user@192.168.1.29:/home/user/
Вывод:
test.txt 100% 12 20.6KB/s 00:00
Можно передать несколько файлов за раз. Для этого указываем пути, разделенные пробелами:
scp test1.txt test2.txt user@192.168.1.29:/home/user/
Для копирования с удаленного сервера на локальную машину нужно поменять источник и место назначения местами:
scp user@192.168.1.29:/home/user/test.txt ~/
Для передачи директории используйте ключ -r
:
scp -r testdir user@192.168.1.29:/home/user/
Также имеется возможность передачи с одного удаленного сервера на другой:
scp gendo@192.168.1.25:/home/gendo/test.txt user@192.168.1.29:/home/user/
Secure FTP (SFTP)
Еще одной утилитой для передачи файлов, поставляемых в OpenSSH, является sftp. C релизом OpenSSH 9.0 утилита scp переведена по умолчанию на использование SFTP вместо устаревшего протокола SCP/RCP. Sftp работает практически также, как и классический ftp, за исключением того, что в sftp данные передаются не в виде обычного текста, а по зашифрованному туннелю (туннелирование — это процесс упаковки и передачи одного сетевого подключения с помощью другого). Также для работы sftp не нужен отдельный FTP-сервер.
Пример простого скачивания через sftp:
gendo@melhior:~$ sftp misato@192.168.1.29
Connected to 192.168.1.29.
sftp> ls
file.txt file1.txt file2.txt test.txt
sftp> lcd testdir/
sftp> get test.txt
Fetching /home/misato/test.txt to test.txt
test.txt 100% 12 4.8KB/s 00:00
sftp> bye
Сам по себе sftp применяется редко: вместо этого его используют файловые менеджеры, например Midnight Commander и Nautilus:
Использование sftp в файловом менеджере Nautilus. Удаленная машина отображается в виде папки с именем пользователя и IP-адресом.
Копирование файлов по SSH в Windows
Скачать файл с сервера или на сервер в Windows можно с помощью консольной программы pscp, поставляемой вместе с PuTTY. Синтаксис очень похож на обычный scp:
pscp [путь к файлу] [имя пользователя]@[имя сервера/ip-адрес]:[путь к файлу]
Для SSH-копирования файлов на сервер, используйте следующую команду:
pscp C:\server\test.txt misato@192.168.1.29:/home/misato/
Скачивание файла с сервера на компьютер:
pscp misato@192.168.1.29:/home/misato/test.txt C:\file.txt
Увидеть список файлов на сервере можно при помощи опции -ls
:
pscp -ls [имя пользователя]@[ip-адрес]:[путь]
Если в пути или в названии файла есть пробелы, используйте кавычки:
pscp "C:\dir\bad file name" misato@192.168.1.29:/home/misato
Для получения помощи по команде введите pscp без аргументов.
Заключение
Мы рассмотрели, как копировать файлы на сервер и с сервера с помощью безопасного сетевого протокола SSH. Если вы используете облачные серверы, важно уметь работать с SSH, так как он является стандартом для удаленного доступа к *nix-машинам и будет необходим вам в повседневной работе.
Кстати, в официальном канале Timeweb Cloud собрали комьюнити из специалистов, которые говорят про IT-тренды, делятся полезными инструкциями и даже приглашают к себе работать.
When you are working on the multiple servers, copying files between two servers is a common task for any system administrator. In this case, the SCP utility is the best choice for any system administrator.
SCP stands for “Secure Copy Protocol” is a Linux command-line tool used to transfer files and directories securely between two servers.
By default, GUI mode is not installed in Linux servers. SCP utility makes it easier for Linux system administrator to manage the multiple servers from the command-line.
SCP utility is based on the SSH, as so you will need a username and password of the source and target system to transfer the files.
In this tutorial, we will show you how to transfer files and directories between two systems using SCP file transfers!
Basic Syntax
The basic syntax of the scp command is shown below:
scp [OPTION] local-file-or-directory user@remote-ip:/directory/
You can use the above command to transfer files and directories from a local system to remote system.
scp [OPTION] user@remote-ip:/remote-file /local-directory
You can use the above command to transfer files and directories from a remote system to local system.
scp [OPTION] user@remote-ip:/directory/ user@remote-ip:/directory/
You can use the above command to transfer files and directories from one remote system to another remote system.
A brief explanation of each option in SCP command are shown below:
*Note: all these options are Case sensitive!
- -r
This option will copy files and directories recursively. - -v
This option will display verbose output during the copying process. - -P
This option is used to specify the ssh port number of the target host when the target host using the different SSH port. - -l
This option is used to limit the bandwidth while copying the files and directories. - -q
This option skips the SSH warning message. - -p
This option will preserve permissions, modes and access time of files while copying. - -i
This option is used to specify the SSH private key.
Transfer Files and Directories with SCP in Linux
The SCP utility allows you to transfer files between, local to remote, remote to local and remote to remote systems.
In this section we will show you how to transfer files and directories between them.
Local to Remote System Transfers:
Local to Remote File Transfers:
To transfer a file named file1.txt located inside /tmp directory from a local system to the remote system directory /opt use the following command:
scp /tmp/file1.txt root@172.20.10.3:/opt/
You will be asked to provide remote system’s root user password to transfer the file as shown below:
root@172.20.10.3's password:
file1.txt 100% 174KB 173.6KB/s 00:00
You can use the option -v with SCP to see the verbose output during the file transfer:
scp -v /tmp/file1.txt root@172.20.10.3:/opt/
Local to Remote Directories/Folders Transfers:
To transfer a directory named apt located inside /opt from a local system to the remote system directory /opt recursively use the following command:
scp -r /opt/apt root@172.20.10.3:/opt/
Provide remote system’s root user password to transfer the directory as shown below:
trustdb.gpg 100% 40 0.0KB/s 00:00
trusted.gpg~ 100% 22KB 21.7KB/s 00:00
mystic-mirage-pycharm-trusty.list 100% 146 0.1KB/s 00:00
ondrej-php.gpg 100% 364 0.4KB/s 00:00
minecraft-installer-peeps-minecraft-installer.gpg~ 100% 0 0.0KB/s 00:00
minecraft-installer-peeps-minecraft-installer.gpg 100% 378 0.4KB/s 00:00
projectatomic-ppa.gpg~ 100% 0 0.0KB/s 00:00
projectatomic-ppa.gpg 100% 1137 1.1KB/s 00:00
osmoma-audio-recorder.gpg 100% 353 0.3KB/s 00:00
nilarimogard-webupd8.gpg 100% 6541 6.4KB/s 00:00
webupd8team-java.gpg~ 100% 0 0.0KB/s 00:00
nilarimogard-webupd8.gpg~ 100% 0 0.0KB/s 00:00
mystic-mirage-pycharm.gpg 100% 366 0.4KB/s 00:00
webupd8team-java.gpg 100% 7140 7.0KB/s 00:00
osmoma-audio-recorder.gpg~ 100% 0 0.0KB/s 00:00
mystic-mirage-pycharm.gpg~ 100% 0 0.0KB/s 00:00
ondrej-php.gpg~ 100% 0 0.0KB/s 00:00
sources.list 100% 2951 2.9KB/s 00:00
sources.list.save 100% 2951 2.9KB/s 00:00
trusted.gpg 100% 23KB 23.2KB/s 00:00
Example:
Remote to Local Transferring:
Remote to Local File Transfers:
To transfer a file named hitesh.zip located inside /mnt directory of the remote to the local system’s directory /opt use the following command:
scp root@172.20.10.10:/mnt/hitesh.zip /opt/
You can increase the transfer speed by enabling the compression using the option -C with SCP as shown below:
scp -C root@172.20.10.10:/mnt/hitesh.zip /opt/
If your remote server uses SSH port 2022, then you can use -P option to specify the remote SSH port as shown below:
scp -P 2022 root@172.20.10.10:/mnt/hitesh.zip /opt/
Remote to Local Directory/Folders Transfers:
To transfer a directory named /etc from the remote system to local system’s directory /mnt recursively use the following command:
scp -r root@172.20.10.10:/database /mnt/
Example:
Remote to Remote System Transfers:
Remote to Remote File Transfers:
In order to transfer files and directories between two remote servers. You will need to configure SSH key-based authentication between both remote servers.
To transfer a file named /etc/rc.local from the one remote system (172.20.10.3) to another remote system’s (172.20.10.5) directory /opt use the following command:
scp root@172.20.10.3:/etc/rc.local root@172.20.10.5:/opt/
To transfer a directory named /mnt/apt from the one remote system (172.20.10.3) to another remote system’s (172.20.10.5) directory /opt use the following command:
scp -r root@172.20.10.3:/mnt/apt root@172.20.10.5:/opt/
Transfer Files and Directories with SCP in Windows (7, 8, 10, and Server)
If you are working on the Windows system and want to transfer files and directories from Windows to Linux and Linux to Windows system. Then, you can achieve this using WinSCP utility.
WinSCP is a free and open-source SCP and SFTP client for Windows based operating systems.
Transfer files between Windows and Linux system follow the below steps:
1. On the windows system, launch the WinSCP utility as shown below:
Now provide the following information:
- File Protocol : Select SCP as file transfer protocol.
- Host name : Provide your Linux server IP address.
- Port number : Provide your Linux server SSH port.
- User name : Provide the user name of your Linux server.
- Password : Provide your user’s password.
2. Now click on the Login button. You should see the following page:
Click on the Yes button to verify the host. Once you are connected to the Linux server, you should see the following page:
On the left pane, right-click on the file you want to upload on the Linux server and click on the Upload button as shown below:
Now, provide the path of the Linux server’s directory and click on the OK button. Once the file has been uploaded, you should see the following page:
3. On the right pane, right-click on the directory you want to download from the Linux server to the Windows system and click on the Download button as shown below:
Now, provide the path of the Windows system directory and click on the OK button. Once the file has been uploaded, you should see the following page.
Conclusion
In the above tutorial, we’ve learned how to transfer files and directories from Linux to Linux, Windows to Linux and Linux to Windows. Feel free to ask questions below in the comments section if you have any!
Transferring files between Linux and Windows might seem tricky at first, especially if you’re new to working across different operating systems. Now, whether you’re sharing documents, moving project files, or backing up data, knowing how to transfer files between these two platforms is very important.
In this blog, we’ll walk you through simple and effective methods to transfer files from Linux to Windows. From using shared networks and USB drives to leveraging powerful tools like Samba, SSH, and cloud services, we’ve got you covered. No matter your level of expertise, this guide will help you choose the best method for your needs and ensure your files are transferred quickly and securely.
Methods to How To Transfer File From Linux To Windows
Explore this section to get three methods that will help you in-order to transfer file form Linux system to Windows system.
Method 1: Using SSH Transfer Protocol with PuTTy
One of the easiest methods to transfer files from Linux (Ubuntu) to Windows OS is to use PuTTy pscp (PuTTy Secure Copy Client). PuTTy is used to create a client-server link to connect both platforms via a Wireless connection. PuTTy is a free open-source SSH client which works across multiple platforms and has become a mode for easy file transfers across platforms.
Step 1: Install SSH
- To start with Install SSH if you don’t have it in your Linux OS. Follow the Command prompt codes to do so.
Ubuntu/Debian OS
sudo apt update
sudo apt install ssh-server
sudo service ssh start
Red Hat and other Linux-based OS
sudo yum install openssh-server
sudo systemctl start sshd
Step 2: Install PuTTy
- Install PuTTy in your system if you don’t have it. Otherwise, ignore this step. If you want to install PuTTy in your Linux OS, follow the command prompt lines below:
For Ubuntu and Linux Mint OS
For Ubuntu, you’ll need to access the universal repository available and install PuTTy there. Hence, there are additional commands to access the universal repository below:
sudo add-apt-repository universe
sudo apt update
sudo apt install putty
For Debian OS
sudo apt-get putty
For Arch Linux OS
sudo pacman -S putty
For RHEL, Fedora, CentOS, AlmaLinux
sudo dnf install putty
For others
sudo yum install putty
Now you have successfully installed PuTTy in your Linux OS. Now, you can use it for file transfer from Linux to Windows and vice-versa. Similarly, you can also download PuTTy in Windows OS.
Step 3: Start Transferring Files
Transfer files across different OS. It becomes easy using PuTTy pscp (PuTTy Secure Copy Client). Simply provide the source path and the destination paths for file transfer and the files would be transfered.
Point to Note
In this case, the IP address of a sample Linux system is 192.168.0.18. Let’s see the skeletal structure of the command prompt line we’ll need to type:
[path_where_pscp_is_downloaded]>pscp user@[host:source destination]
Example 1:
For example, assume that PuTTy pscp is downloaded on the Windows Program Files directory and we’ll need to transfer files from Linux to Windows OS to send a file called “a.txt”. Follow the command prompt code below:
C:\Program Files\PuTTY>pscp user@192.168.0.18:/tmp/a.txt \Users\<username>
Example 2:
For vice-versa, to store the file in a new directory follow the code below:
Important: Check whether the directory exists or else, you’ll get an error. You can use the following command to create a new directory:
mkdir <directory_name>
C:\Program Files\PuTTY>pscp \Users\<username>\a.txt user@192.168.0.18:/<directory_name>
Now, you’ve successfully transferred files from Linux OS to Windows OS and vice-versa.
Method 2: Using FTP with FileZilla or Shared Network Folders
Another simple method used for file transfer is using FTP (File Transfer Protocol). This is the easiest method since this involves no coding/ command lines. Let’s see how to do that. If you don’t have FileZilla, check out How to install FileZilla on Windows. After installing FileZilla, follow the following steps.
Step 1: Download and Install FileZilla on Windows
- To trasnfer file from Linux to Windows you need a FTP server and for this you need to install FileZilla on Windows
Step 2: Open FileZilla
- Once the installation process is over open FileZilla on you Windows system.
Step 3: Open File
- Navigate to “File” section and select “Site Manager” after opening FileZilla.
Step 3: Choose SFTP Protocal
- Change the protocol to SFTP.
Step 4: Add Your Linux Address
- Type your Linux Address in the Host coloumn, which in this case is 192.168.0.18.
Step 5: Modify General Settings
- Under the General section, go to “Logon Type” and select “Normal” as shown in the image below:
Step 6: Enter the User Credentials
- Enter the Username and Password of the Linux OS machine.
Step 7: Share Files
- After all the 6 steps are done, click “Connect”.
- Now you’ve created a client-server connection with SFTP between Linux and Windows OS. After the connection is created, it is simply a matter of dragging and dropping files between the platforms mentioned earlier.
Method 3: Using SMB Protocol
One other way of transferring files from Linux to Windows is by connecting both OS systems using the SMB (Server Message Block) protocol. SMB can be used both in Windows and Linux to initiate a connection to share and transfer files.
Step 1: Use/ Install Samba in Linux
- Samba is an open-source software which provides clients with file and print services in a Windows-based network. This software supports connections between Windows systems and can be used to transfer files.
- To install Samba, type the following commands in your Linux terminal.
sudo apt install samba -y
- After successfully installing samba-client, check its status by typing the command:
systemctl status smbd
Step 2: Create a shared directory
- When transferring files from Linux to Windows, create a shared directory which will be used by both Linux and Windows OS. Follow the command below to see how to do so.
mkdir <directory_of_your_choice>
- Give administrative permission using the chmod command.
chmod 777 <directory_of_your_choice>
Note: There are several numbers in chmod which are used to give specific permissions. They are
- 777— everyone can read, write and edit (full access)
- 755— Owners can read, write and execute, and group users can read and edit the file.
- 644— Only owners can read, write and execute the files. The other people included by the owner can only view the file.
Step 3: Create a New uUer Specifically for File-Sharing
- While sharing files, create a new user whose account will be used for the sharing/ transfer of files. The command for this is
useradd <username>
Step 4: Give an SMB Password for the User
- To facilitate SMB protocol under the user, you must create an SMB password by executing the command below
smbpasswd -a <username>
- Then type out the password in the terminal.
Step 5: Edit the Config File in Samba Using Any Editor (or nano)
- Type out the command below
sudo nano /etc/samba/smb.conf
- After opening the file, scroll to the bottom of the file and add the following lines.
path = <directory_of_your_choice> valid users = <username> read only = no browsable = yes public = yes writable = yes browsable = yes
- Save and exit the file, then check if everything was edited and saved successfully by running the following command.
testparm
Step 6: Find the IP Address of Your Linux System
- Using ifconfig, find the IP address of your Linux system.
ifconfig wlo1
- Your IP address will be shown below:
Step 7: Connect to the Network from the Windows Side
- Launch the “Run” program by pressing the “Windows button” and “R”. Then type the IP address of the Linux system you got from the previous step. Type the IP address with two slashes before it.
- This will open the Linux-shared folders. Now you can view it and transfer files in between.
Methods 4 Use USB Drive (Easiest Method)
If you do not want to do any scription tasks or do not want to use FTP, then you can simple use USB drive to share files between Linux to Windows systems. Just insert your USB drive and copy all the files into the USB drive that you want to transfer into Windows. Once the copying task is completed, eject the USB drive from your Linux system, insert it into Windows system, and paste in anywhere in your Windows system.
Conclusion
Successfully transferring files from Linux to Windows can streamline your workflow and ensure that your data is accessible across different platforms. Whether you choose to use network sharing, SCP, or a USB drive, the methods covered in this guide provide you with the tools you need for efficient Linux to Windows file transfer. Understanding these techniques will help you handle cross-platform data management with ease.
Also Read
- How to Download a File from a Server with SSH / SCP?
- How to Troubleshoot SSH Connection Issues?
- How To Transfer Files From Android to iPhone?
In this tutorial I want to show you how to copy files from one computer to another on a network containing both Linux and Windows hosts, using the SSH protocol. Linux-to-Linux, Linux-to-Windows, and Windows-to-Linux file transfer can be accomplished with an SSH daemon running on one or more Linux hosts and/or a copy of Cygwin running on each Windows host. (For Windows-to-Windows file transfer, it’s much easier to just transfer files over SMB using Windows HomeGroup.) Here are the steps needed to make seamless file transfer over a heterogeneous network a reality:
Step 1: Install OpenSSH if it isn’t already installed
OpenSSH comes preinstalled on most Linux distros, but if it isn’t, you can install it by running the package manager for your distro on the openssh-server
package. For example:
$ sudo apt install openssh-server
Step 2: Generate an SSH host key file
Once OpenSSH is installed, you want to generate a host key for authenticating between the client and the server. You do this using the ssh-keygen
command.
$ sudo ssh-keygen -A -t ecdsa
In this command, the -A
option tells ssh-keygen
to create a host key file in /etc/ssh, as opposed to just a file in your home directory. The SSH daemon will not work unless you use a file in the host key format. The -t
option specifies what public key cipher is to be used. I’m using ECDSA, which is a digital signature algorithm based on elliptic curve cryptography. You can also use RSA or Diffie-Hellman, but ECDSA seems to be the de facto standard for SSH servers.
Step 3: Start the SSH server
Once you’ve created an SSH host key, you can start the OpenSSH server using the following command:
$ sudo /usr/bin/sshd
This starts up the OpenSSH server. (A lot of Linux systems will complain if you don’t provide the full file path for sshd
. I don’t actually know why.) Now you can log into your Linux system remotely from an SSH client.
Step 4: Install Cygwin on Windows
Cygwin is a program for Windows that emulates the POSIX API and command line interface, allowing you to run Unix/Linux software on Windows. It is the method I use to run an SSH client from a Windows computer. You can get the latest version of Cygwin from the Cygwin project’s website. Download the installer and then follow the installation instructions. Cygwin comes with an SSH client installed by default, so you won’t have to do anything special here.
Linux-to-Linux file transfer using scp
The scp
command transfers files to a remote host via the SSH protocol. The name is an acronym that stands for “Secure Copy” and it is an encrypted version of the earlier “Remote Copy” program rcp
. To do a remote copy using scp
, an SSH server must be running on the target machine.
To copy a file from one Linux machine to another using scp
, make sure an SSH server is set up on the destination host, then from the source host, type a command like this:
$ scp file michaelwarren@192.168.10.100:~
Let’s dissect this command now… The first argument is the file or files you want to transfer. The second argument is a specification for the destination which has the following structure:
<username> @ <hostname-or-ip-address> : <directory>
When I’m transferring files through scp
, my destination username will typically be the main non-root user on the destination machine and my destination directory will typically be that user’s home directory. This is because I often don’t have the proper permissions for other directories on the destination machine such as the OpenMediaVault volume on my Raspberry Pi NAS server. After I do this I go to the destination host (or do a direct SSH login) and move the file to the desired location.
If you want to transfer an entire directory, you add the -r
option to scp
like so:
$ scp -r dir michaelwarren@192.168.10.100:~
Windows-to-Linux and Linux-to-Windows file transfer
To copy a file from a Windows computer to a Linux computer via SSH, fire up the Cygwin terminal and cd
to the directory containing the file you want to transfer. The proper file path to use consists of the full Windows file path with all backslashes replaced with forward slashes, the colon after the drive letter removed, and the entire path preceded with /cygdrive/
. For example:
Windows file path:
C:\Users\MichaelWarren\Documents
Cygwin file path:
/cygdrive/c/Users/MichaelWarren/Documents
Once you are in the right directory, use the same scp
command you would use for a Linux-to-Linux file transfer.
In addition to uploading files to an SSH server, you can also download files by simply reversing the order of the arguments:
$ scp michaelwarren@192.168.10.100:~/file .
In this command, you use the user@host:path specification for the file on the remote host you want to download, followed by the directory on the local host to copy it to.
Note that in all of these file transfer methods, the scp
command is run from the SSH client, not the SSH server.
So that’s basically how you transfer files over SSH on a heterogeneous network. I hope you found this tutorial valuable. If you did, please consider sharing my content on social media, and also checking out some of the other Linux-related articles on my site. For now, farewell and happy command line hacking. 🙂
Published by psychocod3r
I’m an insane person who likes to mess around with computers and write about it here. I’m a geek of all trades and don’t like being limited or restricted to one topic, so if you’re coming here expecting some predictable cookie cutter shit, you’re going to be disappointed, sorry. I like to experiment and I like to try new things. I will stay mostly within tech though, so that’s one thing you can be sure of. I have a lot on this site, so you can use my sidebar widgets (bottom of the page if you’re on mobile) to find something that interests you.
View all posts by psychocod3r
Published