Tftp �������� ������ linux

How To Install, Configure, and Run Linux Tftp Client?

Tftp (Trivial File Transfer Protocol) is a very simple client-server protocol used to transfer data and files over the network. Ftp is a very popular protocol but it has a lot of features that may not be needed always. Tftp is a lightweight alternative to Ftp protocol. We can say that Tftp is a featureless protocol because it only downloads and uploads files.

  • Tftp has no authentication or authorization mechanism.
  • Tftp protocol does not have a file listing feature.
  • Tftp is clear text or not encrypted protocol
  • Tftp is fast and simple to implement
  • TFTP uses generally UDP

Install Tftp

The installation of Tftp tools is as simple as the protocol. As TFTP lightweight there is no dependency for other libraries.

Ubuntu, Debian, Mint, Kali:

We will install tftp for Debian, Mint, Ubuntu and Kali like below.

Fedora, CentOS, RedHat:

We can install tftp with the following command on Fedora, CentOS, RedHat.

tftp Command Syntax

We will use following syntax for tftp command in normal command-line usage.

tftp Command Help

Connect TFTP Server From Command Line

Connecting to the Tftp server is very easy. As stated at the beginning of the post Tftp does not have any authentication and authorization mechanisms. so Just providing the hostname of the server of IP address is enough to connect the Tftp server. In this example, we will connect 192.168.122.239 IP address.

TFTP Server Command Line Interactive Shell

After connection to the Tftp server, we will get an interactive shell. In this shell, we will issue commands to get information about status of the connection, download or get files, upload, or put files to the server. We can list available commands provided by Tftp shell with ? .

Upload or Put File To The TFTP Server

We can upload or put files to the TFTP server with the put command. In the example, we upload a file named body.txt

Download or Get File From TFTP Server

We can also download or get files from the Tftp server to get command. In the example, we get a file named body.txt from the Tftp server.

Show TFTP Connection Status

As TFTP works generally on the UDP protocol there is no session like TCP. But we can query current connection status with the status command. This status command will provide us information about the connected server IP address, current working mode, Rexmt-interval, Max-timeout, etc.

Disconnect From TFTP Server by Exiting From TFTP Shell

In order to quit from the Tftp shell we need to issue the q command.

Verbose Mode

While making transfer we may need more information about the transmission. We can get more information about the transfer with the verbose mode.

Источник

TFTP в Linux. Организация сервера TFTP

В репозиториях операционных систем на базе ядра Linux вы найдете множество серверов, реализующих протокол TFTP: некоторые делают упор на простоте конфигурации и малом потребление ресурсов, другие предоставляют расширенные возможности, но все они созданы с одной целью — принимать и отдавать файлы. Мы будем рассматривать настройку TFTP сервера в Linux на примере atftpd — сервера TFTP с расширенными возможностями. Будьте уверены, освоив atftpd, вы без труда справитесь с любым другим TFTP сервером в Linux.

Установка atftp в Linux

Попытка установить сервер atftpd из репозиториев приведет к установке еще одного сервера — одного из супер-серверов inet — демона, запускающего программы по событию, в данном случае по факту появления на 69 порту UDP запросов на подключение. Вы скажите: «А что же тут плохого?». Вообщем-то ничего, но если вы используете Debian версии 8 и выше или Ubuntu версии 15.04 и выше, то вы наверняка слышали о SystemD. SystemD — новый менеджер инициализации, пришедший на смену init. На конец 2015 года поддержка SystemD не реализована для серверов TFTP — мы сделаем это вручную. Поэтому, лучше устанавливать TFTP сервер из исходных текстов и сразу перейти в соответствующий раздел нашей статьи, но если вы всё же решили поизвести установку atftpd из репозиторией комадой

Читайте также:  Bootcamp windows 10 brightness

apt-get install atftpd

незабудьте остановить подтянувшийся inet и, собственно, сам atftpd

systemctl stop atftpd inetd

А также выключить их

systemctl disable atftpd inetd

Для избежания недоразумений также рекоменду удалить скрипт запуска atftpd из /etc/init.d/

И стереть его упоминание из конфигурационного файла inet с помощью, например редактора nano:

nano /etc/inetd.conf #удалите строчку, начинающуюся с tftp

Избежать всего этого поможет сборка TFTP сервера из исходных текстов. Для этого нужно скачать архив с исходниками например c сайта sourceforge с помощью wget

wget http://downloads.sourceforge.net/project/atftp/atftp-0.7.1.tar.gz #версия может отличаться

tar -xzvf atftp-0.7.1.tar.gz #версия может отличаться

