Astuces réseau

Depuis sa mise à jour du 06/09/2022, Raspberry Pi OS offre la possibilité de gérer le réseau via le logiciel NetworkManager plutôt que via Dhcpcd (voir The latest update to Raspberry Pi OS link ou Mise à jour de Raspberry Pi OS link).

A l’écriture de ces lignes, Dhcpcd reste le gestionnaire de réseau par défaut au 1er démarrage de la Raspberry Pi.

Ceci peut être modifié à l’aide de l’utilitaire de configuration en ligne de commande (→) sudo raspi-config) via l’option NetworkManager du menu Advanced Options  Network Config.

NetworkManager est encore considéré comme une fonctionnalité beta mais il est amené à supplanter Dhcpcd car il offre plus de fonctionnalités et facilite la configuration (connexion à des réseaux WiFi avec SSID caché, connexion VPN, mise en place de point d’accès Wifi).

Attribuer une IP fixe

Via NetworkManager

  • Depuis le bureau :

    Aller dans Paramètres réseau(⇅)  Avanced options  Edit Connections…​

  • Depuis la ligne de commande :

    Lancer l’interface textuelle de configuration avec nmtui et sélectionner Edit a connection

Via Dhcpcd

Depuis la version Jessie de Raspberry Pi OS, il est préférable de modifier le fichier /etc/dhcpcd.conf que de passer par ifconfig ou la modification du fichier /etc/network/interfaces.

  1. Éditer en tant qu’utilisateur root le fichier /etc/dhcpcd.conf

  2. Décommenter et modifier la portion suivante du fichier pour s’adapter à la configuration désirée :

    # Example static IP configuration:
    #interface eth0
    #static ip_address=192.168.0.10/24
    #static ip6_address=fd51:42f8:caae:d92e::ff/64
    #static routers=192.168.0.1
    #static domain_name_servers=192.168.0.1 8.8.8.8 fd51:42f8:caae:d92e::1
    Exemple
    interface eth0
    static ip_address=192.168.1.1/24
    static routers=192.168.1.254
    static domain_name_servers=192.168.1.254 8.8.8.8
  3. Appliquer la nouvelle configuration en redémarrant la Raspberry Pi

    sudo reboot
  4. Vérifier que la configuration a été appliquée avec succès

    $ ip addr
    [...]
    2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP group default qlen 1000
        link/ether b8:27:eb:62:81:61 brd ff:ff:ff:ff:ff:ff
        inet 192.168.1.1/24 brd 192.168.1.255 scope global noprefixroute eth0
           valid_lft forever preferred_lft forever
        inet6 fe80::979a:e1c7:4160:2246/64 scope link
           valid_lft forever preferred_lft forever

Se connecter à Internet à travers un proxy

Some networks, such as workplaces or schools, often require you to connect to the Internet through a proxy server.

Getting ready

You will need the address of the proxy server you are trying to connect to, including the username and password if one is required.

You should confirm that the Raspberry Pi is already connected to the network and that you can access the proxy server.

Use the ping command to check this as follows:

ping proxy.address.com -c 4

If this fails (you get no responses), you will need to ensure your network settings are correct before continuing.

How to do it …​

Create a new file using nano as follows (if there is already some content in the file, you can add the code at the end):

sudo nano -c ~/.bash_profile

To allow basic web browsing through programs such as midori while using a proxy server, you can use the following script:

Script content
.bash_profile.sh
function proxyenable {
# Define proxy settings
PROXY_ADDR="proxy.address.com:port"
# Login name (leave blank if not required):
LOGIN_USER="login_name"
# Login Password (leave blank to prompt):
LOGIN_PWD=
#If login specified - check for password
if [[ -z $LOGIN_USER ]]; then
#No login for proxy
PROXY_FULL=$PROXY_ADDR
else
#Login needed for proxy Prompt for password -s option hides input
if [[ -z $LOGIN_PWD ]]; then
read -s -p "Provide proxy password (then Enter):" LOGIN_PWD
echo
fi
PROXY_FULL=$LOGIN_USER:$LOGIN_PWD@$PROXY_ADDR
fi
#Web Proxy Enable: http_proxy or HTTP_PROXY environment variables
export http_proxy="http://$PROXY_FULL/"
export HTTP_PROXY=$http_proxy
export https_proxy="https://$PROXY_FULL/"
export HTTPS_PROXY=$https_proxy
export ftp_proxy="ftp://$PROXY_FULL/"
export FTP_PROXY=$ftp_proxy
#Set proxy for apt-get
sudo cat <<EOF | sudo tee /etc/apt/apt.conf.d/80proxy > /dev/null
Acquire::http::proxy "http://$PROXY_FULL/";
Acquire::ftp::proxy "ftp://$PROXY_FULL/";
Acquire::https::proxy "https://$PROXY_FULL/";
EOF
#Remove info no longer needed from environment
unset LOGIN_USER LOGIN_PWD PROXY_ADDR PROXY_FULL
echo Proxy Enabled
}

