상세 컨텐츠

본문 제목

053. Raspberry Pi 라즈베리 파이 - AP + WiFi Client on Raspberry pi 3 OR Raspberry pi zero w

raspberrypi/raspbian

by ZelKun 2020. 2. 4. 01:34

본문

반응형

2022/2/9 추가

buster(10) 에서 진행했던건데

bullseye(11) 에서는 iptables를 안써서 마지막에서 막힙니다

iptables를 설치해도 nftables 를 삭제하고 설정을 잡아야하는듯 하니 하위버전에서만 하시길..


053. Raspberry Pi 라즈베리 파이 - AP + WiFi Client on Raspberry pi 3 OR Raspberry pi zero w

외부에 들고다닐일이 생겼는데

WiFi Client +AP (Access Point) 를 사용할 수 있다니 해보기로 했습니다

 

참고로 아래설정을 자동화 시킨 github 소스를 찾아서 첨부, 시도해보진 않음

https://gist.github.com/aceisace/b7ca22b50531f43d48c74d86eb62c89a

 

Raspberry Pi: AP + client mode

Raspberry Pi: AP + client mode. GitHub Gist: instantly share code, notes, and snippets.

gist.github.com

 


주의
raspberry pi 3 이더넷(eth0) 비활성화 됨
참고한 글 자체가
라즈베리 ZERO W를 대상으로 해서
interface / iptable 등 eth0 설정이 없음

현재로선 들고다니는 용도라 만족

 

interface 설정 추가, iptable설정은 몰라서 놔둠

설정파일 전부 첨부, 경로는 하단 참고

crontab도 하단 참고 바람

70-persistent-net.rules
0.00MB
dnsmasq.conf
0.03MB
hostapd
0.00MB
hostapd.conf
0.00MB
interfaces
0.00MB
start-ap-managed-wifi.sh
0.00MB
wpa_supplicant.conf
0.00MB


사양

pi@raspberrypi:~ $ lsb_release -a
No LSB modules are available.
Distributor ID: Raspbian
Description: Raspbian GNU/Linux 10 (buster)
Release: 10
Codename: buster


pi@raspberrypi:~ $ uname -a
Linux raspberrypi 4.19.75-v7+ #1270 SMP Tue Sep 24 18:45:11 BST 2019 armv7l GNU/Linux


pi@raspberrypi:~ $ cat /proc/cpuinfo 
processor : 0
model name : ARMv7 Processor rev 4 (v7l)
BogoMIPS : 38.40
Features : half thumb fastmult vfp edsp neon vfpv3 tls vfpv4 idiva idivt vfpd32 lpae evtstrm crc32 
CPU implementer : 0x41
CPU architecture: 7
CPU variant : 0x0
CPU part : 0xd03
CPU revision : 4


. . .


Hardware : BCM2835
Revision : a02082
Serial : 00000000
Model : Raspberry Pi 3 Model B Rev 1.2
pi@raspberrypi:~ $ 

전형적인 Pi 3 B+ 모델


사전준비

update & upgrade

sudo apt update -y && sudo apt upgrade -y

admin@admin ~ % ssh pi@192.168.0.18
pi@192.168.0.18's password: 
Linux raspberrypi 4.19.75-v7+ #1270 SMP Tue Sep 24 18:45:11 BST 2019 armv7l


