Math is Hard: Orange you glad you’re not in fifth grade?

Here’s the answer to a problem that I admit that I cheated on. I got thrown by the idea that giving three oranges away means subtract – that’s where visualizing the transaction helps.

Problem
Shomika was helping her family pick oranges in their grove. She took some oranges home to share with her three friends. She gave 3 more than half to Jennifer. Angela got half of the remainder and 3 more. She gave Josie half of the remainder plus 3. When she got home, she only had 10 oranges left. How many did she have when she left the grove?

Solution
Start from the bottom and work your way up. For example, to be left with 10, she had to have had 26 when she met Josie, because she gave half away (26-13=13) then three more (13-3=10). And 26 is half of 58, etc. It’s the same problem with three iterations. So once you figure out the first problem – how many did she have before she met Josie – you apply the same logic to the rest.

The answer, if you don’t want to try it yourself:

In order for Shomika to be left with 10, she had to have had 26 when she met Josie, because she gave half of the 26 to Josie, which left 13, then she gave Josie 3 more, leaving her with 10.

26/2 - 3 =
  13 - 3 =
      10

In order for Shomika to be left with 26, she had to have had 58 when she met Angela, because she gave half of the 58 to Angela, which left 29, then she gave Angela 3 more, leaving her with 26.

58/2 - 3 =
  29 - 3 =
      26

In order for Shomika to be left with 58, she had to have had 122 when she met Angela, because she gave half of the 122 to Angela, which left 61, then she gave Angela 3 more, leaving her with 58.

122/2 - 3 =
   61 - 3 =
       58

Therefore, Shomika had 122 oranges when she left the grove. We can also infer that Jennifer is her BFF, and Shomika has strong arms. If an average orange weighs 6oz., then 122 oranges would weigh 45.75lbs (6 x 122)/16 = 45.75.

I started going down the algebraic route but stopped, because this was a question for a fifth-grader, who hadn’t had algebra yet. But this is the solution I would have gone for.

Another Way to Look At It

Since you’re going backwards, you just reverse the operations. Shomika had 10 after subtracting 3 and halving the prior amount. So to get to the prior amount, you add three then double that amount.

Or another way to look at it – what if Shomika wanted her oranges back? Her “friends” had posted a mean message on Facebook that she wasn’t supposed to see – but she did! Because Shomika is good friends with Tangiers, who is friends with Angela on Facebook, and he can see all her posts! And both Angela and Josie “liked” it!

So Shomika went to Josie’s house and took the extra 3 from her (now Shomika has 13), then doubled that amount, and now she has 26. Then she went to Angela and asked for the 3 back (now she has 29), then doubled that, and she has 58. Josie wasn’t home when Shomika got to her house, so she sneaked in to her kitchen through the back door (because she knows the back door is always open so the dog can go out and poop). She grabbed the flowery pink bag (that’s just like Josie!) of oranges next to the kitchen sink and ran. It was hard going, because she was already carrying around 22lbs of oranges in a paper bag. When she got home, she pulled three oranges out of the flowery bag (now she has 61), and counted double that to make sure she got all 122 oranges back. She didn’t though. Josie ate one. Josie is fat and picks her nose!

Or algebraically:

1/2x - 3 = 10
   x - 6 = 20
       x = 26

Then

1/2x - 3 = 26
   x - 6 = 52
       x = 58

And

1/2x - 3 =  58
   x - 6 = 116
       x = 122

A Simpler Version

The question is a lot simpler if you don’t include the plus-three. This much easier example will give you an idea for how to solve the problem:

Bellybop helped her family pick oranges in their grove, and afterwards, she took some oranges home to share with her friends. She gave half of the total oranges to Pollysnack. Silipsity got half of what was left of that. And she gave Hesponda half of what was left after that. When she got home, she only had 10 oranges left. How many did she have when she left the grove?

Working backwards from 10:

