Как найти raspberry в сети

I need to find the Raspberry PI IP address on local network without connect the Raspberry to a monitor. How do I do it on Linux or Mac OS systems?

Pavel Fedotov's user avatar

asked Feb 24, 2014 at 13:29

J. Costa's user avatar

2

All raspberry devices MAC addresses started with B8:27:EB (for RPi4 B they start with dc:a6:32, replace where appropriate).

So, on *nix systems, this can be accomplished by executing the following command:

nmap -sP 192.168.1.0/24 | awk '/^Nmap/{ip=$NF}/B8:27:EB/{print ip}'

where 192.168.1.* will be your local network mask. You will get an answer like:

Nmap scan report for raspberrypi.localnetwork.lan (192.168.1.179)

The 192.168.1.179 is the Raspberry Pi IP address on you network.

If you are on a Mac system you can use Homebrew to install nmap:

brew install nmap

On Windows, you might use Wireshark and use the following display filter:

eth.addr[0:3] == B8:27:EB

enedil's user avatar

answered Feb 24, 2014 at 13:29

J. Costa's user avatar

J. CostaJ. Costa

2,4233 gold badges14 silver badges12 bronze badges

12

If you’re running MacOS or Linux, try this one:

$ arp -na | grep -i b8:27:eb

On windows, you can use:

arp -a | findstr b8-27-eb

On RPi 4B, you need to use different string for comparision (dc:a6:32:be:95). You can check it on your RPi by

ip -br link

There will be entries for each network card. eth0 is cable internet, wlan0 is the WiFi.

Ingo's user avatar

Ingo

41.4k15 gold badges81 silver badges192 bronze badges

answered Aug 19, 2015 at 8:45

mrded's user avatar

mrdedmrded

9616 silver badges5 bronze badges

6

I use mDNS/Bonjour to give my Pi a local name like pi.local. I dont need to know it’s IP address and this works for shortcuts and when you need to embed a link…

How and Why to assign a local name to your Pi

answered Feb 27, 2014 at 21:22

dfowler7437's user avatar

1

By default the raspberry’s name is raspberrypi. You can just ‘ping raspberrypi’ and the ICMP echo reply gives you the IP address. It worked for me. Make sure though the DHCP server is reachable as the raspberry’s NIC is by default in DHCP client mode. Otherwise the raspberry gets an APIPA address.

answered Jul 24, 2014 at 18:48

jan's user avatar

janjan

1111 silver badge2 bronze badges

2

If you want to use a GUI application for it, you can use Yakala tool (https://github.com/mozcelikors/yakala) for Debian/Ubuntu. This tool helps you not only search for available Type B and Type C networks, but also helps you to directly SSH into the network:

sudo add-apt-repository ppa:mozcelikors/yakala
sudo apt-get update
sudo apt-get install yakala

or

git clone https://github.com/mozcelikors/yakala
cd yakala && sudo ./install.sh

https://raw.githubusercontent.com/mozcelikors/yakala/master/docs/img/peekx2.gif

Disclaimer: I am the creator of Yakala. Any suggestions/bugs are taken very seriously.

answered Feb 18, 2018 at 11:33

mozcelikors's user avatar

mozcelikorsmozcelikors

2212 silver badges7 bronze badges

2

I use the free Fing app in my android smartphone. It scans the network and shows the connected devices by type, including Raspberry Pi, as well as scanning available ports. Handy to see if SSH, web or VNC are enabled and running.

Andy Anderson's user avatar

answered Jul 13, 2018 at 16:22

Tuxpilgrim's user avatar

TuxpilgrimTuxpilgrim

2212 silver badges6 bronze badges

In linux and MAC, you can also type in «arp — a» in the terminal and you can get a list of connected devices, look for the one with B8 in it, example: 192.168.4.5 @ B8… will be the raspberry pi IP.

answered May 7, 2015 at 13:59

FreshTendrils's user avatar

FreshTendrilsFreshTendrils

4631 gold badge7 silver badges13 bronze badges

Or you could access to your Router via browser and find your android device -almost every router GUI has a service where you can check all devices that are currently connected to your network.

answered Jan 9, 2018 at 10:45

FLBKernel's user avatar

FLBKernelFLBKernel

1611 silver badge2 bronze badges

If you run MacOS, use PiFinder, it is an application that will tell you the IP of a Raspberry Pi on your network.

Community's user avatar

answered May 7, 2015 at 13:46

FreshTendrils's user avatar

FreshTendrilsFreshTendrils

4631 gold badge7 silver badges13 bronze badges

In 2020, the accepted answer does not work anymore because the Raspberry Pi ships with a different range of MAC addresses. I could just add the «new» MAC as a comment, but the string could change again and again each model. Here is something that’s more future-proof.

$ sudo nmap -sP 192.168.150.0/24 |grep 'Raspberry Pi Trading' -B2
Nmap scan report for pi4-01.lan (192.168.150.186)
Host is up (0.037s latency).
MAC Address: DC:A6:32:1B:35:6A (Raspberry Pi Trading)

The main difference above: we don’t assume a MAC pattern, we just grep for the (summary), as this label is provided by nmap itself. Because nmap is continually updated, it contains internal tables of Raspberry Pi MAC addresses (or uses other criteria to detect) and we can assume that will continue working.

CAVEAT: If your scan does not identify all Pis you know are on the network, then repeat the scan — up to 10 times. A Pi which has networking Power Management:on might not always respond to a scan.

Power Management may be a problem for you if you are scanning for multiple Pis on a LAN, as repeat scans might detect one Pi but not another. In that case, repeat the scans look for differences. (To confirm if a Pi has Power Management enabled, ssh to the Pi and run: /sbin/iwconfig wlan0|grep Management)

answered Jun 9, 2020 at 11:50

Scott Prive's user avatar

Scott PriveScott Prive

2112 silver badges4 bronze badges

Copy the following into your Terminal/Console/Shell:

for i in $(jot - 1 254); do ping -t 1 192.168.1.$i && arp -a | cut -f 2,4 -d " " | tr [:lower:] [:upper:] | grep B8:27:EB; done

Please adapt 192.168.1. to your individual network.

The output will look something like this:

(192.168.1.109) B8:27:EE:DD:CC:A

192.168.1.109 would be your Raspberry Pi’s IP… :)