Перейти в каталог с распакованным содержимым

cd atftp-0.7.1 #версия может отличаться

Выполнить конфигурационный скрипт, указав в качестве папки назначения /opt/atftp (вы, конечно, можете выбрать любую другую папку)

Создать эту папку

И, наконец, собранные файлы, закинуть в папку назначения

На последок почистим за собой

cd ..
rm -R atftp-0.7.1

и создадим символические ссылки на исполняемые файлы

ln -svi /opt/atftp/sbin/atftpd /sbin/
ln -svi /opt/atftp/bin/atftp /usr/bin/

Настройка TFTP сервера atftpd

TFTP сервер atftpd не читает никакой конфигурационный файл. Вместо этого все параметры ему передаются в качестве ключей запуска, например:

—logfile /PATH_TO_FLE #задает файл в который atftpd будет писать лог

—verbose=FROM_1_TO_7 # задает уровень документирования событий

—user USER.GROUP #задает от имени какого пользователя и группы будет запущен atftpd

—port PORT_NUMBER #задает UDP порт, который будет слушать сервер

—bind-address SERVER_IP_ADDRESS #задает IP адрес, который будет слушать сервер

В конце командной строки atftpd следует передать полный абсолютный путь до папки, в которой и будет осуществляться вся деятельность TFTP сервера в вашей ОС Linux

Далее мы рассмотрим несколько примеров сценариев запуска atftpd, в зависимости от которых нам понадобяться те или иные ключи запуска

Запуск atftpd из командной строки

Этот способ подойдет тем, хочет единовременно запустить TFTP сервер, отдать или принять файл и завершиться.

Минимальный набор команд будет такой:

atftpd —daemon —no-fork /mnt/share

Вы наверняка заметили два новых ключа запуска: «daemon» и «no-fork». Ключ «—daemon» заставляет atftpd «висеть» в ожидании соединения, а ключ «—no-fork» предотвращает его переход в фон. Когда все операции с передачей файлов будут завершены, мы сможете просто нажать Ctrl+C для завершения atftpd. Если же ключ «—no-fork» не использовать, то завершить процесс можно будет командой

Стоить отметить тот факт, что чтобы папка, которую мы передали TFTP серверу для работы, была доступна не только на чтение, но и на запись, нужно выдать это право обезличенному пользователю (anonymous), так как TFTP, как протокол, вообще не предусматривает никакой аутенфикации:

chmod -R o=rwx /mnt/share #папка может отличаться

Запуск atftpd автоматически при старте системы

Если вы хотите, чтобы atftpd запускался автоматически при старте компьютера, в системах на базе SystemD следует создать в дирректории /lib/systemd/system/ unit-файл atftpd.service для SystemD вот такого минимально содержания:

[Unit]
Description=Extended TFTP server

[Service]
Type=forking
ExecStart=/opt/sbin/atftpd —daemon /mnt/share

В параметре ExecStart нужно указать ту папку и бинарный файл atftpd, в которую вы его устанавливали, а также все ключи запуска, которые считаете нужными. Заметьте, что ключ «—no-fork» в данном случае противопоказан, а вот «—daemon» обязателен, так как по сценарию планируется, что atftpd будет «висеть» в системе постоянно, ожидая соединения

После того, как файл будет создан, нужно, чтобы SystemD перечитал свою конфигурацию

а затем активировать уже сам сервис:

systemctl enable atftpd.service

Теперь atftpd будет запускаться автоматически при старте системы. Вручную его можно запускать и останавливать командами

systemctl stop atftpd.service

systemctl start atftpd.service

Запуск atftpd автоматически по запросу

Мы с вами рассмотрели ситуацию, когда TFTP сервер atftpd, запущенный единожды при старте компьютера, остается «висеть» в системе, ожидая новых подключений. При этом вначале статьи упоминули, что при установке из репозиторией atftp тянет за забой супер-сервер inet, способный запускать atftpd только тогда, когда запрос реально поступает на сервер. Это очень удобно с той точки зрения, что пока TFTP не используется — он остановлен и не потребляет системных ресурсов. Так же мы отметили тот факт, что SystemD имеет такую функциональность «из коробки», и что необходимости теперь и в самом супер-сервере inet нет. Осталось научить SystemD это делать. Для этого SystemD должен сам слушать входящий порт на предмет поступления запросов и, в случае обнаружения, запустить atftpd и отдать ему сокет. Кроме того, после обработки соединения atftpd должен еще и корректно завершиться. Чтобы SystemD стал прослушить соответствующий UDP сокет, нужно создать unit-файл, описывающий этот сокет, и положить его туда же — в /lib/systemd/system/. При этом его имя должно соответствовать имени сервис-файла, который ему придеться запускать, за исключением суффикса, который нужно поменять с «.service» на «.socket». В нашем случае файл должен называться atftpd.socket. Создадим его вот с таким содержанием:

