Raspberry pi 3 как включить wifi
Перейти к содержимому

Raspberry pi 3 как включить wifi

  • автор:

Sorry, you have been blocked

This website is using a security service to protect itself from online attacks. The action you just performed triggered the security solution. There are several actions that could trigger this block including submitting a certain word or phrase, a SQL command or malformed data.

What can I do to resolve this?

You can email the site owner to let them know you were blocked. Please include what you were doing when this page came up and the Cloudflare Ray ID found at the bottom of this page.

Cloudflare Ray ID: 7ed96ff44f883255 • Your IP: Click to reveal 178.132.110.58 • Performance & security by Cloudflare

Raspberry Pi: Enable SSH & Wifi on First Boot

And if you don’t, well, that’s an opinion and that’s okay. But for those of you who share my sentiment, you’ve likely found yourself in a similar situation:

You’ve got a brand new Pi, fresh from the oven — maybe it’s your first one — and now it’s time to boot it up! But… it’s just a little circuit board, it has no screen. No keyboard, touchpad or mouse either.

That’s no problem, though, it has an HDMI out! And (if you have the model B) 4 whole USB ports! So you reach into the nest of cables behind your tower to unplug your second monitor. Whoops, wrong one. Okay, next is a keyboard. You want to keep using your PC in case you need to troubleshoot, though. But there’s an old wired keyboard in the closet! Hmm, it’s a PS2 connection. You’re sure have an adaptor somewhere though…

And finally, hours later, your Pi is officially booted! But now it’s time for dinner and you’re kind of over the inital excitement of your new toy. And boy, do you not want to have to go through all of that again when you inevitably get your next Pi. I know I didn’t.

But, what if I told you it didn’t have to be this way? What if I told you we could skip all this inconvenience with nothing more than a couple little text files? What if I told you I thought I was going to make a Matrix reference, but Laurence Fishburne never actually says the words ‘what if I told you…’ in his monologue to Keanu?

Prep the SD Card

Note:

If you purchased a new Raspberry Pi, it probably came with a micro SD card. If it did not, pause here and aquire yourself one! We’ll need it to move any further.

Right, let’s take a step back here. Before we can do anything with the Pi we need to install an operating system to boot. The Raspberry Pi doesn’t use a traditional hard drive with a SATA connection — instead, the whole operating system runs from flash memory on a micro SD card. So let’s get ourselves an OS and prepare our SD card.

Download an Operating System

Raspberry Pi is almost 10 years old now and there are a host of operating systems that the little board can run, but today we’re going to use the standard Raspberry Pi OS developed by the Raspberry Pi Foundation for their namesake SBC. Head on over to the downloads page and choose the version that’s best for you.

Most of the time I don’t need a GUI for my Pis so I’m choosing Lite, but if you want a desktop, go for it! (If you do, the middle selection is probably the best choice — we can always install more software later, and the recommended software download is almost 2.5x the size.) We’ll talk a little later about using the GUI remotely.

Flash the Micro SD

Now to flash our OS onto the micro SD card. There are many different ways to accomplish this and today I’ll be using a Windows machine to flash the disk using balenaEcher (which is also available on Mac OS). Select your OS image, make sure you’re choosing the correct drive, and before you click Flash!, check again that you’ve chosen the correct drive. The flashing process may take a few minutes. (Hopefully you chose the correct drive.)

Enable SSH & WiFi

Notes:

  1. I’ve had trouble in the past getting the inital WiFi setup to work with other operating systems, such as DietPi. However, enabling SSH has always worked for me. If this is the case for you, just enable SSH, connect via ethernet and set up WiFi manually.
  2. If you have a model of Pi without WiFi capabilities, skip the “Enabling WiFi with wpa_supplicant.conf ” section. You can still enable SSH and connect to your Pi via ethernet.

You may need to eject and re-insert the card for it to show up in your filesystem. Once we’ve done that, you’ll notice the drive has been renamed boot and is full of new files. We don’t want to change anything in here, we’ll only be adding two new configuration files. Follow the instructions below to create the necessary files.

Enabling SSH

First, we’ll create an empty file named ssh with no file extension. If you’re using the terminal/command line, navigate into your mounted drive and enter one of the following commands based on your operating system. Easy!

Unix (Linux / Mac OS)
Windows

If you aren’t using the terminal/command line, this can also be done with a raw text editor like Notepad (or your favorite IDE). Simply open your editor and save the empty file with no extension — just make sure it’s a raw text editor (or IDE) and not a word processor like Microsoft Word!

Enabling WiFi with wpa_supplicant.conf