answered Feb 27, 2014 at 15:32

Wolf's user avatar

WolfWolf

914 bronze badges

Put this in pi.php on your web server:

<?php
$fp = fopen('pi', 'w');
fwrite($fp, $_REQUEST['ip'],1000);
fclose($fp);
?>

You may have to create the file pi on your web server with write permissions for your web server.

Put

curl http://yourwebserver/pi.php -d ip=`hostname -I`

in /etc/rc.local on your pi.

Get the IP of your pi by browsing http://yourwebserver/pi

answered Oct 29, 2017 at 14:16

darsie's user avatar

darsiedarsie

1511 silver badge1 bronze badge

When using a fresh install of NOOBS or Raspbian, the default hostname is «raspberrypi» and in some network configurations (i.e. if mDNS is in use and configured) you could use «raspberrypi.local». Another option is to run arp -a and look for raspberrypi

NOTE: This won’t work for every instance.

answered Aug 16, 2016 at 18:11

linuxgnuru's user avatar

linuxgnurulinuxgnuru

62510 silver badges21 bronze badges

1

My router assigns newly discovered systems an ip-address starting at 192.168.1.2, sequentially. I went through every system in my home one day and reserved addresses for them.

That way when I create a new system, chances are that its ip-address will be 192.169.1.18.

Another way to use the serial console. You can use a serial terminal program in order to log into your raspberry pi. I would suggest using the 8N1 (8-bits, no parity bit, 1 stop bit) setting with a speed (baud rate) of 115,200. You’ll need a USB to serial (3V3) connector.

answered Jul 13, 2018 at 17:27

NomadMaker's user avatar

NomadMakerNomadMaker

1,5608 silver badges10 bronze badges

‘Fing’ or ‘Net Analyzer’ on Android. Shows your whole network.

answered Jul 13, 2018 at 17:49

Andy Anderson's user avatar

If you are on Windows I suggest you to try out this script.
It is mostly based on the «arp -a» command, but it saves you some extra digging and helps you when your Raspberry Pi is not already in the Arp table.

Create a text file with the following content and rename it as find_raspberry_pi.bat

@echo off
:: This script, run from a Windows (10) machine, finds a Raspberry Pi on local network

:: You can manually set subnet if needed
:: E.g.
::SET subnet=192.168.56
SET subnet=

:: --- No need to edit below this line ---

SET raspIp=
SET myip=

:: Get IP for local PC
FOR /f "tokens=1-2 delims=:" %%a IN ('ipconfig^|find "IPv4"') DO SET myip=%%b
SET myip=%myip:~1%
echo IP for local PC: %myip%

:: Retrieve subnet if not manually set
IF "%subnet%" == "" (
    SETLOCAL EnableDelayedExpansion
    SET subnet=%myip%
    FOR /l %%a IN (1,1,31) DO IF NOT "!subnet:~-1!"=="." SET subnet=!subnet:~0,-1!
    SET subnet=!subnet:~0,-1!
    SETLOCAL DisableDelayedExpansion
)

:: Show subnet
echo Subnet: %subnet%
echo.

:: Loop through arp table entries and look for Raspberry Pis MAC addresses
echo Discovering network...
:: Ping all IPs in subnet from 1 to 254
FOR /L %%N IN (1,1,254) DO start /b ping -n 1 -w 200 %subnet%.%%N >nul
timeout 1 >nul
FOR /f "tokens=1" %%f  IN ('arp -a ^| findstr "28-cd-c1 b8-27-eb e4-5f-01 dc-26-32"') DO (
    IF NOT "%%f"=="" echo Found Raspberry Pi having IP %%f
)
echo.
pause