Читайте также:  Где найти скаченную windows 10

[Unit]
Description=TFTP socker for atftpd

Запись ListenDatagram=0.0.0.0:69 означает, что SystemD будет слушать порт UDP 69 на всех доступных ему IP адресах. Вы вправе (да и так будет лучше) указать конкретный IP адрес вашего сервера — это улучшит безопасность.

Но это еще не все. Раз мы выбрали способ запуска по событию, мы не хотим более, чтобы atftpd запускался автоматически при старте системы. Выключим его:

systemctl disable atftpd.service

И сам service-файл /lib/systemd/system/atftpd.service тоже подкорректируем:

  • убираем ключ «—daemon» — мы больше не хотим, чтобы atftpd «висел» в системе постоянно
  • добавляем ключ «—tftpd-timeout 10» — TFTP сервер корректно завершиться, если в течение 10 сек. к нему не поступит более обращений
  • добавляем параметр StandartInput=socket в секцию [Service], чтобы SystemD передавал сокет с данными на вход atftpd
  • удаляем секцию [Install] целиком — мы больше не хотим, чтобы atftpd запускался при старте системы

Должно получиться что-то вроде этого:

[Unit]
Description=Extended TFTP server

[Service]
ExecStart=/opt/atftp/sbin/atftpd —verbose=7 —logfile /var/log/atftpd —tftpd-timeout 10 /mnt/share
StandardInput=socket

Не забываем перечитывать конфигурацию SystemD:

И активируем наш сокет-файл

systemctl enable atftpd.socket

Можно перезагрузиться, можно включить сокет вручную:

systemctl start atftpd.socket

netstat -lupvn | grep 69

Можно увидеть, что порт 69 прослушивает некий «init», который на самом деле является символической ссылкой на SystemD

udp 0 0 0.0.0.0:69 0.0.0.0:* 1/init

При этот, если вы обратитесь к серверу каким-нибудь tftp клиентом, SystemD запустит atftpd и передаст ему клиента. А после того, как передача файлов завершиться, atftpd по истечению таймаута корректно завершиться.

Источник

Ubuntu / Debian Linux: Install and Setup TFTPD Server

H ow do I install and configure TFTP server under Debian or Ubuntu Linux server to configure networking equipment such as remote booting of diskless devices or remote loading of Unix like operating systems via PXE boot?

Tutorial details
Difficulty level Intermediate
Root privileges Yes
Requirements Debian/Ubuntu
tftpd-hpa
Est. reading time 10 minute

tftpd is a server for the Trivial File Transfer Protocol. The TFTP protocol is extensively used to support remote booting of diskless devices or loading operating systems. Debian or Ubuntu can use any one of the following tftpd server:

  • atftpd – Advanced TFTP server.
  • tftpd – Trivial file transfer protocol server.
  • tftpd-hpa – HPA’s tftp server.
  • dnsmasq – Lightweight DNS, TFTP and DHCP server.

In this tutorial, I am going to install and configure tftpd-hpa.

Warning : TFTP server / protocol provides little security. Make sure a TFTP server is placed behind a firewall system.

tftpd-hpa TFTP server installation

Type the following apt-get command as root user:
$ sudo apt-get install tftpd-hpa
OR
# apt-get install tftpd-hpa
You will be promoted as follows (make sure you set the directory name to /srv/tftp ):

Fig.01: Installing and Setting TFTPD Server In Ubuntu / Debian System

  • 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

Configuration

Edit /etc/default/tftpd-hpa, run:
# vi /etc/default/tftpd-hpa
Sample configuration:

How do I start / stop / restart tftpd-hpa server?

Type the following commands:

Fig.02: Starting / Stopping / Restarting the tftpd server commands

Next, you need to place all boot files in /srv/tftp directory. You can create a directory structure as follows for various operating systems and third party firmwares:
# cd /srv/tftp
# mkdir
# mkdir -p linux/
# mkdir -p firmwares/# ls -l
# ls -l linux/
# ls -l firmwares/

How do I test my tftpd server?

You need to install tftp client called tftp. It is the user interface to the Internet TFTP (Trivial File Transfer Protocol), which allows users to transfer files to and from a remote machine. The remote host may be specified on the command line, in which case tftp uses host as the default host.

Install trivial file transfer protocol client (tftp)

