Home IoT & Hardware Learning Raspberry Pi

Learning Raspberry Pi

By Samarth Shah , Serge Schneider
books-svg-icon Book
eBook $39.99 $27.98
Print $48.99
Subscription $15.99 $10 p/m for three months
$10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime!
What do you get with a Packt Subscription?
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
BUY NOW $10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime!
eBook $39.99 $27.98
Print $48.99
Subscription $15.99 $10 p/m for three months
What do you get with a Packt Subscription?
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
About this book
Publication date:
April 2015
Publisher
Packt
Pages
258
ISBN
9781783982820

 

Chapter 1. Getting Started with Raspberry Pi

As you know, Raspberry Pi is a credit card computer developed by Raspberry Pi Foundation in the UK with the intention of promoting the teaching of basic computer science in schools. However, today it is used widely in all areas, including in the process of making super computer and advanced robotics operations. In this chapter, you will be introduced to Raspberry Pi and its components. As Raspberry Pi is supported by a wide variety of operating systems, this chapter provides an overview of what is available and the different installation methods. Before setting up a web server, the security implications and remote access methods are covered. Once the web server is set up and manageable remotely, it is put to use by adding WordPress. We will cover the following sections in this chapter:

  • Getting to know your Raspberry Pi

  • Different types of operating systems

  • Installation methods

  • User management

  • Remotely accessing Raspberry Pi

  • Installing a web server with PHP support

 

Getting to know your Raspberry Pi


Before you start reading further, you should know what exactly Raspberry Pi is and how you can connect different peripherals such as a keyboard and mouse to Raspberry Pi. There are several models of Raspberry Pi. The following table shows an important comparison between all the Raspberry Pi boards released as of February, 2015:

 

Model A

Model A+

Model B

Model B+

Generation 2

Price

25 USD

20 USD

35 USD

35 USD

35 USD

System on Chip

Broadcom 2835

Broadcom 2835

Broadcom 2835

Broadcom 2835

Broadcom 2836

Memory

256 MB

256 MB

512 MB

512 MB

1 GB

USB 2.0 Ports

1

1

2

4

4

Onboard Network

None

None

10/100 Mbits/s Ethernet

10/100 Mbits/s Ethernet

10/100 Mbits/s Ethernet

Power Ratings

300 mA(1.5 W)

200 mA(1W)

700 mA(3.5 W)

600 mA(3.0 W)

900 mA(4.5 W)

Note

As mentioned in the preceding table, there are variants of the model that you choose. For example in this book, Model B is used. All the code that is developed is compatible with Model B+ and Generation 2 boards. So, you can buy any of the Model B , Model B+, or even generation 2 to get the best out of this book.

  1. The microUSB power port

  2. HDMI out

  3. The Ethernet port

  4. Dual USB 2.0 ports

  5. Audio out

  6. RCA video out

  7. The SD card slot (back side)

Raspberry Pi supports almost all keyboards and mice; however, you can check out verified peripherals by the Raspberry Pi community at http://elinux.org/RPi_VerifiedPeripherals.

You need to load the operating system to the SD card before you start your exploration of Raspberry Pi. The following two sections have useful information about different operating systems that are supported on Raspberry Pi and on how to install particular operating systems.

Different types of operating systems

On a personal note, if you would like to dive in as quickly as possible, I would recommend visiting the official quick start guide at http://www.raspberrypi.org/quick-start-guide in order to install Raspbian. Then, continue from the Remotely accessing Raspberry Pi section of this chapter. Although you will be using Raspbian throughout this book, it helps to know what else is available and how the various operating systems differ. I encourage you to try all of the available operating systems and find what suits your needs.

The Raspbian OS

Raspbian is a Linux distribution based on Debian, with all packages compiled specifically for the Raspberry Pi. Although it is a separate project, Raspberry Pi Foundation creates images of Raspbian and maintains a repository containing additional software. Because Raspbian should be familiar to Ubuntu and Linux Mint users, as it aims to be user friendly and has the largest user base; this is often the recommended distribution.

The Arch Linux ARM OS

The Arch Linux ARM OS, which is a port of Arch Linux, is also optimized for the Raspberry Pi. However, this has a different design philosophy to Raspbian. Rather than aiming to be user-friendly, Arch Linux ARM gives the user a complete control over the system. This means that instead of a distribution that just works, you have a starting point from which to build up the distribution tailored to your needs. While this may be intimidating to some newcomers, the ArchWiki (http://wiki.archlinux.org) contains perhaps the most comprehensive documentation of any distribution, making it easy to get started. The other major difference is that Arch uses the latest software. While stability may be a concern, the advantage of bleeding edge software is that you rarely have to compile from the source to get the latest features and bug fixes. Arch is the ideal distribution for users who know how they want their system to work, who are willing to spend some time getting things up and running and don't mind the occasional hiccup.

Pidora is the Raspberry Pi-optimized remix of Fedora. This is the first distribution created specifically for the Raspberry Pi and was the officially recommended distribution prior to Raspbian. Since this is an RPM-based distribution, it should be most familiar to OpenSUSE and CentOS users. Fedora attempts to avoid non-free software where possible, so things such as MP3 support and Oracle's Java are not included. Its target audience is computer literate tinkerers who are likely to contribute to the project. Although Fedora has a significant user base, Pidora itself is a minor distribution on the Raspberry Pi and is not as actively maintained as Raspbian or Arch. Therefore, getting support may be difficult in some cases.

The RISC OS

RISC OS is not related to Linux and does not share the Unix lineage. It dates back to 1987 and has not followed development in the same direction as modern operating systems. As a result, it takes a while to get used to this system, since the user interface is quite different from what most people are familiar with. It lacks the level of hardware support that Linux has, so USB devices such as Wi-Fi sticks are not supported. On the other hand, it is extremely fast and excellent for low-level programming. While Linux competes for resources with your applications, RISC OS can get out of your way and let your code have complete control over the hardware. This is a great advantage for time-sensitive tasks and applications where you want to be close to the hardware. The RISC OS website (which you can access at http://www.riscosopen.org) has the resources necessary to get started.

OpenELEC and Raspbmc

These two distributions are centered on XBMC, which is a media player that can turn your Raspberry Pi into a home theater PC (HTPC). The major difference between the two is that OpenELEC is built from scratch and is designed only to be a HTPC distribution. Raspbmc, on the other hand, is built from Raspbian and can also be used as a general purpose distribution. Each has its own advantages and disadvantages and the final choice between the two comes down to preference. If you plan to use Raspberry Pi for specific purpose (home theater), then choose OpenELEC over Raspbmc. However, if you plan to do some general purpose stuff as well, then choose Raspbmc.

Other operating systems

Apart from the operating systems covered previously, there are many more to explore (you can access them via http://elinux.org/RPi_Distributions). These include BSD, the customized versions of Raspbian, Slackware, Gentoo, DexOS, Plan 9, and many others.

Note

In the remaining chapters of this book, projects are developed using Raspbian OS distribution, which is officially recommended by the Raspberry Pi Foundation.

Command summary

Although Linux distributions are quite different in their design philosophies, they are quite similar once the difference between the Init and package management systems is grasped. The important differences are summarized in the following table:

 

Raspbian

Arch

Pidora

Search for software

apt-cache search <keyword>

pacman -Ss <keyword>

yum search <keyword>

Install software

apt-get install <package>

pacman -S <package>

yum install <package>

Update package index

apt-get update

pacman -Sy

yum check-update

Update packages

apt-get dist-upgrade

pacman -Syu

yum distro-sync

Remove software

apt-get remove <package>

pacman -Rc <package>

yum remove <package>

Start service

service <name> start

systemctl start <name>

systemctl start <name>

Enable service

update-rc.d <name> enable

systemctl enable <name>

systemctl enable <name>

Init system

SysVInit

systemd

systemd

Package management

APT

pacman

RPM

 

Installation methods


In this section, you will learn how to install an operating system to the Raspberry Pi. There are different ways using which you can install OS to Raspberry Pi. Raspberry Pi runs from the OS installed on the SD card.

Tip

Make sure you are using the Class-10 SD card as other Class-4 cards has lots of write failure. Using the Class-10 memory card, you will have a better reading and writing experience.

NOOBS and BerryBoot

New Out Of the Box Software (NOOBS) is the official installation method developed by the Raspberry Pi Foundation as an attempt to simplify the installation procedure for beginners and add support for multiple operating systems on the same card. BerryBoot predates NOOBS and it has the advantage that it supports more operating systems, is able to install them to a USB stick, and can back up, restore, and clone operating systems.

The steps to install BerryBoot and NOOBS are as follows:

  1. First, download BerryBoot at http://www.berryterminal.com/doku.php/berryboot or NOOBS from http://www.raspberrypi.org/downloads.

  2. Next, format the SD card as FAT32, depending on your OS system.

  3. Windows users are recommended to use SD Association's SD Formatter, which can be accessed at https://www.sdcard.org/downloads/formatter_4/.

  4. Linux users can use GParted.

  5. Then, extract the downloaded archive onto the SD card.

  6. After this, the card can be ejected and inserted into the Raspberry Pi.

  7. Finally, boot up the Raspberry Pi with the card inserted and follow the on-screen instructions.

Note

Common pitfalls include extracting into a subdirectory and incorrectly formatting the card by using a card that is too small. Although 4 GB is the recommended minimum, an installed NOOBS Raspbian requires a little more to function correctly.

Installing Raspbian using RAW images

Installing Raspbian using RAW images is the original method that was used to install an operating system onto the SD card. The RAW image contains the binary data directly as it will appear on the card. This includes the Master Boot Record (MBR) and all of the partitions. This method has clear advantages as it is supported by all the operating systems, and there is very little that can go wrong. This does not require the user to partition or format the card as everything is already contained in the image file.

There are also some disadvantages. Since the sizes of SD card vary and the image file contains a static partition table and filesystem, you will end up with unusable free space. The other problem is the lack of flexibility. The image files make it hard to boot multiple operating systems from the same card or have an operating system on the SD card.

Writing an image using Windows

  1. First, download Win32 Disk Imager from https://launchpad.net/win32-image-writer.

  2. Next, select the appropriate image file.

  3. Then, select the SD card from the drop-down menu.

  4. Finally, click Write and remove the card.

The annotations in the preceding screenshot of Win32 Disk Imager correspond to the previous step numbers

Writing an image using Linux

  1. First, ensure the card is not mounted.

  2. Then write to disk, replacing mmcblk0 with the appropriate device. You can do this by running the following command:

    # dd if=file.img of=/dev/mmcblk0 bs=4M
    

    Tip

    Make sure you are pointing to the correct partition. If you point to the main OS partition by mistake, it might corrupt your current OS.

  3. Before removing the card, it is important to flush the filesystem buffers by running the following command:

    # sync
    

    Note

    Some more common problems to look out for include removing the card before flushing the filesystem buffers, writing to a partition instead of the whole card or writing the zip file instead of the extracted image file, and so on.

Raspbian OS interface

Once you have installed the Raspbian OS to the SD card, insert the SD card into Raspberry Pi and connect the keyboard, mouse, and LCD screen using the HDMI port and power the Raspberry Pi. On the first run, it will ask for your username and to type pi and the password as raspberry when prompted. Now, type startx to load the familiar UI.

  1. The Start button

  2. Folders

  3. The Midori browser

  4. Terminal (command windows)

Now, connect the Ethernet cable to your Raspberry Pi.

Tip

Before you start reading further, I recommend you spend some time playing with the OS and trying some of the commands that you are familiar with, of the operating system (Windows, Linux, Mac) you are using right now. Some of the things you can try are:

  • Find out what all applications are already installed on your Raspberry Pi

  • Access your e-mail account using the Midori browser

  • Get yourself familiarized with the folder structure

Expanding the filesystem

If you are using Raspbian, this can be done by choosing the Expand Filesystem option within the raspi-config script, which executes on the first boot. However, you can also launch this script manually by running sudo raspi-config. If your distribution does not provide an automated way to expand the filesystem and you do not have GParted available on your PC, this can be done on the Raspberry Pi itself. For this example, a card containing the Arch Linux image is resized by following these steps:

  1. First, launch fdisk by typing the following command:

    # fdisk /dev/mmcblk0
    
  2. Then, press p, followed by Enter in order to display the current partition table, which should be displayed as follows:

    Command (m for help): p
    Disk /dev/mmcblk0: 29.7 GiB, 31918653440 bytes, 62341120 sectors
    Units: sectors of 1 * 512 = 512 bytes
    Sector size (logical/physical): 512 bytes / 512 bytes
    I/O size (minimum/optimal): 512 bytes / 512 bytes
    Disklabel type: dos
    Disk identifier: 0x417ee54b
    
    Device         Boot     Start       End  Blocks  Id System
    /dev/mmcblk0p1           2048    186367   92160   c W95 FAT32 (LBA)
    /dev/mmcblk0p2         186368   3667967 1740800   5 Extended
    /dev/mmcblk0p5         188416   3667967 1739776  83 Linux
    
  3. Since the card contains an extended partition (p2) with a logical partition side of it (p5), you can simply delete partition 2, so partition 5 will be removed automatically. This can be carried out as follows:

    Command (m for help): d
    Partition number (1,2,5, default 5): 2
    
    Partition 2 has been deleted.
    
  4. After this, create a new extended partition to replace the one that has been deleted. Ensure that the first sector of the new partition matches the one deleted. Then, accept the default last sector, as it will automatically use all of the free space:

    Command (m for help): n
    
    Partition type:
       p   primary (1 primary, 0 extended, 3 free)
       e   extended
    Select (default p): e
    Partition number (2-4, default 2):
    First sector (186368-62341119, default 186368):
    Last sector, +sectors or +size{K,M,G,T,P} (186368-62341119, default 62341119):
    
    Created a new partition 2 of type 'Extended' and of size 29.7 GiB.
    
  5. Then, create a new logical partition, again making sure the start sector matches the old start sector of partition 5 and accept the default last sector:

    Command (m for help): n
    
    Partition type:
       p   primary (1 primary, 1 extended, 2 free)
       l   logical (numbered from 5)
    Select (default p): l
    
    Adding logical partition 5
    First sector (188416-62341119, default 188416):
    Last sector, +sectors or +size{K,M,G,T,P} (188416-62341119, default 62341119):
    
    Created a new partition 5 of type 'Linux' and of size 29.7 GiB.
    
  6. Next, display the partition table again to make sure that only the end sectors are different from the original partition table:

    Command (m for help): p
    Disk /dev/mmcblk0: 29.7 GiB, 31918653440 bytes, 62341120 sectors
    Units: sectors of 1 * 512 = 512 bytes
    Sector size (logical/physical): 512 bytes / 512 bytes
    I/O size (minimum/optimal): 512 bytes / 512 bytes
    Disklabel type: dos
    Disk identifier: 0x417ee54b
    
    Device         Boot     Start       End   Blocks  Id System
    /dev/mmcblk0p1           2048    186367    92160   c W95 FAT32 (LBA)
    /dev/mmcblk0p2         186368  62341119 31077376   5 Extended
    /dev/mmcblk0p5         188416  62341119 31076352  83 Linux
    
  7. Once you are happy with the partition table, write it to disk and quit:

    Command (m for help): w
    

    The partition table has been altered.

  8. Next, restart the Raspberry Pi by running the following command:

    # reboot
    
  9. When the Raspberry Pi has booted up, log in and resize the filesystem:

    # resize2fs /dev/mmcblk0
    

Note

It is important to note that not all images have the same partition layout. You should adapt the preceding steps to suit your needs.

Installing Raspbian using raspbian-ua-netinst

Hifi's raspbian-ua-netinst is a small tool that gives you a minimal Raspbian installation, using the latest packages. This install differs greatly from the RAW image released by the Raspberry Pi Foundation and is therefore only recommended for power-users. The complete documentation can be found at http://github.com/hifi/raspbian-ua-netinst.

Preparing the NetInstall on Linux

The NetInstall has distributed an image, as it is simpler for Linux users. The following steps help in preparing the NetInstall on Linux:

  1. First, download the installer using the following command:

    # wget http://hifi.iki.fi/raspbian-ua-netinst/raspbian-ua- netinst-latest.img.xz
    
  2. Then, extract the image to the SD card by running this command:

    # xzcat /path/to/raspbian-ua-netinst-latest.img.xz > /dev/mmcblk0
    
  3. Next, flush the filesystem buffers using the sync command.

  4. Finally, remove the card, boot the Raspberry Pi, and let the installer finish.

Preparing the NetInstall on Windows

Download and extract http://hifi.iki.fi/raspbian-ua-netinst/raspbian-ua-netinst-latest.zip onto a FAT32 formatted SD card, as shown in the NOOBS install steps.

Post-install configuration for Raspbian distribution

The default install does not replace the kernel, customize the install to your locale, or install any of the Raspberry Pi headers and libraries. The following steps provide a more complete install:

  1. First, log in as root, with the password raspbian.

  2. Then, change the password using the passwd command.

  3. If necessary, configure your locale, keyboard layout, and time zone by running the following command:

    # dpkg-reconfigure locales keyboard-configuration tzdata
    
  4. Next, update the package index by typing this:

    # apt-get update
    
  5. Then, install the kernel, bootloader, optimized memory routines, the Raspberry Pi utilities, and a text editor by running the following command:

    # apt-get install linux-image-rpi-rpfv raspberrypi-bootloader- copies-and-fills libraspberrypi-bin nano
    

    Note

    The linux-image-rpi-rpfv package contains a kernel managed by the Raspbian project, while the raspberrypi-bootloader package contains a kernel provided by the Raspberry Pi Foundation. Although the Raspbian kernel is recommended, the Foundation kernel can be used instead by skipping the sixth and seventh steps.

  6. The Raspbian kernel can then be installed by copying it to the boot partition using the following command:

    # cp /vmlinuz /boot/raspbian-kernel.img
    
  7. In order to avoid conflicts with the Raspberry Pi Foundation's kernel, configure the Raspberry Pi to use the new kernel. This can be done by running the following command and inserting the line kernel raspbian-kernel.img:

    # nano /boot/config.txt
    
  8. Finally, modify the sources list to include the non-free and contrib packages, if necessary. This includes things such as WiFi firmware, which may be required for some people. The /etc/apt/sources.list file should look as follows:

    deb http://mirrordirector.raspbian.org/raspbian/ wheezy main contrib non-free rpi
    deb http://archive.raspberrypi.org/debian/ wheezy main
    
 

User management


Once you have Raspbian installed, it is advisable to set up a user account. The Raspberry Pi Foundation's version of Raspbian already has a user pi, with the password raspberry. A system running with the default password is not secure as the password is widely known. To avoid this problem, the password needs to be changed. The default install does not have a root password set and the user is expected to use sudo to run commands as root. As a result, many beginners never learn the difference between a root and a user account. This leads to misuse of sudo and other issues later on. A root password is set in order to allow administrative tasks to be carried out in a standard root shell and an extra user account is added to standardize the install using the following steps:

  1. First, log in as pi.

  2. Then, change the default user password by running the following command:

    # passwd
    
  3. Next, enter a root shell by typing this:

    # sudo -i
    
  4. Again, run passwd to change the password. As you are in a root shell, this will change the root password this time.

  5. Add a new user with a name of your choice by entering the following command:

    # adduser steve
    
  6. The user will not be able to carry out certain tasks without being a member of the relevant groups. The following command will add the user into the major groups:

    # usermod -a -G adm,dialout,cdrom,sudo,audio,video,plugdev,games,users,netdev, input,spi,gpio steve
    

Note

Please note that raspi-config is coded with the assumption that pi is the main user. As a result, some options (Enable Boot to Desktop/Scratch), will not work as expected.

If you would like to boot the desktop automatically as the new user, this can be easily accomplished without raspi-config:

  1. First, enable the LightDM service by running this:

    # update-rc.d lightdmd enable 2
    
  2. Set the autologin-user variable in /etc/lightdm/lightdm.conf as required. You should note that leaving it commented out with a # will present you with a login window every time you boot up, which is slightly more secure and is especially recommended if you have multiple users.

The reverse can be accomplished simply by disabling the LightDM service.

Once you installed the operating system, you can use the keyboard, mouse, and HDMI screen to get started with the development. However, many of you might not have a USB keyboard, USB mouse, and HDMI screen. In such cases, you need to access Raspberry Pi remotely.

 

Remotely accessing Raspberry Pi


Once the Raspberry Pi is up and running, it may be necessary to access it remotely, and there are several ways of going about it.

The SSH remote server

SSH can be used for the vast majority of remote administration tasks. It gives us full access to a remote terminal just like it is local. Because the Raspberry Pi makes a good headless server, SSH is installed and enabled by default in Raspbian. Within Linux, connecting to an SSH server is done with the ssh command:

ssh user@IP:port

Tip

If you don't know how to get the IP address of Raspberry Pi, refer to Chapter 7, Troubleshooting, Tips/Tricks, and Resources for Advanced Users, Tips and tricks section.

The user and port parameters are optional. The username defaults to the currently logged-in user and the default port is 22.

On Windows, an SSH connection can be established using PuTTY, which you can download from http://www.chiark.greenend.org.uk/~sgtatham/putty/.

Securing SSH

If you want to make the Raspberry Pi accessible from outside of the local network, extra precautions should be taken to protect it from bots and hackers. Most bots simply attempt to connect on port 22 as root and brute force the password. Assuming that the password is relatively secure, this isn't a big problem, but it will eventually start filling up the logs with failed login attempts.

Changing the port number and forbidding root login over SSH is the simplest way of stopping the vast majority of automated login attempts. This can be done by editing /etc/ssh/sshd_config and setting the following options:

Port 1286 #Any unused port number is fine
PermitRootLogin no

Note

To keep things simple for the rest of the instructions, please leave the port at the default 22 for now.

However, changing the port number is not always desirable and will not stop someone from scanning for open ports. Ideally, you would disable password logins altogether and use keys. This is how it works—you generate a private and public key. The public key can be sent to a remote server. The private key, as the name implies, is kept private and is used instead of the password.

Windows users can generate the keys using the PuTTYgen tool, which is available on the PuTTY website:

  1. Copy the public key to the ~/.ssh/authorized_keys file on the Raspberry Pi (you may have to create it) and save the private key onto your PC.

  2. After this, change the permissions of the authorized_keys file in order to protect it:

    # chmod 600 ~/.ssh/authorized_keys
    
  3. Once this is done, you can use Save private key in PuTTY.

  4. The following PuTTY Key Generator screenshot annotations show the public key to be copied and how to save the private key:

  5. The highlighted area of the preceding screenshot shows how the private key can be used within PuTTY.

  6. Within Linux, the keys can be generated as follows:

    # ssh-keygen -t rsa
    
  7. When prompted, accept the default save location and enter a passphrase. The content of id_rsa.pub should then be pasted into the ~/.ssh/authorized_keys file on the Raspberry Pi. This can be done with a single command:

    # ssh-copy-id user@IP –p PORTNUMBER
    

    You should now be able to connect to the Raspberry Pi by using our private key.

  8. Once you have confirmed that this works, come back to /etc/ssh/sshd_config and disable password logins:

    PasswordAuthentication no
    
  9. You can add as many public keys to the authorized_keys file as necessary. For example, you may wish to allow someone else to access your Raspberry Pi. To do this, you would ask for their public keys and add it to the authorized_keys file of the desired user account.

    Note

    In the case the private key is stolen, it cannot be used without the passphrase. If someone knows the passphrase, it is useless without the SSH key. The combination prevents brute force connection attempts and secures the key itself.

  10. The final thing to do is to install fail2ban. This program monitors connection attempts and bans malicious IPs. This is a very powerful tool that can be used to fight a variety of different attacks and SSH is supported by default. This can be installed by running the following command:

    # apt-get install fail2ban
    

Open the configuration file to edit with Sudo nano /etc/fail2ban/jail.local and paste the following content (assuming your private IP addresses are in the range 192.168.0.*):

# SSH
# 3 failed retry: Ban for 10 minutes
[ssh]
enabled = true
port = ssh
filter = sshd
action = iptables[name=SSH, port=ssh, protocol=tcp]
mail-whois-lines[name=%(__name__)s, dest=%(destemail)s, logpath=%(logpath)s]
logpath = /var/log/auth.log
maxretry = 3
bantime = 600
ignoreip = 192.168.0.0/10

[ssh-ddos]
enabled = true
port = ssh
filter = sshd-ddos
action = iptables[name=SSH, port=ssh, protocol=tcp]
logpath = /var/log/auth.log
maxretry = 10
ignoreip = 192.168.0.0/10

Restart the fail2ban service:

sudo /etc/init.d/fail2ban restart

Transferring files

Besides executing commands remotely, SSH also allows us to transfer files. The scp command is similar to cp, but can copy files to and from SSH servers with the following command:

$ scp /path/to/src user@IP:/path/to/dst

This works great for a simple file transfer, but there is a more powerful command, which is as follows:

$ rsync /path/to/src user@IP:/path/to/dst -av

Rsync will only copy files that differ. By default, it does this by checking the file size and timestamp of the file, but a -c option can also be passed to use a checksum. This is very useful when making backups or updating source code, for example. It can also be used with a local source and destination, making it a very useful tool to get familiar with.

Windows users can use WinSCP, which is available at http://winscp.net. It has an excellent GUI that can use PuTTY private keys, and offers a way to move files between your PC and Raspberry Pi.

X11 Forwarding

So, you can run commands and transfer files, but what about the GUI? The X Windowing System was designed with the ability to use a remote display in mind. SSH can be used to forward remote GUI programs to the local X server. For Linux users, it's only a matter of launching SSH as before, but with the addition of a -Y option. When you have a SSH session ready, try launching leafpad. It should show up on your display.

Windows users will require an X server running. Some options are listed here:

Maintaining remote session using screen

While screen is not related to SSH directly, it is an incredibly powerful combination. Under normal conditions, if our connection drops and the SSH session is lost, everything that was running inside of it is terminated. This may result in a lot of hard work being lost. The screen allows us to create a session, which you can detach and re-attach as required. While detached, everything will continue to run as normal. If the connection drops, you can simply re-attach to the screen session and continue where you left off. Unfortunately, Raspbian does not come with screen preinstalled, so run the following command to install it:

# apt-get install screen

Once installed, it can be launched by running the following command:

# screen

You will receive a welcome screen, which can be dismissed by pressing Enter or disabling it in ~/.screenrc.

First, you'll need to learn a few key bindings to get started with screen. The default key bindings are initiated by pressing Ctrl + a and are completed by another key. For example, the screen session can be detached by pressing Ctrl + a and then d. Once detached, you can return back to the screen session by running the following command:

# screen -x

What if you want to run multiple applications? On a local machine, you have multiple ttyS commands or you can open many terminals windows and tabs. Starting a new SSH session for every application would be a little inconvenient. Screen has us covered here as well. Ctrl + a+ c will create a new window. The first window (0) is now replaced by the new window (1). To return to the first windows, the Ctrl + a + 0 binding will work. You can have as many windows as needed and navigate them using the Ctrl + a + 0-9 keys. Alternatively, Ctrl + a will bring up a list of all windows and let us switch between them using the arrows and the Enter key.

This short introduction only scratches the surface of what is possible with screen. It can display multiple windows at once in a split view, allowing you to have a file browser, a media player, and a network monitor running and making them visible all at once within the screen session. Multiple users can connect to the same screen session, if remote assistance is required. Screen can be configured to display a status bar with all of the windows listed and a clock, for example. It also supports start-up scripts, which can be very useful for power users.

The reverse SSH

Your Raspberry Pi could be behind a firewall with no access to port forwarding. In such a case, you can't connect directly. However, if the computer you wish to connect from is not behind a firewall and also has an SSH server running, reverse SSH can be used. From the Raspberry Pi, start SSH with the following command:

$ ssh -N -R 2222:localhost:22 user@IP

In this case, the user and IP parameters are for the computer you wish to connect from. -N means that you do not wish to run any commands. -R 2222:localhost:22 means that port 22 on localhost is going to be tunneled to port 2222 on the remote computer.

Then, from the remote computer, you can connect to localhost on port 2222 and that will redirect to port 22 on the Raspberry Pi launching SSH as follows:

$ ssh user@localhost –p 2222

The disadvantage is that this needs to be prepared in advance and will only last as long as both computers are on. This can be circumvented by preparing a script that runs every 15 minutes and creates the tunnel if it's not already established.

The other problem is that one computer must not be behind a firewall. The solution is to use a middleman server, which the Raspberry Pi will establish a tunnel with. Then, you can connect to this server and be tunneled through to the Raspberry Pi. However, the fundamental problem still remains, as now you require yet another server that is not behind a firewall. If such a server is not available, a third-party solution such as Hamachi, may be an option.

Virtual display using VNC

VNC is quite different from the other options and comes in two flavors. The first allows for the display that is attached to the Raspberry Pi to be mirrored remotely and is called x11vnc. One example of where this is handy is remote assistance. The other option is a virtual display, which is not shown on the Raspberry Pi's monitor itself. The virtual display approach is useful when you would like to be able to launch multiple, independent VNC sessions. In order to connect to a VNC server, you will need a VNC client. There are clients and servers available for all major operating systems, from Windows to Android. TightVNC is one example. The installation package differs from other distributions, but once installed, it can be launched using VNC Viewer.

In order to use the real display, you need to install x11vnc on the Raspberry Pi by running this:

# apt-get install x11vnc

If the X server is running, x11vnc can be launched directly by running x11vnc. By default, x11vnc will exit once the client disconnects. This can be prevented by adding the -forever option.

In order to use a virtual display, install a TightVNC server on the Raspberry Pi by running the following command:

# apt-get install tightvncserver

When running vncserver for the first time, you will be taken through a quick set up procedure.

Pay attention to the output, as it will say which display the server is running on. When connecting, specify this display as the port number.

In order to stop a running virtual VNC display, the -kill option can be used. The following command will kill the VNC server using display :1:

$ vncserver -kill :1

Share the keyboard and mouse using Synergy

Synergy is used to share the keyboard and mouse across multiple systems. For example, you can have a display connected to the Raspberry Pi and control it from the keyboard and mouse on your PC. This will be useful if you would like to use the full desktop environment without VNC, but don't have a spare keyboard, or if you would like to have a dual-display setup with one of the displays dedicated to the Raspberry Pi.

  1. On the PC, download and install the synergy server, either from the official website (http://synergy-foss.org) or from your distribution's repository. Running it will guide you through a setup procedure, which will prepare it for use.

    Note

    The version of synergy in the Raspbian repository is not supported by newer servers. It is possible to download an older server (1.3.8) or compile the client for Raspbian, which will not be covered here.

  2. Install Synergy on the Raspberry Pi by running this:

    # apt-get install synergy
    
  3. Finally, from the Raspberry Pi's desktop, launch the Synergy client with the following command:

    # synergyc IP
    
 

Installing a web server


The first instinct may be to install Apache. However, nginx performs better on lower-end hardware. It should be noted that Apache can work just as well if the unnecessary plugins are removed and Apache is configured appropriately. For something that works fairly well out of the box, nginx is a great start.

  1. First, install nginx and php with an accelerator and a MySQL server with the following command:

    # apt-get install nginx php5-fpm php5-mysql php-apc mysql-server
    

    Note

    You will be prompted to set a password for MySQL; please make sure you remember it, as you will need it later.

  2. Then, start the nginx service:

    # service nginx start
    
  3. In order to ensure nginx is working, open up a browser and connect to the Raspberry Pi's IP. You should be greeted with a Welcome to nginx! message.

    Note

    The configuration file for nginx is located in /etc/nginx/nginx.conf. The file then imports additional configuration files from /etc/nginx/conf.d/*.conf and /etc/nginx/sites-enabled/*. The idea is that you store the configuration for the individual sites you want to run in the /etc/nginx/sites-available/ directory and then symlink the ones you wish to enable into the /etc/nginx/sites-enabled/ directory.

  4. Next, create a configuration for our site based on the default and then enable it by running the following commands:

    # cp /etc/nginx/sites-available/default /etc/nginx/sites- available/pisite
    # unlink /etc/nginx/sites-enabled/default
    # ln -s /etc/nginx/sites-available/pisite /etc/nginx/sites- enabled/default
    
  5. After this, change the content of /etc/nginx/sites-available/pisite as follows:

    server {
            root /srv/www;
            index index.html index.htm;
    }
    
  6. At this point, this is not a valid entry, as /srv/www does not exist. Create the directory and add a simple index.html by executing the following commands:

    # mkdir /srv/www
    # echo "Hello world" > /srv/www/index.html
    
  7. Finally, reload the nginx configuration so that our changes take effect by running this command:

    # service nginx reload
    

Refresh the web page to ensure the new site is properly configured.

Adding PHP support

Now that the web server is working, it is a good idea to configure it to use PHP, using the following steps:

  1. First, start the php5-fpm service, which nginx will communicate with to provide PHP support using FastCGI. This can be done by running the following command:

    # service php5-fpm start
    
  2. Then, modify the pisite configuration as follows:

    server {
            root /srv/www;
    index index.php index.html index.htm;
    
            location ~ \.php$ {
                    fastcgi_pass unix:/var/run/php5-fpm.sock;
                    fastcgi_index index.php;
    include fastcgi_params;
            }
    }
    
  3. Next, remove the old index file by running this command:

    # rm /srv/www/index.html
    
  4. Create /srv/www/index.php with the following content:

    <?php
            phpinfo();
    ?>
    

    The <?php … ?> tags indicate that the contents is to be interpreted as PHP. The phpinfo() function is used to return configuration information.

  5. Finally, reload the configuration:

    # service nginx reload
    

Refreshing the page should bring up information about your PHP configuration, indicating that PHP is working.

Now you have installed popular LAMP server on your Raspberry Pi. Web application development using the LAMP stack is the preferred option for developers to create a stable, reliable, and highly efficient application. Moreover, developing the application using LAMP stack and deploying code on LAMP stack is comparatively easy. Having installed all these stacks, you might want to host your own personal blog/website using Raspberry Pi powered by popular WordPress.

Installing WordPress

Once the server is installed, it can be used to host a personal website powered by WordPress:

  1. First, download and extract WordPress to the www directory by running the following commands:

    # wget http://wordpress.org/latest.zip
    # unzip latest.zip -d /srv/www/
    
  2. Then, launch the MySQL command-line tool. When prompted for a password, enter the password setup when installing MySQL:

    # mysql -u root -p
    
  3. Next, create a new database called piwordpress by entering the following command:

    > CREATE DATABASE piwordpress;
    
  4. After this, create a username wordpress with the password password and give the user all privileges to the piwordpress database by entering this command:

    > GRANT ALL PRIVILEGES ON piwordpress.* TO "wordpress"@"localhost" IDENTIFIED BY "password";
    
  5. Please replace password in the preceding code with something more secure. Then, reload the privileges and exit the MySQL shell with the following commands:

    > FLUSH PRIVILEGES;
    > EXIT
    
  6. Next, give full write access to the wordpress directory for the setup process by running the following command:

    # chmod a +w /srv/www/wordpress
    
  7. Open the IP of the Raspberry Pi in the browser followed by /wordpress/wp-admin/install.php.

  8. Go through the setup process using the parameters outlined in the fourth step. The tables prefix can be anything.

  9. Finally, adjust the ownership and permissions by running the following commands:

    # find /srv/www/wordpress -type d -exec chmod 755 {} \;
    # find /srv//www/wordpress -type f -exec chmod 644 {} \;
    # chown www-data:www-data /srv/www/wordpress/* -R
    # chmod 400 /srv/www/wordpress/wp-config.php
    

The WordPress installation can now be accessed through http://IP/wordpress in your browser.

Note

WordPress and PHP have historically many security holes, and simple mistakes by a plugin or theme coder can make your Raspberry Pi vulnerable to attack. Take extra care by not storing sensitive information on the Raspberry Pi, installing a security plugin, configuring fail2ban, and monitoring your logs. Always search for more ways to secure your server and data.

 

Summary


In this chapter, an overview of the different operating systems was covered along with common administrative tasks. A full-featured web server with a personal website platform was set up.

In the next chapter, a media player will be added to the web server, allowing you to listen to your music from anywhere.

About the Authors
  • Samarth Shah

    Samarth Shah is a software engineer by profession and maker by heart. He leads maker activities at Pune Makers and heads Infosys Robotics Club. He loves building creative/innovative prototypes using the latest hardware/sensors (Raspberry Pi, Arduino, Kinect, Leap Motion, and many more) and software. He has given talks at various national and international conferences. He has authored a book on Raspberry Pi entitled Learning Raspberry Pi, Packt Publishing. During the day, he works on various data visualization techniques and UI frameworks. At night, he does blogging, reading, writing, and many more things. You can read more about him at http://samarthshah.com.

    Browse publications by this author
  • Serge Schneider
Latest Reviews (3 reviews total)
As they say in the advert. It does what it says on the tin.
While you need to have some concept of the basic workings of electricity and some bas component concepts, this book really fills in the gaps.
The book explains the product in great detail
Learning Raspberry Pi
Unlock this book and the full library FREE for 7 days
Start now