Disclaimers:

  1. I am not the author of the original script, I just adapted it a little bit to work with a Raspberry Pi. Sadly, I cannot find the original contributor.
  2. It’s not bullet-proof, it will not work if the subnet it starts scanning is not the correct one if you want to scan a different subnet you need to manually edit the appropriate line at the beginning of the script.

Still, I used it many times and it’s a simple solution.

UPDATE 2022:

I updated this script. Now:

  • it can find multiple Raspberry Pis at once
  • it can find allegedly all types of Raspberry Pis (3, 4, etc.)
  • you can manually force a specific subnet if the autorecognize feature finds the wrong one

find all pis

answered Apr 29, 2020 at 13:44

Kar.ma's user avatar

Kar.maKar.ma

1434 bronze badges

Try this first:

arp -a | grep -E --ignore-case 'b8:27:eb|dc:a6:32'

The two hex strings (b8:27:eb|dc:a6:32) in this command reflect the two OUI values used by «The Foundation» for production of all RPi devices — through RPi ver 4B as of this writing. If your RPi isn’t in your arp cache this command won’t yield anything useful. If that’s the case, then create the following file in your favorite editor, and save/write it as pingpong.sh:

#!/bin/sh

: ${1?"Usage: $0 ip subnet to scan. eg '192.168.1.'"}

subnet=$1
for addr in `seq 0 1 255 `; do
( ping -c 3 -t 5 $subnet$addr > /dev/null ) &
done
arp -a | grep -E --ignore-case 'b8:27:eb|dc:a6:32'

make it executable, and run it (use your network address here, not necessarily 192.168.1.):

$ chmod 755 pingpong.sh
$ ./pingpong.sh 192.168.1. 

Your results may appear as follows:

raspberrypi3b.local (192.168.1.131) at b8:27:eb:1:2:3 on en0 ifscope [ethernet]
raspberrypi4b.local (192.168.1.184) at dc:a6:32:2:3:4 on en0 ifscope [ethernet]

In this case, the hostname appears courtesy of mDNS. If you don’t have/don’t use mDNS/avahi/etc the hostname will be replaced by the character: ?.

answered Aug 27, 2020 at 20:07

Seamus's user avatar

SeamusSeamus

20.3k3 gold badges30 silver badges64 bronze badges

1

Raspbian is using a thing called mDNS, which allows you to access your raspberry pi by a hostname raspberrypi.local.

So, you don’t need to search for an IP address anymore, just connect like so:

ssh pi@raspberrypi.local

answered Nov 19, 2020 at 12:48

mrded's user avatar

mrdedmrded

9616 silver badges5 bronze badges

I assume you cannot connect to you PI, otherwise you’d know its IP.

If you go to your router page (usually something like 192.168.1.1 in your browser) there you should have a section with the already connected devices. You can try to plug and unplug the PI (and one device should appear / dissapear from the list)

answered Feb 24, 2014 at 13:42

javirs's user avatar

javirsjavirs

6601 gold badge6 silver badges19 bronze badges

I wrote myself a bash script to find my OctoPi a while ago.
You can change the systype=»Raspberry Pi» to whatever type of device you are looking for. It finds the subnet itself so you need not guess 192.168.1.0 or whatever.
There are now 3 different OUI ranges for the Pi Foundation:
https://udger.com/resources/mac-address-vendor-detail?name=raspberry_pi_foundation

B8:27:EB:xx:xx:xx   B8-27-EB-xx-xx-xx   B827.EBxx.xxxx
DC:A6:32:xx:xx:xx   DC-A6-32-xx-xx-xx   DCA6.32xx.xxxx 
E4:5F:01:xx:xx:xx   E4-5F-01-xx-xx-xx   E45F.01xx.xxxx 

So the ping grep answers need to add those

[andy@localhost ~]$ sudo ./findpi.sh

Searching 192.168.68.0/24 for Raspberry Pi systems
My address is wlp0s20f3:192.168.68.128

Found 1 Raspberry Pi system 
    Raspberry Pi system found at 192.168.68.124

I fixed it up a little and here it is:

#!/bin/bash
#-----------------------------------------------------------------#
#  Find PI bash script 
#   Andy Richter  
#   05/19/2021  I really wrote it in 2019 when I got my printer
#  This script will search the local subnet for Raspberry Pi systems  
#  The script requires root access for nmap
#
#   There are no parms we find things for ourselves
#------------------------------------------------------------------#
systype="Raspberry Pi"
#systype=Unknown
me=$(readlink --canonicalize --no-newline $0)
if [ "$EUID" -ne 0 ]
  then echo >&2 "Please run as root or use sudo $me"
  exit
else 
  if ! command -v nmap &> /dev/null
    then
       echo "nmap not found on this system. Please install. exiting"
       exit
  fi
fi
# awk doesn't like variables between /.../ 
awkstr="/^Nmap/{ipaddress=$NF}/$systype/{print ipaddress}"
 
# Use ip route to get the active rout to the internet, IP address and interface 
#  Then use that interface to find the subnet 
myrout=`ip route get 8.8.8.8`
myaddr=`echo $myrout | grep src| sed 's/.*src (.* )/1/g'|cut -f1 -d ' '`
mydev=`echo $myrout | grep dev| sed 's/.*dev (.* )/1/g'|cut -f1 -d ' '`
# now get our subnet
mynet=`ip -o -f inet addr show $mydev | awk '/scope global/{sub(/[^.]+//,"0/",$4);print $4}'`

printf "nSearching $mynet for $systype systemsnMy address is $mydev:$myaddrn"

# Use nmap to find PI systems. 'Raspberry Pi' is found in NMAP for PI systems
foundSys=`sudo nmap -sP $mynet | awk "$awkstr"`
foundPI=`echo $foundSys`
numpi=`echo "$foundPI" | awk '{print NF}'`
s=$([[ ($numpi == 1) ]] && echo " " || echo "s")
# Now we know, print the list if any

printf "nFound $numpi $systype system$sn"
for ipaddr in $foundPI
   do
     printf "t$systype system found at $ipaddrn"
   done

exit 0

Nmap output looks like:

Starting Nmap 7.70 ( https://nmap.org ) at 2021-05-01 15:57 EDT
Nmap scan report for 192.168.68.124
Host is up (0.021s latency).
MAC Address: B8:27:EB:58:CA:8F (Raspberry Pi Foundation)

answered Jun 1, 2021 at 19:07

Andy Richter's user avatar

ⓘ Cet article peut avoir été partiellement ou totalement traduit à l’aide d’outils automatiques. Nous nous excusons des erreurs que cela pourrait engendrer.

В учебниках часто просят подключиться к IP-адресу Raspberry Pi, но как найти этот IP-адрес?

Давайте посмотрим, как найти локальный IP-адрес вашего Raspberry Pi 3 разными способами, с графическим интерфейсом или без него.

Обратите внимание: когда в учебнике рассказывается об IP-адресе Raspberry Pi, обычно речь идет об IP-адресе внутри вашей локальной сети. Общедоступный IP-адрес, он используется для вашей идентификации во всем Интернете и фактически направлен на ваш модем, а не на вашу личную машину. Вы можете легко найти его на таких интернет-сайтах, как myip.com.

Необходимое оборудование

Чтобы следовать этому руководству, вам потребуются следующие материалы:

  • Raspberry Pi, подключенный к вашей коробке (в Ethernet или в Wi-Fi, не важно).
  • Его источник питания
  • SD-карта с установленной вашей ОС
  • Экран, на котором хотя бы одна мышь подключена к Pi, компьютеру или внешнему телефону.

В остальном мы предполагаем, что ваш Raspberry Pi включен и подключен к вашему компьютеру.

Как найти IP-адрес Raspberry Pi под Raspbian, подключенного к экрану.

Первый случай, который мы собираемся обсудить, — ваш Raspberry Pi работает на Raspbian, имеет дисплей и мышь.

Это простейший случай, вам просто нужно навести указатель мыши на значок сети в правом верхнем углу строки меню Raspbian, и через несколько секунд появится всплывающая подсказка с вашим IP адрес !

Рабочий стол Raspbian с всплывающим IP-адресом
Ваш IP-адрес является частью формата X.X.X.X, обычно вы можете удалить / 24, что означает, что первые 24 бита (первые три X) являются общими для всех машин в сети.

Имейте в виду, что вы найдете относительно эквивалентные методы для большинства других операционных систем, совместимых с Raspberry Pi. Таким образом, вы обычно можете найти IP-адрес вашего Raspberry в той части системы, которая предназначена для сетевого подключения.

Для информации: если у вас нет рабочего стола и есть только экран с командной строкой, вы можете ввести следующую команду в терминале вашего Raspberry Pi, чтобы узнать его IP-адрес:

hostname -I

Как узнать IP через интерфейс администратора модема

Если ваш Raspberry Pi не подключен к какому-либо дисплею, вы можете найти его IP-адрес в интерфейсе администрирования вашего модема.

Чтобы получить к нему доступ, откройте браузер и перейдите по адресу, указанному в документации производителя. Некоторые провайдеры доступа пишут это прямо на этикетке, приклеенной к коробке.

Но прежде чем вы потрудитесь просмотреть свои документы, попробуйте следующие адреса: http://192.168.0.1, http://192.168.0.254, http://192.168.1.1 и http://192.168.1.254.

Скорее всего, один из них соответствует вашему интерфейсу администратора.

Затем вам нужно будет подключиться (и в этом нет никакого волшебства, вам нужно будет пойти и прочитать этикетку на коробке), чтобы получить доступ к интерфейсу администратора.

После подключения вы, скорее всего, найдете страницу в панели администрирования, на которой можно увидеть все оборудование, подключенное к вашему модему.

Оранжевый интерфейс администрирования.
У Orange, например, это выглядит так.

Этот метод прост с технической точки зрения, но имеет два больших недостатка. Во-первых, вам придется заглядывать в свои бумаги или копаться в кабелях, чтобы найти идентификаторы. Во-вторых, на некоторых модемах функционал работает настолько плохо, что не отображается половина периферии.

Если у вас нет мотивации просматривать свои документы или ваш модем не отображает Raspberry Pi, в этом случае я рекомендую вместо этого метод ниже.

Найдите IP-адрес своего Raspberry Pi с другого компьютера в той же сети.

Если у вашего Raspberry Pi нет дисплея, вы можете найти его адрес с другого компьютера, подключенного к тому же устройству.

Для этого мы собираемся использовать инструмент под названием Nmap, который позволяет выполнять множество действий, связанных с обнаружением машин и портов в сети.

Установите Nmap в Linux

Преимущество Nmap в том, что его можно установить в Linux, Windows, Mac OS и даже Android с приложением «NetworkMapper».

Установить Nmap в Linux нет ничего проще, скорее всего, он есть в репозиториях вашего дистрибутива. Поэтому используйте свой менеджер репозитория для установки Nmap. Таким образом, для всех баз данных Debian (Debian, Ubuntu, Raspbian и т. Д.) Это дает:

sudo apt install nmap -y

Установите Nmap в Windows и Mac OS

Установить Nmap в Windows или Mac не намного сложнее. Все, что вам нужно сделать, это зайти на официальный сайт Nmap в раздел «Скачать» и следовать инструкциям для вашей версии системы.

Интерфейс Zenmap
В Windows и Mac OS используйте Zenmap, графический интерфейс Nmap.

Найдите IP-адрес вашего Raspberry Pi с помощью Nmap

Теперь, когда Nmap установлен, все, что вам нужно сделать, это просканировать сеть, чтобы найти свой Raspberry Pi.

Но перед этим сначала выключите Raspberry Pi и подождите 30 секунд. Вскоре вы поймете, почему.

Вы ждали 30 секунд? Хорошо, теперь давайте просканируем сеть с помощью следующей команды:

nmap -sP 192.168.0.1/24

Для Linux введите его прямо в терминал, для Windows и Mac OS запустите графический интерфейс Nmap под названием Zenmap и введите команду в поле «Команда».

Обратите внимание: в зависимости от вашего поставщика услуг вам может потребоваться 192.168.1.1/24 на месте.

Эта команда фактически попросит Nmap отправить пинг всем машинам, принадлежащим сети. 192.168.0.*.

Затем вы получите ответ с IP-адресами всех машин в вашей сети (а иногда и с их именами хостов).

результаты сканирования nmap
Отображаются IP-адреса машин в сети, иногда с именем хоста.

Это хорошо, но как мне теперь найти Raspberry Pi? Все очень просто. Поскольку мы отключили Raspberry Pi перед сканированием сети, его IP-адрес не отображается в списке.

Снова включите Raspberry Pi, подождите, пока он подключится к сети, и повторите команду. Сравните два списка адресов, IP, которого не было в первом списке, — это ваш Raspberry Pi!

Результат команды nmap
На мой взгляд, у моего Raspberry Pi IP-адрес 192.168.0.14!

Учтите все-таки, может появиться сразу несколько IP, потому что один IP не ответил на первую команду, либо другой устройство тем временем подключилось к сети.

В этом случае вам просто нужно попробовать разные IP-адреса, обычно их немного. Например, попытавшись подключиться к нему по SSH, если вы его активировали.

Иногда вам даже повезет, и имя хоста (которое часто содержит raspberry) будет отмечен на IP-адресе Pi!

Вы знаете IP-адрес своего Raspberry Pi, все, что вам нужно сделать, это подключиться к нему!

Иногда вам необходимо получить доступ к управлению Raspberry Pi в тех ситуациях когда вы не можете подключить монитор, например, когда микрокомпьютер уже уставнолен внутри какого-нибудь проекта. Или вы хотите произвести настроку системы, подключившись с вашего обычного компьютера. На этот случай в системе Raspbian есть целая куча удобных инструментов, мы постараемся рассмотреть основные из них.

Для всего, что описано в данной статье, необходимо чтобы Raspberry Pi был подключен к локальной сети по Wi-Fi или кабелем Ethernet. Если вас не интересует удаленный доступ, то вы можете перейти к следующему шагу настройки системы — «Работа с камерой».

Первым делом проверьте подключены ли вы к сети. Если ваш Raspberry Pi подключен к беспроводной сети, то рядом с часами вы увидите следующую иконку:

Иконка удачного подключения к беспроводной сети

Определение IP адреса

Все настройки сети и удаленного доступа желательно выполнить до начала работы с проектом, пока у вас еще есть возможность подключить монитор. Первое, что нам понадобится для удаленного подключения по сети — это определить IP адрес Raspberry Pi. Именно по этому адресу вы сможете обращаться к своему микрокомпьютеру.

Откройте терминал на Raspberry Pi и введите команду:

hostname -I

В ответ вы увидте следующее сообщение

Определение IP адреса

192.168.1.137 — это и есть ip адрес вашего Raspberry Pi. Дальше все подключения мы будем выполнять через него. 

VLC — доступ к графическому интерфейсу

VNC (Virtual Network Computing) — это система, которая позволяет удаленно контролировать графический интерфейс вашего Raspberry Pi. Т.е. вы можете подключиться к рабочему столу микрокомпьютера со своего обычного компьютера и полностью управлять им. Вы моежете не только просматривать что происходит на рабочем столе, но и управлять мышкой и клавиатурой.

Просмотр рабочего стола Raspberyy Pi с телефона

Во все свежие версии операционной системы Raspbian входит программа RealVNC, поэтому все что вам необходимо сделать для активации этой функции — это включить VNC в основных настройках Raspberry Pi. Выбираете «Enabled» в строке VNC во вскладке Interfaces, нажимаете ОК и перезагружаете систему.

Настройка дополнительных интерфейсов Raspberry Pi

Если вы работаете через консоль, то VNC можно включить через команду sudo raspi-config, в открывшемся окне переходите в Interfacing Options и выбираете VNC > Yes.

После перезагрузки вы увидите приветственно окно VNC сервера, обо будет ообозначать, что сервер готов к работе и вы можете к нему подключиться. Также в окне будет отображаться ip адрес вашего компьютера для подключения.

Окно VNC сервера

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

Если в операционной системе на вашем микрокомпьютере нет VNC сервер, тогда вы можете поставить его выполнив следующие команды в терминале:

sudo apt-get update
sudo apt-get install realvnc-vnc-server realvnc-vnc-viewer

Подключение к VNC серверу по локальной сети

Для того, чтобы начать управлять системой вам необходимо подключиться к VNC серверу, а для этого необходио скачать и установить VNC клиент. Самый распостраненный из них VNC Viewer. Он существует для всех операционных систем, а также доступен для Android и iOs. Вы можете выбрать нужную версию на официальном сайте. Скачайте, установите и откройте VNC Viewer для  вашей системы. Обратите внимание на то, что VNC сервер и клиент должны находится в одной локальной сети!

Прямое подключение через VNC

Не важно с какого устройства вы будете подключаться, принцип работы везде будет одинаковый. Мы покажем его на примере VNC Viewer для MacOs.

В открывшемся окне создайте новое подключение, выбрав «New connection…». Появится окно подключения, в котором необходимо ввести название подвключения и ip адрес сервера, к которому вы хотите подключиться. В нашем случае это 192.168.1.137.

Создание нового подключения по VNC

Также вы можете настроить дополнительные параметрые, такие как шифрование, качество передаваемой картинки, масштаб, работу кнопок. Во вкладке Expert вы моежете найти много более тонких настроек. Но для первого подключения нам понадобится только ip и название подключения. Сохраните подключение нажав кнопку «ОК». Новое подключение появится в списке подключений на главном экране. Дважды кликните по новому подключению.

Введите логин и пароль от вашего пользователя

В появившемся окне необходимо ввести имя пользователя и пароль пользователя под которым вы обычно работаете на вашем Raspberry Pi. В нашем случае это будет pi и пароль, который мы установили при настройке системы. Если вы не меняли пароль, то используйте пароль по-умолчанию raspberry. Через несколько мгновений VNC клиент подключится к серверу вы увидите рабочий стол своего микрокомпьютера. Теперь вы можете управлять им по сети!

Успешное подключение к VNC серверу

Воспользовавшись иконками в верхней части экрана вы можете посмотреть информацию о системе, отправить сообщения или файлы на удаленный компьютер.

Также если установить на Raspberry Pi пакет Common Unix Printing System (устанавливается через терминал командой sudo apt-get install cups), то вы сможете печатать файлы с VNC сервера на вашем обычно компьютере. 

Подключение к VNC серверу через интернет

Кроме обычно подключения по локальной сети RealVNC позволяет подключиться к вашему Raspberry Pi через интернет. Подключение через облако полностью шифруется и позволяет вам получить доступ к вашему микрокомпьютеру из любой точки мира. Нет необходимости дополнительно настраивать домашний роутер или знать ip адрес микрокомпьютера. Облачный сервис предоставляется бесплатно для обучения и некоммерческого использования, но имеет ограничения — к аккаунту можно подключить только 5 удаленных компьютеров. 

Подключение по VNC через облачный сервис

Все что вам необходимо для это сделать — это зарегистрировать аккаунт на сайте RealVNC, подтвердить адрес электронной почты и ввести данные нового аккаунта в настройках VNC сервера и клиента. 

На вашем Raspberry Pi откройте окно VNC сервера, нажмите на иконку меню в правом верхнем углу и и выберите «Licensing…». В появившемся окне необходимо выбрать первый пункт «Sing in to your RealVNC account» и нажать кнопку «Next >». На следующей странице введите электронную почту и пароль от аккаунта, который вы только что создали, и нажмите кнопку «Sing in».

Подключение VNC сервера к аккаунту RealVNC

 Программа войдет в вашу учетную запись и предложит ввести имя данного сервера, которое будет отображаться в списке серверов в вашем аккаунте. Придумайте подходящее имя и нажмите кнопку «Done». Сервер подключен к вашему аккаунту RealVNC, теперь вам необходимо добавить свой аккаунт RealVNC еще и в VNC клиент.

Откройте свой VNC клиент и нажмите на кропку «Sing in».

Подключение к аккаунту RealVNC с клиента

В появившемся окне введите логин и пароль от вашего RealVNC аккаунта и нажмите Sing in. Не закрывайте это окно. Вам на почту придет присьмо со ссылкой на подтверждение авторизации. Просто нажмите на кнопу «CONTINUE SIGNING IN» в письме и через несколько секунд VNC клиент подключится к вашему аккаунту.

Теперь в VNC клиенте кроме локальных серверов таже отображается список VNC серверов, к которым вы можете подключиться через интернет.

Подключение к Raspberry Pi через cloud RealVNC

Для подключения к удаленному серверу дважды кликните по его иконке.

Подключение по VNC к системе без монитора

Если вы используете Raspberry Pi в проекте без монитора, то вы можете подключиться к его графическому интерфейсу создав виртуальный рабочий стол! Для этого необходимо сначало подключиться к нему по SSH и ввести команду vncserver. В ответ вы получите адрес для подключения с указанием номера виртуального монитора, например, 192.167.1.147:1. Теперь подключитесь через ваш VNC клиент искользуя 192.167.1.147:1. Когда вы закончите работать с VNC сервером, необходимо будет через терминал прекратить работу виртуального рабочего стола, чтобы он не расходовал ресурсы системы. Для этого в терминале ввидте команду vncserver -kill :<display-number>. В нашем случае это будет vncserver -kill :1.

SSH — удаленный доступ через терминал

Все что надо сделать — включить в настройках и перезагрузить.

Доступ по ssh ключу — https://www.raspberrypi.org/documentation/remote-access/ssh/passwordless.md

Удаленный доступ к файлам

SFTP — начинает работать сразу как только мы вклювили ssh. Статья про то как копировать файлы, SCP — Copy files between your Pi and another computer using SCP (Secure Copy Protocol) — Работает также как SFTP. Также многие используют samba server (Samba/CIFS — Sharing folders from or to Windows-based devices). Еще есть netatalk для работы с маком, но надо проверить есть ли у него возможность выбора папки расшаривания или он только с папкой пользователя pi работает.

rsync — Synchronise folders between the Pi and another computer using  rsync over SSH, Resilio Sync

To connect to a Raspberry Pi using SSH or VNC, you need to know the Pi’s IP address.

If you use the Raspberry Pi with a monitor, you can check the Pi’s IP from the command line (terminal) by executing the hostname -I command.

Without a monitor and keyboard (headless) you can find the Raspberry Pi’s IP if you connect it to LAN (Local Area Network).

In this note i will show how to find the Raspberry Pi’s IP on network.

MAC Address Lookup: MAC addresses of the all devices of Raspberry Pi Foundation start with B8:27:EB:xx:xx:xx or DC:A6:32:xx:xx:xx.

Connect the Raspberry Pi to your local network and use one of the following commands, depending on your operating system, to find the Pi’s IP address.

Windows command prompt:

C:> arp -a | findstr /i "b8-27-eb dc-a6-32"

MacOS or Linux command line:

$ arp -a | grep -i "b8:27:eb|dc:a6:32"

Alternatively, you can find the Raspberry Pi’s IP using nmap command, but the solution with arp is much faster and does’t require installation of additional software:

$ sudo nmap -sP 192.168.1.0/24 | grep -i "b8:27:eb|dc:a6:32" -B2

Subnet: Replace 192.168.1 with the subnet for your LAN if it’s different.

Ping all IP addresses on LAN

If you have connected a Raspberry Pi to the network recently, the ARP table may not contain the Raspberry Pi’s IP and MAC addresses, as to be recorded Raspberry Pi has to send at least one packet to your computer.

To force this we can simply ping all IP addresses on LAN.

Windows command prompt:

C:> FOR /L %i IN (1,1,254) DO ping -n 1 -w 100 192.168.1.%i | FIND /i "Reply"

MacOS or Linux command line:

$ echo 192.168.1.{1..254}|xargs -n1 -P0 ping -c1|grep "bytes from"

As only the computer receives a response from Raspberry Pi, it records IP and MAC addresses in the ARP table and you can run the arp commands above to find them out.

Was it useful? Share this post with the world!

Find My Raspberry Pi Using NmapSo you have bought your Raspberry Pi but you don’t have a screen. How can you connect to it. Thankfully the Raspberry Pi has SSH enabled by default, enabling you to connect using SSH. An SSH connection will give you command line access to the Pi and you can use the SSH client on another Linux host or OSX system. Failing that you can install PuTTY in Windows. You know what, I need to know the IP Address of the Raspberry Pi and I don’t have it. Adding a screen to the Pi is a solution but it is beginning to feel a little like the song, there is a hole in my bucket. We are going to discover how we can: “Find My Raspberry Pi using NMAP”.

Keeping Hardware to the Minimum

We will demonstrate how we can connect to the Pi with just and Ethernet cable without the need of adding in a screen, keyboard or mouse. The Pi will have power and an ethernet cable and this is all.

Raspberry Pi is SSH Enabled

As we have already mentioned the Secure Shell Server is running by default on the Raspberry Pi, certainly in the Raspbian Distribution. Connecting is simple using the SSH client from another Linux host or Apple OSX system. On Windows based systems there is an SSH client available at no cost called PuTTY. You will need to download and install this. Once a connection has been made then you can work on the command line or install something like XRDP to allow remote desktop connections to the Pi. The difficulty we have to overcome is locating the IP Address of the Pi. This is the network address that we need to connect to.

Use Wired Connection

If you are using the Raspberry Pi 3 it does come with a built-in WiFi connection, however, at least to begin with we will need a wired connection as we have no method of specifying the WiFi network to connect to if we have not added a screen and keyboard. If using the Pi at home it will connect to the network through the ethernet cable to your hub where it will be assigned an IP Address. Great just what we want, but we will not know the address that has been issued. So we still have a problem!

Install NMAP

NMAP or the Network Mapper is a tool originally developed in 1997 for Linux. Availability is much better now with versions for OSX, Windows and Unix systems as well as the original Linux platform. NMAP can be used by system administrators in locating threats on their network, but we will see how we can find my raspberry pi using NMAP. Make sure that the host we install NMAP onto is on the same network as the Raspberry Pi need locating. In the video, we are using a CentOS Linux system and we install nmap using the command:

sudo yum install -y nmap

Using a Debian based system like Ubuntu or even Raspbian we would use the apt suite to install nmap:

sudo apt-get install -y nmap

Using the MAC Address To Identify a Pi

The MAC Address, or Media Access Control Address, of a host, identifies the serial number of the Network Card. This serial number can be traced back to a vendor. For the Raspberry Pi Foundation, the MAC Address will begin with the characters B8:27:EB. Scanning the network with nmap we can return hosts that are up and their MAC Address. Make you are running the command as root or with sudo as the MAC Address is not returned if you run the command as a standard user. I am using the address range 192.168.0.0/24 as that is the network that I have at home. You will need to adjust to match your network.

sudo nmap -sP 192.168.0.0/24

This should not take too long, perhaps 10 seconds or so. You can always hit the ENTER key to get an update on the progress of the scan. If you have many hosts connected to the network and this may include mobile phones and tablets then we can filter further by piping the result to AWK.

Using AWK to Search the Results

Each record for a running host will be printed in a format similar to the following. Firstly a listing start with Nmap and ends with the MAC Address:

Nmap scan report for 192.168.0.252
Host is up (0.0013s latency).
MAC Address: D4:85:64:1B:0A:FD (Hewlett-Packard Company)

We can see that this relates to an HP system from the returned MAC Address. The databases read by nmap to identify the MAC address prefix is the text file, /usr/share/nmap/nmap-mac-prefixes. The important information to note that the MAC address is display first and is followed on the next line with the IP Address. We really want to display just the IP Address fo those hosts that have a MAC address from Raspberry Pi. We do this with the following command.

sudo nmap -sP 192.168.0.0/24 | awk '/^Nmap/{ipaddress=$NF}/B8:27:EB/{print ipaddress}'

Piping the output of nmap to awk we can filter the displayed results. Breaking the awk command down:

/^Nmap/   Search the output for lines beginning with Nmap. This will yield lines similar to:

Nmap scan report for 192.168.0.254

{ipaddress=$NF}    The total number of fields in a record is shown by NF. We assign the last field to a variable IP address. The last field in the output is the IP address if we check the output from the previous command.

/B8:27:EB/  We now search for the MAC address of an RPi in the already filtered output.

{print ipaddress}    If we do match on both the Nmap and Mac Address searches we have found a Pi and we print the IP Address which awk previously stored.

If we wanted a simpler awk command that displays the complete matches upi may prefer this syntax.

sudo nmap -sP 192.168.0.0/24 | awk '/^Nmap/{print}/B8:27:EB/{print}'

The video follows.



Понравилась статья? Поделить с друзьями:
  • Как найти клиентов на печать
  • Как составить жалобу в надзор
  • Как найти потерянный портал в аду
  • Как найти площадь трапецыи
  • Как найти площадь круга через угол