function proxydisable {
#Disable proxy values, apt-get and git settings
unset http_proxy HTTP_PROXY https_proxy HTTPS_PROXY
unset ftp_proxy FTP_PROXY
sudo rm /etc/apt/apt.conf.d/80proxy
echo Proxy Disabled
}

Once done, save and exit by pressing Ctrl+X, Y, and Enter.

The script is added to the user’s own .bash_profile file, which is run when that particular user logs in. This will ensure that the proxy settings are kept separately for each user. If you want all users to use the same settings, you can add the code to /etc/rc.local instead (this file must have exit 0 at the end).

How it works …​

Many programs that make use of the Internet will check for the http_proxy or HTTP_PROXY environment variables before connecting. If they are present, they will use the proxy settings to connect through. Some programs may also use the HTTPS and FTP protocols, so we can set the proxy setting for them here too.

If a username is required for the proxy server, a password will be prompted for. It is generally not recommended to store your passwords inside scripts unless you are confident that no one else will have access to your device (either physically or through the Internet).

The last part allows any programs that execute using the sudo command to use the proxy environment variables while acting as the super user (most programs will try accessing the network using normal privileges first, even if running as a super user, so it isn’t always needed).

There’s more …​

We also need to allow the proxy settings to be used by some programs, which use super user permissions while accessing the network (this will depend on the program; most don’t need this). We need to add the commands into a file stored in /etc/sudoers.d/ by performing the following steps:

It is important to use visudo here, as it ensures the permissions of the file are created correctly for the sudoers directory (read only by the root user).

  1. Use the following command to open a new sudoer file:

    sudo visudo -f /etc/sudoers.d/proxy
  2. Enter the following text in the file (on a single line) :

    Defaults env_keep += "http_proxy HTTP_PROXY https_proxy HTTPS_PROXY ftp_proxy FTP_PROXY"
  3. Once done, save and exit by pressing Ctrl+X, Y, and kbd[Enter]; don’t change the proxy.tmp filename (this is normal for visudo; it will change it to proxy when finished).

  4. If prompted What now?, there is an error in the command. Press X to exit without saving and retype the command !

  5. After a reboot (using sudo reboot), you will be able to use the following commands to enable and disable the proxy respectively :

    proxyenable
    proxydisable

Mettre en place un partage de fichiers avec Samba

Ci-dessous les étapes pour mettre en place un partage Samba sur une Raspberry Pi qui sera accessible depuis l’explorateur Windows.

Procédure

  1. Installer les packages nécessaires

    sudo apt-get update
    sudo apt-get install samba samba-common-bin
  2. Ajouter les options suivantes dans la section [global] du fichier /etc/samba/smb.conf

    netbios name = ma-rpi (1)
    follow symlinks = yes
    wide links = yes
    unix extensions = no
    1 Nom sous lequel on veut que la Raspberry Pi soit vue par Windows (→ netbios name). Pour y accéder, on tapera le chemin UNC [1] suivant dans l’explorateur Windows : \\ma-rpi

    Le nom netbios ne doit pas excéder 16 caractères.

  3. Ajouter la section suivante en fin du fichier /etc/samba/smb.conf

    [Mon partage] (1)
    comment = Mon partage Samba sur Raspberry Pi
    path = /home/pi/mon-partage (2)
    writable = yes (3)
    create mode = 0777
    directory mode = 0777
    share modes = yes
    valid users = pi (4)
    1 Nom du partage tel qu’il apparaitra dans Windows. C’est une bonne idée de lui donner le nom du répertoire devant être partagé.
    2 Chemin du répertoire de la Raspberry Pi devant être partagé
    3 Option qui permet l’écriture dans le partage depuis Windows
    4 Option qui définit les utilisateurs autorisés à accéder au partage
  4. Créer un mot de passe conforme à ce qu’attend Samba pour l’utilisateur pi

    $ sudo smbpasswd -a pi
    New SMB password: ***** (1)
    Retype new SMB password: ***** (1)
    Added user pi.
    $
    1 Saisie (“masquée” par des ‘*’) du mot de passe souhaité

    Pour plus de cohérence, on peut fournir ici le même mot de passe que celui qui permet d’ouvrir une session sur la Raspberry Pi mais ce n’est pas une obligation (la seule obligation est que l’utilisateur fourni en paramètre sur la ligne de commande existe sur la Raspberry Pi)

  5. Relancer les services associés à Samba

    sudo systemctl restart smbd.service
    sudo systemctl restart nmbd.service

