- Копирование файлов scp
- Что такое SCP?
- Копирование файлов scp
- Выводы
- Copy Files Between Windows and Linux Using Command Line
- Copy File from Windows To Linux
- Copy File From Linux To Windows
- How to copy file from linux to windows server using c
- 7 Answers 7
- How to copy a file from remote server to local machine? [closed]
- 4 Answers 4
- Script to copy log files from linux server to windows shared server
- 2 Answers 2
Копирование файлов 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 один из таких инструментов.
Copy Files Between Windows and Linux Using Command Line
It is not always that you will need to copy a file from Windows to Linux or vice versa. But at times when you are automating things or trying to achieve some copy functionality using a script, it is good to have a utility to do that. Here is where pscp comes into play. Using pscp you can copy the file to/from windows and Linux. In this guide, I will go through the steps of doing the same.
Copy File from Windows To Linux
1. Download pscp.exe from here
2. copy the pscp.exe executable to the system32 directory of your windows machine. This folder normally exists in C:\Windows\System32 path.
3. Open PowerShell and use the following command to verify if pscp is accessible from the path.
4. Use the following format to copy the file to the Linux box.
- -pw for the password.
- replace password with the Linux user password.
- C:\Users\Admin\Desktop\test.txt represents the path of the file that has to be copied to the Linux system.
- 192.168.33.10 is the IP of the Linux server.
- /home/vagrant is the user-accessible path in the Linux system to copy the file.
If you are using private keys for authentications, you can use -i flag instead of -pw followed by the path to the .ppk file. If your key file is in pem format, you can use the puttygen command to convert it to ppk.
Info: Learn Linux & Windows administration from Pluralsight with its 10 days free account
For key-based authentication, the command looks like below.
Copy File From Linux To Windows
You can use pscp to copy files from Linux to windows. use the following command format for the same.
The above command will copy the file in Linux from the specified path to the Windows desktop.
How to copy file from linux to windows server using c
I have to create a C program which will run on Linux server. It will take information from Oracle database, create a local file and then copy that file to Windows server. I know how to create a local file on Linux server. But what is the way to copy it to windows server from C?
7 Answers 7
Mount Windows Share first and then create the file in the mounted directory.
It depends on the type of connectivty between the two machines and on the level of security you have to achieve.
The simplest scenario would be with the two machine on the same LAN and no particular security. In this case possible solution would be:
Samba : Share a directory on the Win machine, install/configure Samba on the Linux box. The C program will see the shared disk as a local disk under a specific path (e.g. /win/share).
NFS : Alternatively you can export a directory on Linux using NFS and install/configure an NFS product on the Win machine. I see this as a second option, if Samba cannot be used for any reason (e.g. security/authentication).
ftp : you will need an ftp server on the Windows machine. It also will be trickier to copy the file via a C program. If I’m not mistaken the ftp client on Linux is interactive and it is not supposed to be used in a script (or via another program) but you should check.
http : you will need an http server on the Windows machine and a page that would allow upload (IIS plus some asp page, should suffice) and use libcurl to dialog with it.
More complicated scenario when security is a concerm, would require the use of scp or sftp over and SSL connection. Also the libcurl with https could provide a good enough solution.
My advice is: try Samba first and see if meets your need, all the other options will require more work to you as a programmer.
How to copy a file from remote server to local machine? [closed]
Want to improve this question? Update the question so it’s on-topic for Stack Overflow.
Closed 5 years ago .
In my terminal shell, I ssh’ed into a remote server, and I cd to the directory I want. Now in this directory, there is a file called table that I want to copy to my local machine /home/me/Desktop . How can I do this?
I tried scp table /home/me/Desktop but it gave an error about no such file or directory. Does anyone know how to do this?
4 Answers 4
For example, your remote host is example.com and remote login name is user1:
The scp operation is separate from your ssh login. You will need to issue an ssh command similar to the following one assuming jdoe is account with which you log into the remote system and that the remote system is example.com:
The scp command issued from the system where /home/me/Desktop resides is followed by the userid for the account on the remote server. You then add a «:» followed by the directory path and file name on the remote server, e.g., /somedir/table. Then add a space and the location to which you want to copy the file. If you want the file to have the same name on the client system, you can indicate that with a period, i.e. «.» at the end of the directory path; if you want a different name you could use /home/me/Desktop/newname, instead. If you were using a nonstandard port for SSH connections, you would need to specify that port with a «-P n» (capital P), where «n» is the port number. The standard port is 22 and if you aren’t specifying it for the SSH connection then you won’t need that.
When you use scp you have to tell the host name and ip address from where you want to copy the file. For instance, if you are at the remote host and you want to transfer the file to your pc you may use something like this:
Example:
scp -P22 table fake_user@111.111.111.11:/home/me/Desktop/
On the other hand, if you are at your are actually on your machine you may use something like this:
Example:
scp -P22 [fake_user]@222.222.222.222:/remote/path/table /home/me/Desktop/
Script to copy log files from linux server to windows shared server
Need to create a shell script to copy all the logs everyday from Linux server to Windows Shared server.
sudo mount //192.168.1.250/PASSPORT2TB /home/pi/mntPassport -o username=root,password=********,vers=1.0
sudo mount //192.168.1.250/PASSPORT2TB /home/pi/mntPassport -o username=root,password=********,vers=1.0
mount error(112): Host is down Refer to the mount.cifs(8) manual page (e.g. man mount.cifs)
2 Answers 2
I use this way, on my network:
where //192.168.77.199 is my windows machine.
but, before, you can test if your share is ok, with:
Install SAMBA on the Linux box, share the logs folder (read only would suffice), and copy them from the Windows side.
EDIT: to share the folder, edit smb.conf , which is usually under /etc/samba/ . Add a section:
This will create a share called logs on the Linux machine, and it will correspond to whatever directory you provide under path .
Then copy the files from the Windows side, using Windows’ regular copy or xcopy commands, using \\linuxmachine\logs as the source. What else are you having a problem with?
In this scenario, the Linux machine is the file server and the Windows machine is the client, not vice versa like in the question.