Next, we’ll specify our WiFi credentials with a file called wpa_supplicant.conf . Just like before, make sure to create this file with an IDE or raw text editor. Linux / Mac OS users can create and edit this file all in the terminal with the command nano wpa_supplicant.conf . Windows doesn’t offer a native way to edit files in the command line, but you can open Notepad easily with the command notepad wpa_supplicant.conf .

Unlike our ssh file, this one needs some content to have an effect. The example below is pretty basic, but it works for me. (If you have any trouble, check the documentation.) Just replace network_name with the SSID you’d like the Pi to connect to and replace password with the associated password.

And That’s It!

Finally we can eject our SD card, insert it into the Pi and power it up! Give it a few moments to boot, and a few moments longer for it to connect to the network if you’re using WiFi.

Connecting to the Pi

Now that our Pi is booted and connected to the network, we can connect to it with our local machine, but to do this we first need the Pi’s IP address. Often, the easiest way to do this is via the Devices list in your router’s web interface.

Your router’s IP address is typically something like 192.168.1.1 (mine is 192.168.0.1 ) and you can connect to it by visiting that IP address in your web browser, e.g. http://192.168.1.1/. All routers are different, but a quick Google search with your router’s make and model number plus the words “web interface” should help you navigate yours. If you don’t know the login credentials, they are usually printed on a label somewhere on the router.

Once there, navigate to your router’s Devices or Clilents list and look for an IP address with the hostname “raspberrypi” — this is the default for a machine running Raspberry Pi OS. My Pi was given the IP address 192.168.0.41 , yours will probably be different.

Notes:

If you aren’t having luck interfacing with your router, the Raspberry Pi Documentation offers up some additional terminal-based methods for determining your IP address.

Connect Over the Terminal with SSH

The time has come at last, we can finally connect with our Pi for real. Using our newly minted IP address, we’ll open up our terminal/command line and use the command ssh pi@<your-ip-address> to open a secure shell connection to the Pi. The default password for a new Raspberry Pi OS install is raspberry .

Connecting for the first time will look something like this:

A Little Housekeeping

Using our SSH connection, we’ll take two more quick steps to ensure our Pi is updated and secure:

  1. Remember that default password of raspberry ? That’s not terribly secure, so let’s change it with the command passwd .
  2. We’ll update and upgrade our software to make sure everything’s up to date. These commands will take a bit of time, but you can chain them together with “ & ”, automatically answer yes to the upgrade command with the flag “ -y ”, and go pour yourself some coffee while the process completes.

And congratulations, your Pi is ready to go! I can’t wait to see what you make with it!

Until next time

Appendix

Optional: Using the Desktop GUI Remotely with VNC

So you downloaded the Raspberry Pi OS with desktop and now you want to use the GUI instead of a boring old terminal connection? No problem, we can do that with VNC!

From Wikipedia:
Virtual Network Computing (VNC) is a graphical desktop-sharing system that uses the Remote Frame Buffer protocol (RFB) to remotely control another computer. It transmits the keyboard and mouse input from one computer to another, relaying the graphical-screen updates, over a network.

Raspberry Pi OS comes pre-loaded with RealVNC’s VNC Server, allowing it to be controlled remotely by another computer. To use it, we need to:

— Enable VNC Server on the Raspberry Pi
  1. Connect to your Pi via SSH using the instructions above.
  2. Start the configuration tool with the command sudo raspi-config . You’ll be met with a screen like this:
  3. Navigate to Interface Options , then VNC and answer ‘Yes’ when asked to enable VNC.
— Install VNC Viewer on our Local Machine and Connect!
  1. Visit the VNC Viewer download page and install the appropriate software on your local machine.
  2. Run the VNC viewer and enter your Pi’s IP address in the bar at the top of the window. (The application will warn us that it doesn’t regonize this server, which is normal since this is the first time we’ve connected to it.)
  3. Finally, enter your credentials and voilà! You can use the Raspberry Pi’s desktop right in the VNC Viewer window!

Troubleshooting: WiFi not Connecting?

Trying to connect via WiFi and can’t seem to find your Pi’s IP address on your network? First, make sure your model of Pi actually supports WiFi! Once you’ve done that, you may want to double-check the credentials in your wpa_supplicant.conf file and try again, but it’s typically faster and easier to just connect via ethernet, ssh into the machine and set up WiFi manually with the raspi-config tool.

  1. Connect to your Pi via SSH using the instructions above.
  2. Start the configuration tool with the command sudo raspi-config . You’ll be met with a screen like the one above.
  3. Choose System Options and then Wireless LAN . You’ll be asked for your SSID and password, and you’re done!