She had 20 when she met with Hesponda, who took 10.    (20 – 10 leaves 10).
She had 40 when she met with Silipsity, who took 20.       (40 – 20 leaves 20.
She had 80 when she met with Pollysnack, who took 40.  (80 – 40 leaves 40).

It’s a bit harder when you add the plus-three variant.

A Funner Version

Annabelle works for Apple Computer, and she was blackmailed into stealing iPads from the warehouse by three mafioso. The first guy, Guy (pronounced “Gee”), got half of the loot, plus seven extra to sell on eBay under the handle: “FlyGuy”. The next fella, Rosie, got half of what was left, plus 1. He wanted to post on Youtube a video of someone diving into a pool with a brand new iPad with the extra one (yeah, that was him!). Donny, the last guy, got half of the remainder, plus an extra 2 for his kids. Annabelle was left with 1, so if they got busted, she’d be holding the hot merch, too. How many iPads were stolen?

Work it backwards. The first calculation is for Donny:

1/2x - 2 = 1
   x - 4 = 2
       x = 6

Then Rosie:

1/2x - 1 = 6
   x - 2 = 12
       x = 14

And finally, Guy:

1/2x - 7 = 14
  x - 14 = 28
       x = 42

Next: English lesson on “had to have had”. Shomika had to have had had a lot of oranges. Also, why is it “backwards” as an adverb and “backward” as an adjective?

RealVNC Small Resolution Problem on Raspberry Pi

Because nothing is easy on Linux. If it were not for the staggering amount of user supplied support, wrestling with Linux would be as frustrating as ever. Fortunately, the answers are out there, due to the common denominator of the Raspberry Pi.

I set up VNC Server (RealVNC) on the Pi while it was connected to my HDMI monitor, whose resolution is set to 1080p (aka 1920 x 1080). When I logged in with the VNC Client from Windows, it gave me full resolution. Later, when I had shut down and restarted without the monitor attached (running headless), the Windows client gave me some horrid size like 480 x 320 – something minuscule.

Apparently, when you run headless, it defaults to the lowest possible resolution. To fix this:

$ sudo cp /boot/config.txt /boot/config.backup
$ sudo nano /boot/config.txt

and uncomment/edit:

hdmi_force_hotplug=1
hdmi_group=2
hdmi_mode=82

Now reboot:

$ sudo shutdown -r

Had it not been for stackexchange and the raspi forum, I would have been lost. Instead, I got the glorious 1080p as I had expected. Actually, I had expected the client to allow me to set this value, but I suppose it makes sense that it has to be configured at the server.

Remember to revert to the backup config.txt file if you want to connect with some other monitor.

You can also set it to a lower resolution of 1024×768 at 60Hz by:

$ sudo cp /boot/config.txt /boot/config.backup
$ sudo nano /boot/config.txt

and uncomment/edit:

hdmi_force_hotplug=1
hdmi_group=2
hdmi_mode=16

You can view more screen resolutions at http://elinux.org/RPiconfig

SD Disk Space on Raspbian Jessie

The older Raspbian distributions required that you expand the root file system to the maximum on the SD card.

That looks like it’s taken care of automatically with Jessie. If I run:

$ df -k
Filesystem      1K-blocks    Used Available Use% Mounted on
/dev/root        15119432 3969928  10475472  28% /
devtmpfs           437052       0    437052   0% /dev
tmpfs              441384   32344    409040   8% /dev/shm
tmpfs              441384    6064    435320   2% /run
tmpfs                5120       4      5116   1% /run/lock
tmpfs              441384       0    441384   0% /sys/fs/cgroup
/dev/mmcblk0p1      63503   20756     42747  33% /boot
tmpfs               88280       0     88280   0% /run/user/1000

It shows that /dev/root has all the 16GB SD allocated to it.

I ran

$ sudo raspi-config

And selected Advanced Options > Expand Root Filesystem, then rebooted. Then I ran again df -k, and the result was about the same.

 

From Zero to Pi in 5 Hours

I bought a Raspberry Pi 3 B and a Pi Camera (v2.1) from Fry’s and spent some hours configuring it. Even though it’s considered a kid’s learning computer, I don’t think it suits your average kid.

A few days prior, I bought a Sandisk 16GB micro SD card from Amazon , and used Win32 Disk Imager to flash the disk image Raspbian Jessie with Pixel . That all went fine.

I installed the SD card, plugged in a wired keyboard and mouse, and connected the Pi to an HDMI enabled monitor. I had to look up how to install the camera, because the included instructions were in 2pt font with no diagrams – it’s the socket next to the headphone jack; you have to pull up on the black tabs to open the socket, the blue side faces the headphone jack. I was ready for power up.

My first issue was powering up the Pi – of course it was. Even though I had picked a 2 Amp power supply (according to the label), the Pi didn’t light up. My second power supply worked. (Later, I tried the same power supply with a different USB cable, and it worked. USB cables – who would have thought?)

The Pi booted straight into XWindows (aka Pixel), really fast – compared to my old 2012 v1 B Pi. This was my first experience with a wireless Pi 3 – and my next problem took me an hour to figure out.

But first, I changed my Pi password, because everyone should. Then I configured my location. When you configure your location, the Pi updates your /etc/wpa_supplicant/wpa_supplicant.conf file with your info. Knowing this comes in handy later.

I don’t broadcast my wireless SSID. I know this probably causes more trouble for me than anyone who might want to hijack my wireless connection, but that’s what I’ve done. So even though the Pi could see a [blank] wireless broadcast, I couldn’t connect. I tried entering my wireless password for the [blank] connection, but that didn’t work (and actually added an entry for [blank] in the wpa_supplicant.conf file). So, to the Internet!

What I discovered was that I would have to modify a CONF file to get it to work. I really expected the GUI to have a “Manually Configure Network” option, but alas it was not so. After sifting through lots of text on how to do it, I gave it a shot. There were several different takes on what to add to

/etc/wpa_supplicant/wpa_supplicant.conf

to make it work. The one I chose worked at first, then caused even more trouble. What I tried at first was something like:

network={
 ssid="name of your network"
 psk="password key"
 key_mgmt=WPA-PSK
 scan_ssid=1
}

And it worked! So I went on my merry way. And the first thing I wanted to do was update/upgrade:

$ sudo apt-get upated
$ sudo apt-get upgrade

These seemed to go well. I was following the “official” instructions for setting up the camera. The “official” documentation says:

“Now you need to enable camera support using the raspi-config program you will have used when you first set up your Raspberry Pi.”

Sounds easy enough. What I expected was that now I should see the Camera option when I:

$ sudo raspi-config

Alas, NO CAMERA OPTION! Where is my camera? Why isn’t it there? I tried a reboot, but still no camera option in raspi-config. So just to be safe, I did another:

$ sudo apt-get upated
$ sudo apt-get upgrade

And this time, I got error, errror, error. Because, as I discovered, I was no longer connected to the Internet. Not only that, I wasn’t connected to my wireless network. And now the Pi GUI said: “No wireless interfaces found”.

I plugged it in to a wired ethernet and update/upgraded but still no fix for the wireless.

Apparently, the “No wireless interfaces found” message is very common – so common that smartasses at the Beginners forum tell people to stop asking about it. What I read was that it could be either:

  • A defective Pi WiFi.
  • A bad power source.
  • You need to run dist-upgrade.
  • Use NOOBS.
  • Install firmware.
  • Edit /boot/config.txt
  • Edit /etc/dhcpcd.conf with static IP
  • Stop asking and look up “2 ip addresses”

Whelp, none of these was my problem. I re-flashed my SD and started over, taking everything slow. When it came to editing /etc/wpa_supplicant/wpa_supplicant.conf, I discovered that it was causing the GUI to display the “No wireless interfaces found” message. The answer was to add just the SSID and password, so the wpa_supplicant.conf file that ended up working looked like this:

$ sudo nano /etc/wpa_supplicant/wpa_supplicant.conf
country=US
ctrl_interface=DIR=/var/run/wpa_supplicant GROUP=netdev
update_config=1

network={
ssid="myssid"
psk="mypassword"
}

It worked! A mere hour+ of trial and error, and I was on to greater things. Note the country, ctrl_interface, update lines were all added via the GUI. I did another:

$ sudo apt-get upated
$ sudo apt-get upgrade

Just to be safe. Still, there was no Camera option in raspi-config. It was, however, in the GUI under Preferences > Pi Configuration. After enabling it there, I tried:

$ raspistill -o myimage.jpg

And it worked! Everything that works right off seems like a freeking miracle. So I’m not sure why the official documentation is incorrect.

Update here: I found out that the camera is now in raspi-config, under 5. Interfacing Options. 

And since Jessie comes with VNC installed, I also enabled that and SSH so I could manage it from my Windows PC. I installed the Windows VNC Viewer from RealVNC, and it worked flawlessly.

So from purchase time of 10:30am to up and running at 3:30pm, it took 5 hours of fiddling. But now I have all this experience (that I’ll probably never need to use again)!

Don’t forget to change your root password:

$ sudo passwd root

Because if you don’t, you can’t log in as root. Also, anyone can get root access!

Using rsync for Backup on Raspberry Pi

A good discussion of rsync and how to use it can be found here. I will try to explain why I back up the way I do.

Using rsync seems to be fairly straightforward. At first, I considered not using rsync, because it deletes from the destination what has been deleted from the source. What I thought I wanted was a way to archive those deleted files. But then I thought about the frequency of the backup – if I back up once per day at 3am, for example, and I mistakenly delete a file, the file is recoverable until 3am. I can’t think of a time where I deleted a file that I wanted to keep but didn’t realize it until the next day. Usually (always) I realize my error immediately.

Also, I have been running an application for the past few years that does archive deleted files to an “Archive” folder on the destination drive, and I have yet to ever restore anything from the Archive and find that having to delete those files is a chore.

This will be the daily backup, and I will continue to back up weekly or monthly on a third drive for off-site redundancy. The third drive will contain any legacy files that I might need – I might even keep the Archive folder on that drive. I haven’t decided. I guess it depends on how much storage I have/need.

The current setup is a Pi + Samba with a single USB drive as the NAS for my Windows network. What I need is to connect another backup drive to the Pi, either over the network or directly to the Pi’s USB.

Here’s the idea. I have several PCs where I do work. When I’m done with my projects, I save them to the Pi NAS, where they’re backed up daily.

Backups

The only one that’s a problem is the Off-Site, because it’s a manual backup, and I procrastinate.

Use Dry Run

rsync --dry-run --delete -avhz /home/myfiles/* /mybackup/somewhere/

Options:

-a        preserves everything about the file
-v        verbose
-h        human readable
-z        compresses data file during transfer
--delete  deletes from destination if not found on source
-n        dry run

 

Note: Follow up with fail2ban.

1) dont allow ssh conenctions though your router tro the rpi
2) change the default password for user pi to something else actually
2a) create a new user
2b) give that user sudo access
2c) give that user the same group access as user pi
2d) disable and remove user pi
2e) only allow the new user to be access by ssh keys
3) sudo apt-get update && sudo apt-get dist-upgrade #regularly

Change Default Shell to Bash

Log in as target user, then:

$ chsh -s /bin/bash

Change SSH Port

Install and Configure Fail2Ban

ddd

Send Email from Raspberry Pi Command Line and/or Python Script

Send Mail from Raspberry Pi Using SSMTP

Raspberry Pi B: Wheezy.

First, you need a Gmail account to use as the actual mail client. You will forward the email from the Pi to Gmail.

Set Up Gmail

Log in to Gmail, and then click here:

https://www.google.com/settings/security/lesssecureapps

or

myaccount.google.com -> "Sign-in & security" -> "Allow less secure apps: ON"

This is the location where you change your security settings. You need to set “Allow less secure apps” to ON.

Install SSMTP on Pi

$ sudo apt-get install ssmtp

Now edit the configuration file.

$ sudo nano /etc/ssmtp/ssmtp.conf

Make the following changes:

# Config file for sSMTP sendmail
#
# The person who gets all mail for userids < 1000
# Make this empty to disable rewriting.
root=postmaster

# The place where the mail goes. The actual machine name is required no
# MX records are consulted. Commonly mailhosts are named mail.domain.com
mailhub=smtp.gmail.com:465

# Where will the mail seem to come from?
#rewriteDomain=

# The full hostname
hostname=MyRaspbi

AuthUser=myEmailAddress@gmail.com
AuthPass=superSecretPassword
UsSTARTTLS=YES
UseTLS=YES

# Are users allowed to set their own From: address?
# YES - Allow the user to specify their own From: address
# NO - Use the system generated From: address
#FromLineOverride=YES

Note that the port for the conf file is 465 – I attempted to use 587, but it failed. The odd thing is that when I use a Python script to do the same thing, I have to use port 465. [scratches head]

When I ran it with 587:

$ echo "Hello inbox" | mail -s "Test" theToEmailAddress@hotmail.com

I got:

$ send-mail: Cannot open smtp.gmail.com:587

But changing the port to 465 made it happy. Also note that it fails if you add an exclamation point to the subject:

$ echo "Hello inbox!" | mail -s "Test" theToEmailAddress@hotmail.com

Will fail.

Note: I installed this the same way on Debian Jessie, and it did not have Mail installed. Instead, I tested it by entering the following, on each line, then after the last line, pressed Ctrl+D.

$ ssmtp theToEmailAddress@hotmail.com
subject: Test
Hello
$

CTRL+D.

Also, I discovered that Mpack (module that allows email attachments) was already installed.

Create Python Script

Create your python script to send the mail:

$ sudo nano sendMail.py

Enter the following (be careful to use single quotes where applicable):

import smtplib
smtpUser = 'myEmailAddress@gmail.com'
smtpPass = 'superSecretPassword'
toAdd = 'theToEmailAddress@hotmail.com'
fromAdd = smtpUser
subject = 'Python Test'
header = 'To: ' + toAdd + '\n' + 'From: ' + fromAdd + '\n' + 'Subject: ' + subject
body = 'From within a Python script'
s = smtplib.SMTP('smtp.gmail.com',587)
s.ehlo()
s.starttls()
s.ehlo()
s.login(smtpUser, smtpPass)
s.sendmail(fromAdd, toAdd, header + '\n\n' + body)
s.quit()

Save it, then run it:

$ python sendMail.py

Tada!

Install Logitech Media Server (LMS) on Raspberry Pi

Raspberry Pi B: Wheezy.

Before installing it, I did a lot of reading about how hard it is to install. Several different sites suggested a long and difficult installation process. For me, it was not hard AT ALL.

I installed it on a Raspberry Pi B (the original) running Debian Wheezy.

$ cat /etc/os-release
PRETTY_NAME="Raspbian GNU/Linux 7 (wheezy)"
NAME="Raspbian GNU/Linux"
VERSION_ID="7"
VERSION="7 (wheezy)"
ID=raspbian
ID_LIKE=debian
ANSI_COLOR="1;31"
HOME_URL="http://www.raspbian.org/"
SUPPORT_URL="http://www.raspbian.org/RaspbianForums"
BUG_REPORT_URL="http://www.raspbian.org/RaspbianBugs"

And specifically:

$ uname -a

Linux myservername 4.1.19+ #858 Tue Mar 15 15:52:03 GMT 2016 armv6l GNU/Linux

How to Install

Update first:

$ sudo apt-get update && sudo apt-get dist-upgrade

I followed the install directions, sort of, from AllThingsPi. The following installs SOX libraries, and what looks like FLAC support – which I’ll need:

# install some libs
$ sudo apt-get install -y libsox-fmt-all libflac-dev libfaad2 libmad0

Then download from Logitech:

# get the latest nightly build (from downloads.slimdevices.com):
$ wget -O logitechmediaserver_all.deb $(wget -q -O - "http://www.mysqueezebox.com/update/?version=7.9.0&revision=1&geturl=1&os=deb")

And install:

$ sudo dpkg -i logitechmediaserver_all.deb

It started automatically, so I went to http://myserverorIPaddress:9000 and there it was, running fine.

So far, my Pi is a NAS, a backup server, web server, and music server.

And AllThingsPi said that he also installed SqueezeLite on the same Pi so that it was serving the client installed on the same Pi. Pretty spiffy. I won’t be doing that. My goal is to run multiple Pis as Squeezeboxes, synchronized throughout my castle.

Raspberry Pi (Model B) NAS and Backup

Raspberry Pi B: Wheezy.

It seems that there is no one place to do all of the things you need to do to make this happen. So here are my detailed notes for the next time I have to set up a Linux based NAS.

Below is a photo of 1) not a model B, and 2) not my Pi.

raspberry-pi-nas-openmediavault

I actually couldn’t get a non-self powered hard drive to work with my Pi. I think they made the later versions easier to hook up.

I bought a Raspberry Pi Model B on the first day they were for sale (February 29, 2012) and spent the following weekend finding a power cable and SD card that would work with it.

I installed the Raspbian image following the directions on the web site.
[need to find those notes – I know I have them]

And not being too Linux savvy, I immediately started Windows X and was disappointed in the performance. Dang it’s slow. Even a 10yr old closet PC was faster. So I gave up on it and let it ferment in a drawer for a few years.

Recently, I decided to get serious about my backup strategy. I had been backing up inconsistently – sometimes going for 6mos without a backup – so my thoughts returned to the RasPi. I could set up a NAS and a backup with it.

Initially, I considered two external drives connected via the two USB ports. I began by connecting an external 500GB external 3.5 HD to the USB, but the Pi didn’t recognize it. As I discovered, there wasn’t enough power to run it from the Pi. I tried a 1.5GB external 5.25HD that had its own power source, and it was recognized. In fact, I discovered that if I unplugged the Pi from its own power source, that the USB drive would “backpower” the Pi via the standard USB port. But I also discovered that it was enough power to light up the lights, but it didn’t run the Pi, so I plugged the Pi back in to its own power source.

One of the benefits of running a Pi NAS is that you can use NTFS (MS Windows) formatted disks and not Linux. So if I needed to, I could unplug it from the Pi and plug it directly into a Windows PC.

I still haven’t changed the password for the user “pi”. I did change root password. The Pi is internal only and isn’t serving port 80 externally. To find the version of Linux:

$ cat /etc/*release
 PRETTY_NAME="Raspbian GNU/Linux 7 (wheezy)"
 NAME="Raspbian GNU/Linux"
 VERSION_ID="7"
 VERSION="7 (wheezy)"
 ID=raspbian
 ID_LIKE=debian
 ANSI_COLOR="1;31"
 HOME_URL="http://www.raspbian.org/"
 SUPPORT_URL="http://www.raspbian.org/RaspbianForums"
 BUG_REPORT_URL="http://www.raspbian.org/RaspbianBugs"

My Pi is headless – that is, it doesn’t have a keyboard, mouse, or monitor. To manage a headless Pi, install Putty. The original server name is raspberrypi, so to connect via Putty, connect to RASPBERRYPI on port 21.

To make life easier, in the Putty sesison, enter:

$ bash

That allows you to use up/down arrows to recall commands.

Also, set your preferences in Putty so that right mouse click copies but doesn’t immediately paste – honestly I don’t know why anyone would ever want to do that – and it’s the default setting in Putty.

  • The brief overview of the steps:
  • Set up your Pi.
  • Connect your NTFS drive.
  • Mount the drive.
  • Create a Linux user.
  • Install Samba.
  • Create a Samba user.
  • Configure Samba.
  • Set up crontab event.

First off, you need to mount the drive. Make sure your drive is recognized. List the drives:

$ sudo fdisk -l
NAME        MAJ:MIN RM   SIZE RO TYPE MOUNTPOINT
mmcblk0     179:0 0 7.5G 0    disk
+-mmcblk0p1 179:1 0 56M  0    part     /boot
+-mmcblk0p2 179:2 0 7.5G 0    part     /
sda           8:0 0 1.4T 0    disk
+-sda1        8:1 0 1.4T 0    part

In the above output, mmcblk0 is the SD card, and the mmcblk01 and mmcblk02 are the partitions. The sda is the external drive, and sda1 is the partition. The first external drive will be sda, and if you have a second, it will be sdb, etc. According to the above, the sda1 partition is NOT mounted.

Side Note: I did all this as root, since I did not and still don’t have a handle on the ownership/permissions. I do understand that after I create a user such as backupUser and create the same user in Samba that I had to mount the drive as backupUser for Samba to work correctly.

My Pi recognized that drive on bootup and created a mount point for it automatically. Go to the drive mounts and see if your drive is already set up. Note that the default drive name can be changed by plugging it in to a Windows PC and renaming it there.

Go see what mount locations are already set up:

$ cd /media
$ ls -l

Displays mount locations for the user you are currently logged in as.

Let’s mount that sda1 partition to /media/1_5TBExt:

$ sudo mount -t auto /dev/sda1 /media/1_5TBExt

Side Note: mount the drive as your backupUser and not root. If you mount it as root, then the permissions will be incorrect. I can’t stress this enough.

Make sure you can view files there:

$ cd /media/1_5TBExt
$ ls -l

And if you list your disks, you should see that the sda1 partition is now mounted:

$ lsblk
NAME        MAJ:MIN  RM SIZE RO TYPE MOUNTPOINT
sda         8:0 0    1.4T    0 disk
+-sda1      8:1 0    1.4T    0 part  /media/1_5TBExt
mmcblk0     179:0    0 7.5G  0 disk
+-mmcblk0p1 179:1    0 56M   0 part  /boot
+-mmcblk0p2 179:2    0 7.5G  0 part  /

Now we need to create a Linux user for the backup. You don’t want to be root or pi, since those are potential targets, although I suppose you could if you wanted to. To avoid a lot of frustration, just use root for everything – and light all the Linux experts’ hair on fire. Normally, you want to create a user for a particular reason and use it rather than using root, since root provides god-like power to your Pi and potentially your network.

Note that you need to use a Linux user AND a Samba user – BOTH. For Linux to share files with a Windows PC, you need to install and run Samba. Samba lets you use Windows connect to your Linux box and view mounted drives. Samba contains the SMB protocol, support for the Windows naming service (WINS), and support for joining Windows workgroups.

Create a new Unix user and password:

$ sudo useradd backupUser -m -G users
$ sudo passwd backupUser

Side Note: you will need to create a Samba user with this SAME username, as I mentioned before.

Install NTFS Driver

$ sudo apt-get install ntfs-3g

Install Samba

Now that you have a drive mounted and you can see it and navigate to it on your Pi, you can move on to installing Samba. Each of these steps has its own frustrations. So if you have gotten to this point, congratulations. The entire process took me about 8 hours.

Before we install Samba, update your app list and upgrade your Linux so that you know that you have all the latest patches.

apt-get update updates the list of available packages and their versions, but it does not install or upgrade any packages.

apt-get upgrade actually installs newer versions of the packages you have. After updating the lists, the package manager knows about available updates for the software you have installed. This is why you first want to update.

Update your Linux applications:

$ sudo apt-get update

Upgrade Linux:

$ sudo apt-get upgrade

It’s common practice to update/upgrade before installing any new applications.

Now let’s install Samba:

$ sudo apt-get install samba samba-common-bin

Once installed, you will modify the Samba config file, /etc/samba/smb.conf. But first, back up the config file in case you need to restore it:

$ sudo cp /etc/samba/smb.conf /etc/samba/smb.conf.old

Side Note: I did actually restore smb.conf at one point, because I spent so much time trying to figure out why my Windows PC couldn’t see the drive – and I kept fiddling with the smb.conf, based on what various Internet people said to do. I can tell you that you need only do the minimum, described below.

BTW, to restore, you copy the old file to the original name:

$ cd /etc/samba/
$ cp smb.conf.old smb.conf

Now edit the config file with nano:

$ sudo nano /etc/samba/smb.conf

You need to change the workgroup = WORKGROUP line to your actual workgroup name. If you don’t know anything about workgroups, then your workgroup is probably WORKGROUP.

Find #security = user line and remove the comment tag: #. This enforces security, which Windows will want you to do. You can look up how to set this up without security – it’s not recommended, since it’s a security risk.

Add this to the end of the file:

[Backup]
comment = Backup Folder
path = /media/1_5TBExt
valid users = @users
force group = users
create mask = 0660
directory mask = 0771
read only = no

The bracketed name [Backup] could be anything – this is the name of your shared drive when you navigate to it in Windows. Save by Ctr+X. Press Y, then Enter to save the file and exit nano.

Restart Samba:

$ sudo /etc/init.d/samba restart

I forgot this next step, so don’t forget this step! Create a Samba user of the same name as your Linux user. To create a Samba user:

$ sudo smbpasswd -a backupUser

If you want to view the Samba users:

$ sudo pdbedit -L -v

In case you need to remove a Samba user:

$ sudo pdbedit -x -u username

Here’s where things go wrong. If the drive is owned by root, then you can’t log in from Windows. Change to the user you created: backupUser:

$ su backupUser

Now you will need to mount the drive as this user:

$ sudo mount -t auto /dev/sda1 /media/1_5TBExt

If you get the error: Mount is denied because the NTFS volume is already exclusively opened… it means that the drive is already mounted and assigned. Find out where it’s mounted:

$ lsblk

List the drives:

$ sudo fdisk -l
NAME        MAJ:MIN RM SIZE RO TYPE MOUNTPOINT
mmcblk0     179:0   0  7.5G 0       disk
+-mmcblk0p1 179:1   0  56M  0       part /boot
+-mmcblk0p2 179:2   0  7.5G 0       part /
sda           8:0   0  1.4T 0       disk
+-sda1        8:1   0  1.4T 0       part /media/1_5TBExt

If you see your drive mounted, make sure that your user is the owner or that the group has read/write.

$ cd /media
$ ls -l

This will display your drives and the owners. If your drive owner is root:root, you need to change the owner to your backupUser using chmod. Since I don’t have a good grasp of permissions, I’ll let you figure this out. Meanwhile, here’s a pleasant photo for you while you pull your hair:

Rays Forest Dawn Sage Dusk Trees Photography Wallpaper Iphone 4

Go to a Windows PC on your network and connect to your server. In this example, it’s RASPBERRYPI. You should see your “Backup” location as well as the user’s home directory. Make sure you can read and write to this location – save a text file there or something.

If you can see the server and the location but you can’t write to it, then you probably didn’t mount the drive as the backupUser.

I later added another Samba share location for my /home/backupUser/myfiles location so that I could back up my web server files. This required another entry in the smb.conf file for that location.

[BackupWeb]
comment = Backup For Web
path = /home/backupUser/myfiles
valid users = @users
force group = users
create mask = 0660
directory mask = 0771
read only = no

Set Up a Web Server

The hard part is done. Getting the drive mounted and the permissions set is a battle. The rest is pretty easy.

The web server will run Apache (that’s my preference), MySQL db, and PHP. If you didn’t update/upgrade today, then do it now:

$ sudo apt-get update 
$ sudo apt-get upgrade

Install Apache

The following command installs Apache 2.4 web server:

$ sudo apt-get install apache2 apache2-utils

Once installed, check the installation by navigating to: http://RASPBERRYPI/ (or whatever your Pi server name is) from anywhere on your network. You should see an html page: It works! The web server files are here:

$ cd /var/www

Side Note: My Apache install didn’t go perfectly. I didn’t update/upgrade before installing it; I did it after installing Apache – and that worked for me.

Install PHP

The following command installs the PHP 5 and some PHP libraries:

$ sudo apt-get install libapache2-mod-php5 php5 php-pear php5-xcache php5-mysql php5-curl php5-gd

Note: the PHP.INI file is here:

/etc/php5/apache2/php.ini

After installing, test it to make sure it’s working by creating a index.php file and calling PHP Info. Change the directory to the default document root:

$ cd /var/www/

Create a php file for testing the db connection:

$ sudo nano test.php

and enter

 <? print "PHP is working."; ?>

Test it. For some reason, it won’t work if you create index.php. This is likely an owner problem. The default user for Apache is www-data. The following command changes the ownership to the Apache default user recursively for all files in the selected directory and its subdirs:

$ sudo chown -R www-data:www-data /var/www *

As an aside, while you’re trying to figure out how to set permissions – a major pain – you can clean up the install files by running:

$ sudo apt-get clean

The PHP files need to have their permissions changed to executable – I think. Although I’m not too worried about giving out too much permissions, I do want to know how to set permissions properly.

Once you have installed Apache, gotten the It works! to work and installed PHP and gotten php to work, you can now install MySQL.

Install MySql

Installing PHP was much easier to install on the Pi than it ever was on a Windows PC. MySql also is pretty easy.

$ sudo apt-get install mysql-server

The installation will ask you for a master password. Don’t forget it.

I repeat – don’t forget your master password.

Create a database called “test”:

$ mysql -u root -p
Enter password:**************
mysql> CREATE DATABASE test;
mysql> USE test;
mysql> exit;

Create a PHP file that connects to test:

$ cd /var/www
$ sudo nano dbtest.php

Paste the following, substituting your user and password:


Save the php file, and open mySql again.

$ mysql -u root -p
Enter password:**************
mysql> USE test;

Create a table in test called “people”- just paste this at the mysql prompt:

mysql> CREATE TABLE people (
ID int NOT NULL AUTO_INCREMENT,
name varchar(255) NOT NULL,
address varchar(255),
PRIMARY KEY (ID)
);

Add a record:

mysql> INSERT INTO people (name, address) VALUES ('Lars','123 Monsen Ave');

You don’t need to enter the IP address; you can use the pi server name:

http://raspberrypi/dbtest.php

If all goes well, you should see your people data.

Set Up Scheduled Backup

First, create a .sh file that contains the commands that you want to run. I just added mine in the backupUser home directory.

$ sudo nano backupDaily.sh

In the backupDaily.sh file, enter:

#!/bin/bash
sudo cp /var/www/myfiles/*.txt /home/backupUser/myfiles

Make it executable:

$ chmod +x backupDaily.sh

This file will copy all *.txt files in /var/www/myfiles/ to /home/backupUser/myfiles
It copies the files from the inaccessible web dir to one that is accessible to Windows via Samba

Test it but entering:

$ sh backupDaily.sh

Make sure it copies all the files to the backup location.

Now schedule it using crontab.

I used crontab -e logged in as root because I couldn’t get it to work any other way:

$ crontab -e

At the bottom of the file, add:

0 23 * * * /home/backupUser/backupDaily.sh

This runs the backupDaily.sh file at zero minutes on the 23rd hour (midnight). Note – add a blank line after this line. I read this somewhere: “ALWAYS add a line break to your Cron Job. If your Cron Job does not run it’s probably the reason why” – so I add a line break, just in case.

You can add lines to the script. I added a line to compress the files into a single file with the date and time stamp. Added to the cron script:

tar -vczf DailyBackup_$(date +%Y-%m-%d_%H%M).tar.gz /home/backupUser/myfiles/*.txt

Create a Windows Batch File

Make sure the Windows PC has the credentials saved for the raspberrypi server. On the Windows PC, open a notepad and save a backupcopy.bat file. Add the line:
copy \\RASPBERRYPI\Backups\*.txt D:\MyBackups\pibackup\

I will probably just copy over the gz file eventually.
==+++++

Change Server Name

To change the server name: At the terminal, type the following command to open the hosts file:

sudo nano /etc/hosts

??????

sudo nano /etc/hostname

Add a User to SU

Login as root or su to get root prompt:

visudo

An editor will open. Find the line:

root ALL=(ALL) ALL

and add your new user with super user privileges:

newusername ALL=(ALL) ALL

Type Ctrl+X Type Y to save and close.

Helpful Notes

$ cat /etc/*release
PRETTY_NAME="Raspbian GNU/Linux 7 (wheezy)"
NAME="Raspbian GNU/Linux"
VERSION_ID="7"
VERSION="7 (wheezy)"
ID=raspbian
ID_LIKE=debian
ANSI_COLOR="1;31"
HOME_URL="http://www.raspbian.org/"
SUPPORT_URL="http://www.raspbian.org/RaspbianForums"
BUG_REPORT_URL="http://www.raspbian.org/RaspbianBugs"

Current Directory

$ pwd

User files:

$ cd /home/backupUser/

Change to your user’s dir:

$ cd

Web files:

$ cd /var/www

Disk free space

$ df
/dev/mmcblk0p1 57288 20344 36944 36% /boot percent full
/dev/sda1 1465136000 1125819892 339316108 77% /media/1_5TBExt

Drive mounts:

$ cd /media/

Reboot

$ sudo shutdown -r

Shut down now

$ sudo shutdown -h now

List users:

$ cat /etc/passwd

To modify the username of a user:

$ usermod -l new_username old_username

To change the password for a user:

$ sudo passwd username

Add user

sudo adduser new_username

Delete user

sudo userdel username

Delete the home directory of the user:

sudo rm -r /home/username

List drives

lsblk