Type the following command:
$ sudo apt-get install tftp
OR
# apt-get install tftp
Sample outputs:

Test the tftpd server

In this example, I am putting pxeboot file (second-stage PXE bootstrap for network installs) from OpenBSD.org in /srv/tftp/openbsd/ directory to retrieve with a client, for testing purpose:
# cd /srv/tftp/openbsd/
# wget http://ftp.openbsd.org/pub/OpenBSD/5.2/i386/pxeboot
Sample outputs:

I am also downloading bsd.rd file. It is a compressed RAMDISK kernel; the embedded filesystem contains the installation tools:
# wget http://ftp.openbsd.org/pub/OpenBSD/5.2/i386/bsd.rd
Sample outputs:

Finally, verify that both files are downloaded and installed correctly at the /srv/tftp/openbsd/ location:
# ls -l /srv/tftp/openbsd/
Sample outputs:

Type the following command from the remote client:
$ tftp tftp-server-ip-here
$ tftp 192.168.1.5
Sample outputs (type the commands highlighted in green color at tftp> prompt):

Firewall configuration

Add firewall rules to your firewall script to open required ports:

Did it worked?

Now, you have DHCP and TFTP services available. Reboot the test system. Turn on PXE network boot in BIOS. Save and reboot the system. You will see information about he BIOS. Press [Enter] (or special key) to start pxe booting. A sample session:

Fig.03: Installing OpenBSD by booting the server via PXE

🐧 Get the latest tutorials on Linux, Open Source & DevOps via

Category List of Unix and Linux commands
Documentation help • mandb • man • pinfo
Disk space analyzers df • duf • ncdu • pydf
File Management cat • cp • less • mkdir • more • tree
Firewall Alpine Awall • CentOS 8 • OpenSUSE • RHEL 8 • Ubuntu 16.04 • Ubuntu 18.04 • Ubuntu 20.04
Linux Desktop Apps Skype • Spotify • VLC 3
Modern utilities bat • exa
Network Utilities NetHogs • dig • host • ip • nmap
OpenVPN CentOS 7 • CentOS 8 • Debian 10 • Debian 8/9 • Ubuntu 18.04 • Ubuntu 20.04
Package Manager apk • apt
Processes Management bg • chroot • cron • disown • fg • glances • gtop • jobs • killall • kill • pidof • pstree • pwdx • time • vtop
Searching ag • grep • whereis • which
Shell builtins compgen • echo • printf
Text processing cut • rev
User Information groups • id • lastcomm • last • lid/libuser-lid • logname • members • users • whoami • who • w
WireGuard VPN Alpine • CentOS 8 • Debian 10 • Firewall • Ubuntu 20.04

Comments on this entry are closed.

During and after the apt-get install, I never received the Package Configuration screen as you have shown here in the tutorial. How do I go about setting up the /srv/tftp directory after it has been installed or do I need to remove tftp and try again?

Hi,
Thanks for your post.
To avoid issues with the get/put action, I would recommend to add
–create
in the configuration of /etc/default/tftpd-hpa:

# vi /etc/default/tftpd-hpa
[…]
TFTP_OPTIONS=”–secure –create”
[…]

Thanks! And great comments!
–create option is very important if you want devices to write to tftp server as well.

Jeremy, I started to install tftpd last night and noticed the same thing. However, while I haven’t done it yet, I think you just need to continue with his instructions and execute ‘vi /etc/default/tftpd-hpa’ and set the directory there.

I tried to install it into Raspberry PI ( Debian Wheezy ) but an error occurs :

when a try to do this
$ tftp 192.168.1.5

tftp> status
Connected to 192.168.1.5.
Mode: netascii Verbose: off Tracing: off
Rexmt-interval: 5 seconds, Max-timeout: 25 seconds
tftp> get openbsd/pxeboot
“show this”
Transfer timed out.

I’ve got the same, you should put your IP adress in the configuration file (see with ifconfig).

Can you specify which configuration file you are referring to? is it the /etc/xinetd.d/tftp file to change? what should it be to add the ip address?

That seems to resolve the “Transfer timed out” in Debian Jessie.

After I edited /etc/default/tftpd-hpa to replace TFTP_ADDRESS=”0.0.0.0:69″ with my real IP (leaving the port at 69), it works.

This looks like a bug in the client or in the server.

Hi
I am new in linux n try to install tftpd-hpa server on my laptop but i got this massage on terminal :

was my installation fail or what?
i use ubuntu 13.10 saucy
Thanks for the help

Источник

Читайте также:  Realtek alc861 windows 10
Оцените статью