- Копирование файлов при помощи smbclient
- How to copy a directory from smb server to linux?
- 2 Answers 2
- copy file from windows to Linux
- 4 Answers 4
- Copy files between Linux and Windows
- Contents
- You are on a Linux host
- You want to access a Windows drive
- troubleshooting
- You want to share a folder
- You are on a Windows host
- You want to access a Linux drive
- You want to share a folder
- Linux copy file from smb
Копирование файлов при помощи smbclient
Попалась тут задачка. Есть сервер на Centos 7. В локальной сети без доступа в интернет от слова — совсем. Есть сервер под управлением Windows на котором есть сетевой диск Share_it$ с которого надо получить файлы из директории This. На сервере где стоит Centos есть только samba client (smbclient) и никакой возможности что-то еще доустановить -ни cifs-utils, ни smbfs. Ну что же, попробуем с тем что есть. В конце-концов smbclient — это что-то вроде ftp-client, следовательно он может и без посторонних утилит копировать файлы. Приступим.
- Определяем что можем подключиться к серверу SMB и посмотреть список открытых сетевых ресурсов:
Где 10.10.10.2 — адрес сервера с SMB ресурсом. Если выведет что-то вроде Access Denied — значит доступ в директорию ограничен и требуется ввести логин-пароль. Клиент их по идее должен запросить сам в интерактивном режиме.
На этом собственно всё. Мы скопировали файлы с удаленного smb-ресурса имея под рукой только smb-client
Источник
How to copy a directory from smb server to linux?
I’m trying to copy a directory from an smb link smb://source/path to a Linux machine
but I get a «No such file or directory» error
Any suggestion on how to perform this task?
2 Answers 2
You can try using an smbclient , which ships with Samba:
The client machine, in this case is acting as a server. It needs to have a folder or drive shared via SMB for this to work.
Unfortunately, rsync cannot directly access Windows SMB fileshares. You will need something that can communicate using the SMB protocol .
With smbclient , I believe you will want to do something like this:
Or you could use mount.cifs if you have it:
Of course, after successful mounting, you will be able to access /source_path as if it was a local path, so you could use cp -a to perform the copy also.
Alternatively, you might install DeltaCopy Server on the Windows system: it will provide a rsync -compatible server on the Windows side, and then you will be able to use rsync like this:
Note that in this case, the path at the source is based on a «virtual directory definition» configured at the DeltaCopy Server, and has nothing to do with Windows SMB shares.
Источник
copy file from windows to Linux
I am writing one script. it will run one linux machine. its targets includes linux, solaris and windows.
I know that i can use scp to copy files between *nix. but how about copying file from windows?
These windows are test machines, which can not be expected to have specific software installed, as the OS can be reinstalled often.
4 Answers 4
Samba provides a file sharing service compatible with Windows.
You can share a directory (for example /srv/samba/sharename ) on your Linux computer and access it from Windows like this: \\linuxservername\sharename . It doesn’t need any extra software on the Windows side.
Samba is included in most Linux distributions. Install it using the package manager, for example:
Ubuntu: sudo apt-get install samba smbclient
SUSE: zypper samba
CentOS/RedHat: yum install samba
To configure Samba, see:
or search Google to find a guide for your distribution.
Note that you may need to configure your Linux firewall, in case you use one, to accept connections to ports 137/tcp, 138/tcp, 139/tcp and 445/tcp (see this and this).
In the description above the Linux computer is a Samba server and Windows mounts a share from it.
In your comment below you mention that you’d like to automate the transfer process. This can be achieved by reversing the roles so that Windows acts as the server and Linux connects to it using smbclient .
With smbclient you don’t need to mount the Windows share at all. For example, to retrieve C:\Directory\file.txt and copy it to /tmp on your Linux computer do this:
-c Command to execute. See man smbclient for details.
-U Username and password for accessing the share specified as username%password
Modify it to your needs and add it to your script.
I know you said you can’t expect specific software to be installed, but there are SSH/SCP/SFTP clients for Windows which do not require any particular installation; only the executable being available. One that I keep turning to is PuTTY with its companion pscp and psftp tools, but I am certain that alternatives exist. pscp and psftp can be driven completely from the command line, and thus are well-suited for automation tasks. Both of them even have a -batch switch which is described as «disable all interactive prompts» and almost certainly can be leveraged.
Since you presumably already have a SSH/SCP/SFTP server installed and configured on the server, this avoids having to install any software on either host just for the purpose of copying those files.
Another upside might be the fact that PuTTY is open source under a permissive license, so if it doesn’t do what you want straight out of the box, it should be relatively easy to make it act the way you prefer.
The easiest way I found is using smbget
If authentication is needed (if password is not provided, it will prompt for password):
You can also specify where to save the file and the name of the file after copy:
I’m a CentOS 6 User so I tried this method on CentOS 6
Install samba using
Query for confirm
Create a Samba User.
Now create samba password for username sambashare using smbpasswd command.
Create a samba share directory
change the ownership for the share folder
]# chown -R sambashare:sambashare /share/
Open the file /etc/samba/smb.conf and add the below lines.
Start samba service
Check your configuration by using testparm command
Источник
Copy files between Linux and Windows
This describes how to copy files over the network between a computer (or virtual machine) running Windows and another computer (or virtual machine) running Linux.
There is also an article how to access a Linux partition when running Windows and how to access a Windows partition when running Linux. You may need this if your computer is running only one operating system and having two hard disk partitions.
Contents
You are on a Linux host
You want to access a Windows drive
So you are on a Linux computer and want to access a Windows drive over the network. This explains how. In this example we assume winhost is your Windows computer’s hostname (you can check the hostname by right clicking on My Computer and selecting Properties). Go to the Windows computer and open the Explorer. Share a folder by right-clicking onto it and selecting «Sharing and security». Call it «share1». Then, on your Linux computer,
- Open up your favorite file explorer, perhaps Konqueror or Nautilus
- In the address bar, type smb://winhost/share1
- You should now see the files and folders in that share. Double-click on them to open them up and view them.
troubleshooting
If that doesn’t work, then you may need to do something more complicated.
- install the samba client software
- try to find the share:
- If you see the share, mount it like this:
- after the next reboot, your mount will be lost. To make it persistant, add the following line to your /etc/fstab:
You want to share a folder
So you are on a Linux computer and want to share a folder so that also Windows machines can access it over the network. To do this, you run the SAMBA service on your computer. To enable sharing to Windows machines, right click on a folder in Nautilus; the menu should have an item called «Sharing Options». Click it and pick the name for your share. If you don’t have Windows folder sharing enabled yet, Nautilus will ask you for a password and install the service, after which you will need to log out and back in. The share should now be available on the Windows computer.
You are on a Windows host
You want to access a Linux drive
Use WinSCP. Choose the SFTP protocol; the login and password are the same as those you use when logging in locally. If it does not work, look at your Linux computer: Try to shut down your firewall and install the openssh service.
You want to share a folder
You can share files with Linux using normal Windows sharing mechanisms. The Linux host will be able to access these files using samba.
Источник
Linux copy file from smb
Машины с Linux (UNIX) могут также просматривать и монтировать SMB-ресурсы. Заметьте, что это может быть сделано когда сервером является либо машина с Windows, либо с сервером Samba!
Программа клиента SMB для UNIX-машин включена в дистрибутив Samba. Она обеспечивает ftp-подобный интерфейс командной строки. Вы можете использовать эту утилиту для переноса файлов между ‘сервером’ под управлением Windows и клиентом под Linux.
Большинство дистрибутивов Linux также включают полезный пакет smbfs, который позволяет монтировать и размонтировать SMB-ресурсы. Больше информации о smbfs можно получить дальше.
Для того, чтобы увидеть какие ресурсы доступны на данной машине, выполните команду:
где ‘host’ это имя машины, которую вы хотите видеть. Эта команда вернет список имен ‘сервисов’ — т.е. имен дисков или принтеров к которым может быть получен доступ. До тех пор, пока SMB сервер не будет настроен без управления доступом, он будет запрашивать у вас пароль. Введите в ответ на запрос пароль для пользователя ‘гость (guest)’ или ваш персональный пароль на этой машине.
Вывод этой команды должен выглядеть примерно так:
Browse list показывает другие SMB сервера в сети с доступными ресурсами.
Для использования клиента, выполните следующую команду:
где ‘service’ — имя машины и сервиса. Например, если вы пытаетесь обратиться к директории, которая доступна под именем ‘public’ на машине названной ‘zimmerman’, то имя сервиса должно звучать как \\zimmerman\public. Однако в следствии ограничений оболочки, вам необходимо спрятать обратный слэш, так что в итоге это командная строка выглядеть следующим образом:
где ‘mypasswd’ — символьная строка вашего пароля.
Вы получите приглашение smbclient:
Напечатайте ‘h’ чтобы получить помощь об использовании smbclient:
Если вы умеете использовать ftp, то вам не будут нужны справочные страницы о smbclient.
Хотя вы можете использовать smbclient для тестирования, вы скоро устанете использовать его в работе. Для работы вам скорее всего понадобится пакет smbfs. Smbfs поставляется с двумя простыми утилитами, smbmount и smbumount. Они работают подобно mount и umount для SMB-ресурсов.
Одно важное замечание: Чтобы использовать эти утилиты, у вас должна быть поддержка smbfs вкомпилированная в ядро!
Следующий пример показывает типичное использование smbmount для монтирования SMB-ресурса, названного «customers» с машины с именем «samba1»:
Запуск команды mount покажет вам, что ресурс смонтирован, точно также как и через экспорт NFS:
Пожалуйста прочитайте справочные страницы smbmount и smbumount для дополнительной информации о описанных выше операциях.
Источник