Welcome to the end. Thanks for reading, I hope you found something useful here today. If you would like to chat, you can email me. I’m also on LinkedIn and Polywork, I stream python programming very unreliably, and maybe if you tweet at me I’ll start using Twitter again. Maybe.

Raspberry Pi 3: настройка Wi-Fi на всех моделях в консоли и GUI

Приветствую! В этой статье мы посмотрим, как можно произвести настройку Wi-Fi в Raspberry Pi через консоль и не только. Аккуратно, точно, без воды от нашего вайфайного портала. Поехали!

Нашли ошибку? Есть дополнение? Обязательно напишите об этом в комментариях к этой статье. Помогите другим читателям решить их проблему!

Предупреждение

По умолчанию в Raspberry Pi нет Wi-Fi модуля. Он появляется только в модели Raspberry Pi 3. Для использования Wi-Fi можно использовать почти любой адаптер, подключенный через USB – донгл.

Raspberry Pi 3: настройка Wi-Fi на всех моделях в консоли и GUI

Ниже мы рассмотрим использование Wi-Fi для всех моделей. Просто напаситесь терпением или же перейдите сразу на интересующую вас главу. Будет рассмотрено подключение исключительно через консоль, так как через графический интерфейс особенных действий и не требуется – все понятно без лишних морок.

Видеоверсия

Проверка подключения

Прежде чем использовать Wi-Fi, предлагаю посмотреть, а находит ли его устройство вообще. Это очень актуально для подключаемых «свистков», но и на «третьей Малине» можно проверить – а вдруг с модулем что-то не в порядке.

Делаем так: подключаем наш модуль в USB порт, запускаем консоль через тот же Putty, вводим команду:

Должен вывестись список USB устройств, среди которых нам нужно найти наш адаптер, который обычно подписан как Wireless Adapter. Можно и сразу перейти во включенные адаптеры через команду:

Наш беспроводной адаптер обычно обозначается как wlan0 (стандартно для Linux, на котором и основан Raspbian). Здесь же уже после настройки конфигурационных файлов будет написан выданный IP адрес в случае удачного подключения. Рекомендую по завершению и перезагрузке еще раз воспользоваться этой командой.

Настройка интерфейса

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

Идем смотреть этот файл:

Его содержание должно быть примерно таким (верхнюю часть не трогаем, нас интересуют именно эти 4 строчки):

allow-hotplug wlan0
iface wlan0 inet manual
wpa-roam /etc/wpa_supplicant/wpa_supplicant.conf
iface default inet dhcp

Меняем их на это:

auto wlan0
iface wlan0 inet dhcp
wpa-conf /etc/wpa_supplicant/wpa_supplicant.conf

Получение списка сетей

Едем дальше, попробуем просканировать все окружающие нас сети через этот модуль:

Нашли нужную сеть? Запомнили ее SSID (имя сети)? Переходим непосредственно к подключению.

Подключение

На Linux удобно вводить данные для доступа к сети заранее. Делается это в файле:

В секции network здесь и указываются данные для авторизации в сети:

На самом деле минимально достаточно ввести два поля – ssid и psk, все остальное определится уже в процессе. Здесь показан вариант очень точной настройки в случае возникновения необходимости.

Если данные сохранены в файле верно (считайте, что это сделали автоматическое запоминание сети), то для подключения к любой доступной сети в нашем поле зрения достаточно выполнить команду:

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

Т.к. в конфигурации у нас указано dhcp – все найдет и подключится тоже самостоятельно.

Через графический интерфейс

Здесь все зависит от вашей версии операционной системы, но обычно подключение выглядит вот так:

Raspberry Pi 3: настройка Wi-Fi на всех моделях в консоли и GUI

Т.е. привычно – щелкнули по значку, выбрали нужную сеть среди доступных, ввели от нее пароль. Никаких предварительных настроек и изменений файла не требуется. В случае же необходимости точной настройки (как правило ручного назначения IP адреса) лучше это сделать через правую кнопку мыши и выйти вот на такое меню:

Raspberry Pi 3: настройка Wi-Fi на всех моделях в консоли и GUI

Вот и все. Если есть что дополнить или остались вопросы – пишите смело в комментарии. Вместе мы можем помочь друг другу и разрешить все вопросы в этой сфере!

Настройка сети Raspberry Pi 3

Основная операционная система предназначенная для Raspberry Pi — Raspbian — основана на Debian, поэтому и настройка сетевых интерфейсов здесь выполняется так же, как и в Debian. С проводным подключением всё достаточно просто. Вам достаточно подсоединить сетевой шнур к устройству, чтобы интернет начал работать. Немного сложнее настроить статический IP-адрес и беспроводное соединение с Wi-Fi.