Illustration du résultat

samba share 01
samba share 02

On notera dans l’image ci-dessus que le nom d’hôte de la Raspberry Pi qui lui a été attribué lors de sa configuration et qui est affiché dans l’invite de commande (→ rpi-defrance) n’a rien à voir avec le nom netbios qui lui a été affecté dans le fichier /etc/samba/smb.conf.

Créer un point d’accès WiFi sur une Raspberry Pi

Via NetworkManager

  • Depuis le bureau :

    Aller dans Paramètres réseau(⇅)  Avanced options  Create Wi-Fi Hotspot et suivre l’assistant

  • Depuis la ligne de commande :

    Exécuter les commandes suivantes en remplaçant :

    • <nom-connexion-hotspot> par le nom que vous voulez donner à la connexion

    • <ssid-hotspot> par le nom par lequel vous voulez que le point d’accès apparaisse dans le voisinage réseau

    • <clé-wifi-psk> par le mot de passe que protègera l’accès

      nmcli con add type wifi ifname wlan0 con-name <nom-connexion-hotspot> autoconnect yes ssid <ssid-hotspot>
      nmcli con modify <nom-connexion-hotspot> 802-11-wireless.mode ap 802-11-wireless.band bg ipv4.method shared
      nmcli con modify <nom-connexion-hotspot> wifi-sec.key-mgmt wpa-psk
      nmcli con modify <nom-connexion-hotspot> wifi-sec.psk "<clé-wifi-psk>"
      nmcli con up <nom-connexion-hotspot>

Via dhcpcd/hostapd/dnsmasq

Cette recette a été testée sur une Raspberry Pi 3 modèle B v1.2 tournant sur Raspberry Pi OS Buster (version du 2021-12-02)

Dans la documentation officielle de Raspberry Pi OS, selon la configuration désirée (→ routeur ou pont) suivre les indications fournies dans les sections :

  • Setting up a Routed Wireless Access Point link (→ Pour créer un réseau WiFi “Invité”)

                                             +- RPi -------+
                                         +---+ 10.10.0.2   |          +- Laptop ----+
                                         |   |     WLAN AP +-)))  (((-+ WLAN Client |
                                         |   | 192.168.4.1 |          | 192.168.4.2 |
                                         |   +-------------+          +-------------+
                     +- Router ----+     |
                     | Firewall    |     |   +- PC#2 ------+
    (Internet)---WAN-+ DHCP server +-LAN-+---+ 10.10.0.3   |
                     |   10.10.0.1 |     |   +-------------+
                     +-------------+     |
                                         |   +- PC#1 ------+
                                         +---+ 10.10.0.4   |
                                             +-------------+

ou

  • Setting up a Bridged Wireless Access Point link (→ Pour étendre le réseau existant avec du WiFi)

                                             +- RPi -------+
                                         +---+ 10.10.0.2   |          +- Laptop ----+
                                         |   |     WLAN AP +-)))  (((-+ WLAN Client |
                                         |   |  Bridge     |          | 10.10.0.5   |
                                         |   +-------------+          +-------------+
                     +- Router ----+     |
                     | Firewall    |     |   +- PC#2 ------+
    (Internet)---WAN-+ DHCP server +-LAN-+---+ 10.10.0.3   |
                     |   10.10.0.1 |     |   +-------------+
                     +-------------+     |
                                         |   +- PC#1 ------+
                                         +---+ 10.10.0.4   |
                                             +-------------+
Autres ressources

1. Uniform Naming Convention : convention de chez Microsoft pour désigner une ressource réseau

🞄  🞄  🞄