The programs included with the Debian GNU/Linux system are free software;
the exact distribution terms for each program are described in the
individual files in /usr/share/doc/*/copyright.


Debian GNU/Linux comes with ABSOLUTELY NO WARRANTY, to the extent
permitted by applicable law.
Last login: Sat Feb  1 09:11:12 2020 from 192.168.0.10
pi@raspberrypi:~ $ sudo apt update -y && sudo apt upgrade -y
Get:1 http://archive.raspberrypi.org/debian buster InRelease [25.2 kB]
Get:2 http://raspbian.raspberrypi.org/raspbian buster InRelease [15.0 kB]   
Fetched 40.2 kB in 2s (18.0 kB/s)   
Reading package lists... Done
Building dependency tree       
Reading state information... Done
65 packages can be upgraded. Run 'apt list --upgradable' to see them.
Reading package lists... Done
Building dependency tree       
Reading state information... Done
Calculating upgrade... 10%

관련 패키지설치

sudo apt-get install hostapd dnsmasq -y

pi@raspberrypi:~ $ sudo apt-get install hostapd dnsmasq -y
Reading package lists... Done
Building dependency tree       
Reading state information... Done
The following additional packages will be installed:
  dns-root-data dnsmasq-base
The following NEW packages will be installed:
  dns-root-data dnsmasq dnsmasq-base hostapd
0 upgraded, 4 newly installed, 0 to remove and 0 not upgraded.
Need to get 1,052 kB of archives.
After this operation, 2,666 kB of additional disk space will be used.
Get:1 http://archive.raspberrypi.org/debian buster/main armhf dnsmasq-base armhf 2.80-1+rpt1 [400 kB]
Get:2 http://archive.raspberrypi.org/debian buster/main armhf dnsmasq all 2.80-1+rpt1 [16.5 kB]
Get:3 http://ftp.harukasan.org/raspbian/raspbian buster/main armhf hostapd armhf 2:2.7+git20190128+0c1e29f-6+deb10u1 [630 kB]
Get:4 http://ftp.harukasan.org/raspbian/raspbian buster/main armhf dns-root-data all 2019031302 [5,396 B]
Fetched 1,052 kB in 3s (304 kB/s)        
Selecting previously unselected package hostapd.
(Reading database ... 41824 files and directories currently installed.)
Preparing to unpack .../hostapd_2%3a2.7+git20190128+0c1e29f-6+deb10u1_armhf.deb ...
Unpacking hostapd (2:2.7+git20190128+0c1e29f-6+deb10u1) ...
Selecting previously unselected package dns-root-data.
Preparing to unpack .../dns-root-data_2019031302_all.deb ...
Unpacking dns-root-data (2019031302) ...
Selecting previously unselected package dnsmasq-base.
Preparing to unpack .../dnsmasq-base_2.80-1+rpt1_armhf.deb ...
Unpacking dnsmasq-base (2.80-1+rpt1) ...
Selecting previously unselected package dnsmasq.
Preparing to unpack .../dnsmasq_2.80-1+rpt1_all.deb ...
Unpacking dnsmasq (2.80-1+rpt1) ...
Setting up dnsmasq-base (2.80-1+rpt1) ...
Setting up dns-root-data (2019031302) ...
Setting up dnsmasq (2.80-1+rpt1) ...
Created symlink /etc/systemd/system/multi-user.target.wants/dnsmasq.service → /lib/systemd/system/dnsmasq.service.
Setting up hostapd (2:2.7+git20190128+0c1e29f-6+deb10u1) ...
Created symlink /etc/systemd/system/multi-user.target.wants/hostapd.service → /lib/systemd/system/hostapd.service.
Job for hostapd.service failed because the control process exited with error code.
See "systemctl status hostapd.service" and "journalctl -xe" for details.
Created symlink /etc/systemd/system/hostapd.service → /dev/null.
Processing triggers for systemd (241-7~deb10u2+rpi1) ...
Processing triggers for man-db (2.8.5-2) ...
Processing triggers for dbus (1.12.16-1) ...
pi@raspberrypi:~ $ 

wlan0 mac address 확인

ip addr or iw dev

pi@raspberrypi:~ $ ip addr
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1000
    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
    inet 127.0.0.1/8 scope host lo
       valid_lft forever preferred_lft forever
    inet6 ::1/128 scope host 
       valid_lft forever preferred_lft forever
2: eth0: <NO-CARRIER,BROADCAST,MULTICAST,UP> mtu 1500 qdisc pfifo_fast state DOWN group default qlen 1000
    link/ether b8:27:eb:b7:04:a3 brd ff:ff:ff:ff:ff:ff
3: wlan0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP group default qlen 1000
    link/ether b8:27:eb:e2:5d:55 brd ff:ff:ff:ff:ff:ff
    inet 192.168.0.18/24 brd 192.168.0.255 scope global noprefixroute wlan0
       valid_lft forever preferred_lft forever
    inet6 fe80::2368:8d9f:5b83:e930/64 scope link 
       valid_lft forever preferred_lft forever

우선 wlan0 물리주소를 확인합니다

link/ether b8:27:eb:e2:5d:55 으로 확인되네요


가상 interface rule 등록

udev에 룰(rules)파일 하나 만들건데
파일명은 뭘해도 상관은 없는듯, 이름순으로 실행된다고 합니다
sudo vim /etc/udev/rules.d/70-persistent-net.rules

pi@raspberrypi:~ $ sudo vim /etc/udev/rules.d/70-persistent-net.rules


SUBSYSTEM=="ieee80211", ACTION=="add", KERNEL=="phy0", \
  RUN+="/sbin/iw phy phy0 interface add ap0 type __ap", \
  RUN+="/bin/ip link set ap0 address b8:27:eb:e2:5d:55"
                                                                                                                               
-- INSERT --                                                  3,55          All

가상 인터페이스라 mac address는 임의로 해도 될 것 같은데
바꿔보니 AP에 붙었을때 ISP(외부 인터넷)에 연결이 안되네요

 

사전에 확인한 wlan0 물리주소를  address 부분에 넣어줍니다
interface add ap0 를 보면 가상인터페이스를 추가 하고 이름을 ap0 로 준걸 알 수 있습니다
모든 라인이 한줄에 있어야 한다고 하니 주의 행변환 \ 는 문자열이 안끝난걸 의미합니다

 

좀더 세부설정

SUBSYSTEM=="ieee80211", ACTION=="add", ATTR{macaddress}=="b8:27:eb:*:*:*", KERNEL=="phy0", \
  RUN+="/sbin/iw phy phy0 interface add ap0 type __ap", \
  RUN+="/bin/ip link set ap0 address b8:27:eb:*:*:*"

보시면 address 에 b8:27:eb:*:*:* 로 되있는데

라즈베리 wifi 물리주소가 b8:27:eb 로 시작하네요

* (like) 사용으로 SD카드를 다른 Pi3에 껴도 mac주소를 수정할 필요가 없어집니다

주의할점은 모든 라인이 한줄에 있어야 한다고 하니 주의, 행변환 \ 는 문자열이 안끝난걸 의미합니다

 

무선랜 인터페이스 확인

iw dev

pi@raspberrypi:~ $ iw dev
phy#0
Unnamed/non-netdev interface
wdev 0x2
addr fe:60:32:0f:a0:19
type P2P-device
txpower 31.00 dBm
Interface wlan0
ifindex 3
wdev 0x1
addr b8:27:eb:e2:5d:55
ssid SSID
type managed
channel 4 (2427 MHz), width: 20 MHz, center1: 2427 MHz
txpower 31.00 dBm
 

사용가능한 WiFi 인터페이스가 보이는데 추가한 ap0는 안보이네요
rule 을 등록한다고 바로 생기진 않나봐요
reboot을 하면 ap0 확인 할 수 있습니다

안 나온다면 rules 설정을 잘못한거니 다시 확인이 필요


# 이후 설정실수는 wlan0이 비 활성화 될 수 있으니 주의 #

모든 설정파일을 백업하고 진행하시면 복구하기 편합니다


dnsmasq.conf 수정

sudo cp /etc/dnsmasq.conf /etc/dnsmasq.conf.org
sudo vim /etc/dnsmasq.conf

pi@raspberrypi:~ $ sudo cp /etc/dnsmasq.conf /etc/dnsmasq.conf.org
pi@raspberrypi:~ $ sudo vim /etc/dnsmasq.conf


# Include all files in a directory which end in .conf
#conf-dir=/etc/dnsmasq.d/,*.conf


# If a DHCP client claims that its name is "wpad", ignore that.
# This fixes a security hole. see CERT Vulnerability VU#598349
#dhcp-name-match=set:wpad-ignore,wpad
#dhcp-ignore-names=tag:wpad-ignore


# Delays sending DHCPOFFER and proxydhcp replies for at least the specified number of seconds.
dhcp-mac=set:client_is_a_pi,B8:27:EB:*:*:*
dhcp-reply-delay=tag:client_is_a_pi,2


interface=lo,ap0
no-dhcp-interface=lo,wlan0,eth0
bind-interfaces
server=8.8.8.8
domain-needed
bogus-priv
dhcp-range=192.168.10.2,192.168.10.255,255.255.255.0,24h


-- INSERT --                                                  693,39        Bot

사전준비에서 설치한 dnsmasq 설정파일을 수정합니다

B8:27:EB:*:*:* 가 눈에 띄는데

저 부분을 WiFi 동글 물리주소로 바꿔봤는데, 결론적으로 실패

아마 오래된 동글이라 Dual을 지원안하는듯 사실 디바이스 쪽은 관심이 없어서 잘 모름..


hostapd.conf 생성

sudo vim /etc/hostapd/hostapd.conf

pi@raspberrypi:~ $ sudo vim /etc/hostapd/hostapd.conf


ctrl_interface=/var/run/hostapd
ctrl_interface_group=0
interface=ap0
driver=nl80211
ssid=raspberry
hw_mode=g
channel=11
wmm_enabled=0
macaddr_acl=0
auth_algs=1
ignore_broadcast_ssid=0
wpa=2
wpa_passphrase=raspberry
wpa_key_mgmt=WPA-PSK
wpa_pairwise=TKIP CCMP
rsn_pairwise=CCMP


~                                                                               
"/etc/hostapd/hostapd.conf" 16L, 276C                         11,23         All

파일이 없으니 만들어 주면됩니다
ssid, wpa_passphrase (passwd) 를 raspberry 로 해놨는데 바꿔도 됩니다

 

상세 설명

# Set the channel (frequency) of the host access point
channel=1
# Set the SSID broadcast by your access point (replace with your own, of course)
ssid=yourSSIDhere
# This sets the passphrase for your access point (again, use your own)
wpa_passphrase=passwordBetween8and64charactersLong
# This is the name of the WiFi interface we configured above
interface=uap0
# Use the 2.4GHz band (I think you can use in ag mode to get the 5GHz band as well, but I have not tested this yet)
hw_mode=g
# Accept all MAC addresses
macaddr_acl=0
# Use WPA authentication
auth_algs=1
# Require clients to know the network name
ignore_broadcast_ssid=0
# Use WPA2
wpa=2
# Use a pre-shared key
wpa_key_mgmt=WPA-PSK
wpa_pairwise=TKIP
rsn_pairwise=CCMP
driver=nl80211
# I commented out the lines below in my implementation, but I kept them here for reference.
# Enable WMM
#wmm_enabled=1
# Enable 40MHz channels with 20ns guard interval
#ht_capab=[HT40][SHORT-GI-20][DSSS_CCK-40]

 출처: https://lb.raspberrypi.org/forums/viewtopic.php?t=211542#p1355569


hostapd 수정

sudo cp /etc/default/hostapd /etc/default/hostapd.org
sudo vim /etc/default/hostapd 

pi@raspberrypi:~ $ sudo cp /etc/default/hostapd /etc/default/hostapd.org
pi@raspberrypi:~ $ sudo vim /etc/default/hostapd


# Defaults for hostapd initscript
#
# WARNING: The DAEMON_CONF setting has been deprecated and will be removed
#          in future package releases.
#
# See /usr/share/doc/hostapd/README.Debian for information about alternative
# methods of managing hostapd.
#
# Uncomment and set DAEMON_CONF to the absolute path of a hostapd configuration
# file and hostapd will be started during system boot. An example configuration
# file can be found at /usr/share/doc/hostapd/examples/hostapd.conf.gz
#
#DAEMON_CONF=""
DAEMON_CONF="/etc/hostapd/hostapd.conf"


# Additional daemon options to be appended to hostapd command:-
#       -d   show more debug messages (-dd for even more)
#       -K   include key data in debug messages
#       -t   include timestamps in some debug messages
#
# Note that -B (daemon mode) and -P (pidfile) options are automatically
# configured by the init.d script and must not be added to DAEMON_OPTS.
#
                                                              14,38         Top

DAEMON_CONF 에 좀전에 만들어준 파일 경로를 넣어주면 끗
DAEMON_CONF="/etc/hostapd/hostapd.conf"


interfaces 수정

sudo cp /etc/network/interfaces /etc/network/interfaces.org
sudo vim /etc/network/interfaces

pi@raspberrypi:~ $ sudo cp /etc/network/interfaces /etc/network/interfaces.org
pi@raspberrypi:~ $ sudo vim /etc/network/interfaces


# Please note that this file is written to be used with dhcpcd
# For static IP, consult /etc/dhcpcd.conf and 'man dhcpcd.conf'


# Include files from /etc/network/interfaces.d:
source-directory /etc/network/interfaces.d


auto lo
auto eth0
auto ap0
auto wlan0


iface lo inet loopback


allow-hotplug eth0
iface eth0 inet dhcp


allow-hotplug ap0
iface ap0 inet static
    address 192.168.10.1
    netmask 255.255.255.0
    hostapd /etc/hostapd/hostapd.conf


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


-- INSERT --                                                  16,23         Bot

하단에 interface 설정 추가해줍니다

아직도 API1, AP2는 뭔지 모르겠네요
cat /run/network/ifstate 으로 보면 wlan0로 받긴하던데


wpa_supplicant.conf 수정

sudo vim /etc/wpa_supplicant/wpa_supplicant.conf

pi@raspberrypi:~ $ sudo vim /etc/wpa_supplicant/wpa_supplicant.conf


ctrl_interface=DIR=/var/run/wpa_supplicant GROUP=netdev
update_config=1
country=US


network={
        ssid="SSID1"
        psk="PASSWD1"
        key_mgmt=WPA-PSK
        id_str="AP1"
}


network={
        ssid="SSID2"
        psk="PASSWD2"
        key_mgmt=WPA-PSK
        id_str="AP2"
}


~                                                                               
~                                                                               
~                                                                               
~                                                                               
"/etc/wpa_supplicant/wpa_supplicant.conf" 19L, 242C           1,1           All

interface 에 넣어둔 AP1, AP2 를 id_str 을 추가해서 넣어줍니다

집/직장 별로 wifi 연결을 따로 그룹화 해주는 듯?


가상 interface 활성화

interface 재시작

sudo ifdown --force wlan0
sudo ifdown --force ap0
sudo ifup ap0
sudo ifup wlan0

근데 iw dev 해보면 ap0 보이질 않으니 그냥 재부팅을 시켜주는게...

ip 관련 명령과 dnsmasp 재시작

iptable 안써봐서 잘모르겠지만
NAT POSTROUTING 눈에 띈다

pi@raspberrypi:~ $ sudo sysctl -w net.ipv4.ip_forward=1
net.ipv4.ip_forward = 1
pi@raspberrypi:~ $ sudo iptables -t nat -A POSTROUTING -s 192.168.10.0/24 ! -d 192.168.10.0/24 -j MASQUERADE
pi@raspberrypi:~ $ sudo systemctl restart dnsmasq

이걸 파이가 켜질때 마다 해줘야 하는것 같은데

번거로우니 shell 부팅할때 마다 실행되도록 script 작성


start-ap-managed-wifi.sh 생성

부팅 시 사용할 shell, root 디렉토리에서 작업 했습니다
sudo mkdir /root/shell
sudo vim /root/shell/start-ap-managed-wifi.sh
sudo chmod 755 /root/shell/start-ap-managed-wifi.sh

pi@raspberrypi:~ $ pwd
/home/pi
pi@raspberrypi:~ $ sudo su - root
root@raspberrypi:~# mkdir shell
root@raspberrypi:~# sudo touch shell/start-ap-managed-wifi.sh
root@raspberrypi:~# sudo chmod 755 shell/start-ap-managed-wifi.sh
root@raspberrypi:~# sudo vim shell/start-ap-managed-wifi.sh


#!/bin/bash
sleep 30
sudo ifdown --force wlan0 && sudo ifdown --force ap0 && sudo ifup ap0 && sudo ifup wlan0
sudo sysctl -w net.ipv4.ip_forward=1
sudo iptables -t nat -A POSTROUTING -s 192.168.10.0/24 ! -d 192.168.10.0/24 -j MASQUERADE
sudo systemctl restart dnsmasq


                                                                               
-- INSERT --                                                  5,90          All

파일에 실행권한 까지 주면 된다

sleep 30을 줄이고 싶은데 아직 테스트를 안해봄

 

스케줄러 등록 (crontab)

sudo crontab -e

pi@raspberrypi:~ $ sudo crontab -e
no crontab for root - using an empty one


Select an editor.  To change later, run 'select-editor'.
  1. /bin/nano        <---- easiest
  2. /usr/bin/vim.basic
  3. /usr/bin/vim.tiny
  4. /bin/ed


Choose 1-4 [1]: 2


# Each task to run has to be defined through a single line
# indicating with different fields when the task will be run
# and what command to run for the task
# 
# To define the time you can provide concrete values for
# minute (m), hour (h), day of month (dom), month (mon),
# and day of week (dow) or use '*' in these fields (for 'any').
# 
# Notice that tasks will be started based on the cron's system
# daemon's notion of time and timezones.
# 
# Output of the crontab jobs (including errors) is sent through
# email to the user the crontab file belongs to (unless redirected).
# 
# For example, you can run a backup of all your user accounts
# at 5 a.m every week with:
# 0 5 * * 1 tar -zcf /var/backups/home.tgz /home/
# 
# For more information see the manual pages of crontab(5) and cron(8)
# 
# m h  dom mon dow   command


@reboot /root/shell/start-ap-managed-wifi.sh
-- INSERT --                                                  25,21         Bot

제일 하단에 스크립트 경로를 추가해줬습니다

crontab 수정에 사용할 에디터를 설정하는건 처음만, vim 이 편하니 vim으로

 

@reboot /root/shell/start-ap-managed-wifi.sh
부팅/재부팅 할때마다 실행되나 보다

 

053. Raspberry Pi 라즈베리 파이 - AP + WiFi Client on Raspberry pi 3 OR Raspberry pi zero w

 

재시작을 하면 ssid 접속가능한 wifi 리스트에 나온다

 

가급적 집에서 설정하고 나가서는

wpa_supplicant.conf에 wifi 접속정보만 추가하는걸 추천..

 

참고

https://lb.raspberrypi.org/forums/viewtopic.php?t=211542#p1355569
http://w1.fi/cgit/hostap/plain/hostapd/hostapd.conf
https://thepi.io/how-to-use-your-raspberry-pi-as-a-wireless-access-point/
https://www.raspberrypi.org/documentation/configuration/wireless/access-point.md
https://lb.raspberrypi.org/forums/viewtopic.php?f=36&t=191453#p1204633
https://blog.thewalr.us/2017/09/26/raspberry-pi-zero-w-simultaneous-ap-and-managed-mode-wifi/
https://gist.github.com/aceisace/b7ca22b50531f43d48c74d86eb62c89a

반응형

관련글 더보기

댓글 영역