Но, как бы там нибыло, без сети сейчас никуда. Поэтому в этой статье мы рассмотрим, как выполняется настройка сети Raspberry Pi 3 различными способами. Начнём с беспроводного подключения.

Подключение к Wi-Fi Raspberry Pi

1. Графический интерфейс

Проще всего подключиться к сети Wi-Fi через графический интерфейс. Для этого просто щёлкните по значку сети в верхнем правом углу экрана и выберите нужную сеть, затем введите для неё пароль:

Готово. Теперь подключение к Wi-Fi Raspberry Pi настроено.

2. raspi-config

Подключится к Wi-Fi через терминал ненамного сложнее. Здесь нам понадобится утилита raspi-config. Запустите её из главного меню и выберите Network Options:

Затем выберите Wi-Fi:

Дальше вам нужно ввести SSID вашей сети:

А потом пароль к ней:

Настройка завершена. Если проводного подключения нет, то устройство должно подключится к этой сети. Если вы не знаете, какой SSID (имя) у вашей Wi-Fi сети, смотрите следующий пункт.

3. Добавление Wi-Fi сети вручную

Сначала нужно посмотреть доступные Wi-Fi сети. Для этого используйте команду:

sudo iwlist wlan0 scan

Вам нужен параметр ESSID. Чтобы не хранить пароль к сети в открытом виде, воспользуемся утилитой wpa_passphrase для его шифрования:

Полученную конфигурацию сети нужно добавить в файл /etc/wpa_supplicant/wpa_supplicant.conf:

sudo vi /etc/wpa_supplicant/wpa_supplicant.conf

network= <
ssid=»UKrtelecom_367120″
#psk=»12345678″
psk=450c6c130a6308081a2c7cbc0af3653627b08c44478be55b0980e4bdf34ee74f
>

Далее попросить систему перечитать конфигурацию сетевых интерфейсов с помощью команды:

wpa_cli -i wlan0 reconfigure

Убедится, что всё прошло успешно, вы можете, выполнив:

Если после слов inet addr содержится IP-адрес, значит вы подключены к этой сети. Если же нет, проверьте правильность ввода ESSID и пароля. Также можно попытаться получить IP-адрес командой:

sudo dhclient wlan0

Если вы хотите пользоваться 5ГГц Wi-Fi, то кроме всего этого вам нужно указать вашу страну в wpa_supplicant.conf:

sudo vi /etc/wpa_supplicant.conf

Настройки Raspberry Pi Wi-Fi завершена. Теперь устройство будет автоматически подключаться к выбранной сети после загрузки.

Настройка статического IP Raspberry Pi

После того, как вы настроили доступ к сети, нужно настроить статический IP-raspberry pi 3, чтобы ваше устройство всегда было доступно в локальной сети по одному и тому же адресу. Как я уже говорил в статье про настройку Raspberry Pi 3 после установки, сначала статический IP для устройства нужно установить на роутере. Иначе возникнет конфликт IP-адресов, и ничего работать не будет.

Сначала выполните инструкцию из той статьи, а потом переходите дальше. За получение IP-адреса в Raspbian отвечает служба dhcpcd и конфигурационный файл /etc/dhcpcd.conf. По умолчанию адреса для всех интерфейсов запрашиваются у роутера по DHCP. Но вы можете настроить статический IP, добавив в конец файла несколько строк. Их синтаксис такой:

interface имя_интерфейса
static ip_address = нужный_ip_адрес/подсеть
static routers = ip_роутера
static domain_name_servers = ip_dns_сервера

В качестве имени интерфейса можно использовать:

  • eth0 — проводное подключение к интернету;
  • wlan0 — беспроводное подключение.

Если вы подключены к сети и получили все нужные данные по DHCP, то узнать IP-адрес роутера можно, выполнив команду:

Здесь он находится в колонке gateway. И вам осталось ещё узнать IP-адрес DNS-сервера, а для этого просто посмотрите содержимое файла /etc/resolv.conf:

Чтобы установить статический IP 192.168.1.5 для проводного интерфейса, нужно добавить в конец конфигурационного файла такие строки:

sudo vi /etc/dhcpcd.conf

interface eth0
static ip_address=192.168.1.5/24
static routers=192.168.1.1
static domain_name_servers=8.8.8.8 8.8.4.4

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

Выводы

В этой статье мы разобрали, как выполняется настройка сети Raspberry Pi 3, а также как подключится к Wi-Fi с помощью этого устройства. Вы можете выбрать более простой путь, настроив всё с помощью графического интерфейса или разбираться в способе настройки через терминал.

Обнаружили ошибку в тексте? Сообщите мне об этом. Выделите текст с ошибкой и нажмите Ctrl+Enter.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *