Configure WordPress on LAMP, Ubuntu 14.04, VPS

This is tutorial how to install and configure simple WordPress based website to run in your own virtual private server (VPS).

From my previous blog post, you can see how to buy a domain, acquire a VPS and from another post how to configure LAMP-stack into that. Now we are continuing from there and installing WordPress into it.

Configuring MySql

First we’ll need to configure MySql server. Just to make sure:

sudo apt-get install mysql-server

And then we’ll create new user and database for the WordPress

mysql -u root -p
create database wpaxel;
grant all on wpaxel.* to wpaxel@localhost identified by "GOOD_PASSWORD_HERE";

Also remember to check that you have php5-mysql installed, because it’s needed by the WordPress

sudo apt-get install -y php5-mysql

Get and configure WordPress

When I’m at /home/axel/public_html/axelauvinen.com, I will wget latest package of WordPress and extract it

wget http://wordpress.org/latest.tar.gz
tar -xf latest.tar.gz

This will create a folder called WordPress. Next I’ll move the content of that folder into the one we are at and remove useless folder

mv wordpress/* .
rm -r wordpress

Now when I open up my url (www.axelauvinen.com) I will see a setup screen showing up.

Into the setup, insert your databases information, create your user and install the WordPress.

Here you can see working result: http://www.axelauvinen.com

Resources

Course of Fall 2015, Tero Karvinen, Linux as a Server

Advertisements

Configuring apache and domain to VPS

Task this time is to create a Virtual Private Server (VPS) and register a domain into your server.

I have bought a domain from namecheap and I have billing plan going on with Digital Ocean. In this task I will install apache2, harden the security of my server and configure apache to be called from given domain (www.axelauvinen.com)

Task

First I’ll create a ‘droplet’ in DigitalOcean. This is a single virtual server. When the droplet is ready I’ll connect into it with given root user and password.

ssh root@ipaddress

Creating user and locking root

When I’m in, I will create new user and add that user into sudo group

sudo adduser axel
sudo adduser axel sudo

When this is done I’ll lock user root login with following command

sudo passwd -l root

Now I have custom user created with sudo privileges and root login locked.

Firewall

To begin with I’ll use UFW (Universal Firewall) to just disable all ports except port 22 (so I can have ssh connection)

sudo ufw allow ssh
sudo ufw enable
sudo ufw status

After these commands my UFW status seems like this

Status: active

To Action From
-- ------ ----
22 ALLOW Anywhere
22 (v6) ALLOW Anywhere (v6)

Configuring NameCheap domain to my ipaddress

I’ll be using this tutorial to register my ipaddress to my domain

In a nutshell, I created 2 new Host Records forwarding to my ipaddress with Host values @ and www

Screen Shot 2015-09-30 at 18.26.50

Installing and configuring apache

So now I will install apache

sudo apt-get install apache2

And then I add userdir module to apache2 and create my VirtualHost configuration to location /home/axel/public_html/axelauvinen.com/

sudo a2enmod userdir
mkdir -p /home/axel/public_html/axelauvinen.com
sudoedit /etc/apache2/sites-available/axelauvinen.conf

With content:

<VirtualHost *:80>
 ServerName www.axelauvinen.com
 ServerAlias axelauvinen.com
 DocumentRoot /home/axel/public_html/axelauvinen.com
</VirtualHost>

And then from folder /etc/apache2/sites-available/ i’ll run following command to my new conf file:

sudo a2ensite axelauvinen.conf

Then I reboot my apache2

sudo service apache2 restart

After all this is done, i’ll enable port 80 from ufw

sudo ufw allow 80/tcp

Also I created small index.html file with just text content in folder /home/axel/public_html/axelauvinen.com/ so when the host registration is done, axelauvinen.com should show this text content

Conclusion

Now I’ll just have to wait until Namecheap registers my new Host record files. They said it’ll take 30 minutes, but we’ll see. I will update this when the registration is done.

Additions: Now the registration is done and domain is fully functional. Next step is to configure name-based wordpress, with a nice theme and import all my earlier blog posts into it.

Resources

 

Tero Karvinen, course Linux as a server

Apache2 virtualhost examples

Creating deb metapacket and packet repository on Ubuntu 14.04

Description of the task

First I will create metapacket of some programs/tools and to make sure it’s valid packet, I’ll use tool called lintian.

Next I will create packet repository with reprepro and serve it with apache2.

Then I’ll create simple shell script and add it into my metapacket, so it’s usable for all the users after installation.

Environment

I’ll be using Vagrant for this job

Here is a quick guide how to setup Vagrant on your computer

I added these 2 lines in my Vagrantfile so I can locally test my apache configurations from given ip address

 config.vm.network "private_network", ip: "192.168.33.26"
 config.vm.hostname = "metapacket-test"

My hardware is Macbook Pro (mid-2014) and Vagrant installation will be Ubuntu 14.04 64-bit

Operating system: OSX Yosemite

Task

First I’ll install equivs, which is a packeting tool for deb packages

sudo apt-get install equivs -y

This installs 2 tools, called equivs-control and equivs-build

Configuring deb package

First tool we’ll use is equivs-control, which creates a configuration skeleton file for the incoming package. Always use proper naming in your files.

equivs-control axel-auvinen-basic-toolkit.cfg

Next we’ll edit that file. Most important fields are Package (package name), Version (version number), Depends (your metapackets dependencies)

nano axel-auvinen-basic-toolkit.cfg

After editions my file looks like this

Section: misc
Priority: optional
Homepage: https://axelauvinen.wordpress.com
Standards-Version: 3.9.2
Package: axel-auvinen-basic-toolkit
Version: 0.0.1
Maintainer: Axel Auvinen <axel.auvinen@gmail.com>
Depends: tree, htop, wget, apache2, openssh-client, curl, nmap, screen
Description: Basic toolkit for my own use
 Basic tools I use on my everyday life

Building and testing deb package

To build the package, I’ll use equivs-build

equivs-build axel-auvinen-basic-toolkit.cfg

For testing the package I’ll use lintian so:

sudo apt-get install lintial -y

And to test just run lintian on your file

lintian axel-auvinen-basic-toolkit.cfg

It gave no errors, so it’s good to assume it’s properly packaged.

Installing deb package

For installation I’ll use gdebi:

sudo apt-get install gdebi -y

and to install the local deb package run:

sudo gdebi -n axel-auvinen-basic-toolkit_0.0.1_all.deb

After this I confirmed that some of these were truly installed.

Creating packet repository with reprepro

For this I’ll need reprepro, and also apache which I already installed with my packet. But just for a reminder:

sudo apt-get install apache2 reprepro -y

Into /var/www/html folder I’ll run following commands (with sudo because root owns these and they are shared publicly anyways)

sudo mkdir -p repository/conf
sudoedit repository/conf/distributions

And to that distributions file I’ll insert following configuration

Codename: trusty
Components: main
Suite: trusty
Architectures: i386 amd64 source

And inside /var/www/html I’ll run the following command (as sudo because root owns folders)

sudo reprepro -VVVV -b repository/ includedeb trusty /home/vagrant/axel-auvinen-basic-toolkit_0.0.1_all.deb

If you now want to install this package from a client computer, you’ll have to add masters ip address and folder location into apt’s configuration, like this:

sudoedit /etc/apt/sources.list.d/repository.list

With this content (my local ip address):

deb http://192.168.33.26/repository trusty main

Let’s test it works

sudo apt-get update
sudo apt-get install axel-auvinen-basic-toolkit

Everything seems to work as it should – apt found my package and was able to confirm that the package was at it’s newest version as it should be.

Packing a script into deb package

First off I’ll create a simple script like this in to the same location where my .cfg is:

nano hardware-and-ip

Content:

#!/bin/bash
lshw -short
hostname -I
hostname

And then to make it executable:

chmod +x hardware-and-ip

Next we’ll edit the .cfg file and add following row (also increased the version number)

Files: hardware-and-ip /usr/local/bin

This will package the file into the package and it will be installed into given folder on installation

Lets test this:

equivs-build axel-auvinen-basic-toolkit.cfg
sudo gdebi -n axel-auvinen-basic-toolkit_0.0.2_all.deb
hardware-and-ip

Everything works as they should be.

 

 

Resources

Tero Karvinen, course Linux as a server

Tero Karvinen, Create deb metapackage in 5 minutes

Tero Karvinen, Update All Your Computers with a .DEB Repository

Files in equivs

Honeynet Scan of the month, Scan 15

I was given a task to complete HoneyNet Scan of the month -challenge, Scan #15. The challenge is stated below and some keywords for the scan would be forensic analysis (data-analysis of malicious acts) and rootkit (set of malicious scripts / softwares)

As a bonus task, one should explain step by step how the rootkit works and search for clues of the creator.

Environment

I’ll be using Vagrant for this job, because it’s easy to test this kind of things without messing up your own computer

Here is a quick guide how to setup Vagrant on your computer

I added these 2 lines in my Vagrantfile so I can locally test my apache configurations from given ip address

 config.vm.network "private_network", ip: "192.168.33.25"
 config.vm.hostname = "honeynet15"

My hardware is Macbook Pro (mid-2014) and Vagrant installation will be Ubuntu 14.04 64-bit

Operating system: OSX Yosemite

The Challenge:
On 15 March. 2001, a Linux honeypot was successfully compromised, a rootkit was download to the / partition and then deleted from the system. Your mission is to find and recover the deleted rootkit. If you are not sure where to begin on conducting this forensic analysis and recover the rootkit, we highly reccommend you start with the Forensic Challenge. The steps you will have to follow for the rootkit recovery are similar to the steps discussed there. We have posted only the / partion for download to keep this challenge simple. The compressed image is 13MB, (honeynet.tar.gz)MD5=0dff8fb9fe022ea80d8f1a4e4ae33e21. Once you have downloaded, untarred, and unzipped the partition image, it will be 255 MB and the checksum should be MD5=5a8ebf5725b15e563c825be85f2f852e.

  1. Show step by step how you identify and recover the deleted rootkit from the / partition.
  2. What files make up the deleted rootkit?

Bonus Question:
Was the rootkit ever actually installed on the system? How do you know?

Doing the challenge

Everything I do and report here is done in real-time. I’m starting the challenge on 17:50 on September 14.

Setting up the environment

First I’ll download the file from their website. (you can also directly wget the file from the url with ‘wget http://old.honeynet.org/scans/scan15/honeynet.tar.gz’)

Next I’ll move it to my vagrant box’s folder and vagrant-scp it into the virtual machine.

vagrant scp honeynet.tar.gz 358bdc9:/home/vagrant

Then I’ll ssh into the VM (vagrant ssh) and start analysing.

Untar files

First I’ll untar the file (x = extract, v=verbose, f=file)

tar xvf honeynet.tar.gz

Next I will go into the extracted folder and it looks like this

vagrant@honeynet15:~/honeynet$ tree
.
|-- honeypot.hda8.dd
`-- README

As you can see, there is an image file (dd) and that is the analyzation target

Retrieving undeleted and deleted files from DD-image

 

In Teros website there is a good explanation how to recover undeleted and deleted files from the DD-image. First I’ll create folders called allocated and deleted, then I’ll extract data from DD-image (dependency: sudo apt-get install sleuthkit)

mkdir allocated deleted
tsk_recover -a honeypot.hda8.dd allocated/
tsk_recover honeypot.hda8.dd deleted/

These commands will recover all the files from the image into these folder. (-a flag is for allocated (undeleted) files, without flags it extracts the unallocated files)

Analyzing recovered files and searching for the rootkit

In the deleted files I found a lk.tgz file which really confused me, because normally there ain’t any tar files in root (/) folder. Next I’ll untar that and we’ll see what is inside.

tar xvf lk.tgz

It extracted folder called last with following content

vagrant@honeynet15:~/honeynet/deleted/last$ tree
.
|-- cleaner
|-- ifconfig
|-- inetd.conf
|-- install
|-- last.cgi
|-- linsniffer
|-- logclear
|-- lsattr
|-- mkxfs
|-- netstat
|-- pidfile
|-- ps
|-- s
|-- sense
|-- services
|-- sl2
|-- ssh
|-- ssh_config
|-- sshd_config
|-- ssh_host_key
|-- ssh_host_key.pub
|-- ssh_random_seed
`-- top

With ls -la command I can see that install was the last file that was edited and also the name install intrigues me

I open the content of the file with cat (cat install) command and it is getting clear to me that this is the install file of the rootkit.

What the rootkit does

First in the top of the file, there are some declarations / taunting of the author (some swearing and suggestion of sucking on something) and clear notification that it is a rootkit.

What the rootkit actually does is, it first goes through what components are installed (make, gcc, sshd)

Next it’ll try to remove old configuration files (for example ifconfig, netstat..) and move its own files into their places. Also it tries to change add content in /dev/rpm file (rpm is package manager of redhat distributions)

There are some IP addresses and port numbers it tries to copy  into /dev/last file. Googling the first ip, it seems that it’s located in Romania.

After this it copies it’s other shell commands into /dev/ida/.drag-on and /dev/ida”.. ” folders and then removes the original ones (tries to be cunning with folder names)

Next it tries forcefully to copy some configuration files into /etc (services and inetd.conf) and remove some shell scripts from /usr/bin/ folder. Also it tries to insert it own shell scripts in to previous folder.

Last malicious act it tries to do, is to copy last.cgi file into any installed Web Server (.cgi because it was year 2001). After that it tries to send via email hardware information into these two email adresses (clues of the creator):

bidi_damm@yahoo.com
last@linuxmail.org

And also it removes all the original files with

rm -rf last lk.tgz computer lk.tar.gz

Let’s find out if this particular computer was affected by rootkit

So now that we know how the installation of rootkit works, we can check if any or some of these malicious acts were done to the computer

By doing sha25sum command into ../allocated/sbin/ifconfig, and comparing that to the rootkits sha256sum of its ifconfig file, I can see that it was copied from the original rootkit folder, because the sum matches.

After checking out some other files I can be sure that the computer was affected by the rootkit

Authors comments

This challenge was indeed quite intriguing. I really enjoyed studying how to recover files off of an image file and how some simple malicious acts could be done.

This is the first time I’ve ever seen and studied a rootkit.

The task was done and reported on 19:50, 2 hours in total.

Edited: way of comparing files

Resources

HoneyNet website

Wikipedia, Rootkit & Forensic Analysis explinations

Tero Karvinen, course Linux as a server

Tero Karvinen, Forensic File Recovery

Monitoring Ubuntu 14.04 with various tools (munin, htop, stress)

In this blog post I will be monitoring Ubuntu 14.04 with various tools and stressing it out with stress.

Environment

I’ll be using Ubuntu 14.04 live boot USB stick on a computer with following specs:

Intel i5 760 2.8 ghz
8gb RAM 1333 mhz
Asus P8P67 motherboard

Task

First upgrade and update your Ubuntu

sudo apt-get update
sudo apt-get upgrade

Next install munin and munin-node

sudo apt-get install munin -y
sudo apt-get install munin-node -y

Then I’ll open munin data with browser by entering file:///var/cache/munin/www to browser

This will open up directory of munin statistic files. Under localdomain.localhost directory you’ll find various charts and statistics about your computers hardware usage.

Next I will apply stress to computer with program called stress. While this is running I will monitor base stats with htop

sudo apt-get install stress -y
sudo apt-get install htop -y

While stress is running, I’ll open another terminal window with htop. Statisics look something like this without stress

Screenshot from 2015-09-09 08:21:41

And like this with stress. Stress will use all CPU Cores and load the machine quite heavily. This is why I inserted timeout to be 20 seconds.

stress --cpu 8 --io 4 --vm 2 --vm-bytes 128m --timeout 20s

Screenshot from 2015-09-09 08:25:00

We can see that stress uses 24,4 and 19.9 % of maximum capacity. I’m not quite sure why there are two processes running, but the main point is that we can analyze the load. Apparently stress didn’t use any memory, which confuses me. But for example firefox uses 7.9 % of memory capacity (this isn’t the whole true though)

Analyzing Munin statistics

Screenshot from 2015-09-09 08:31:15

Screenshot from 2015-09-09 08:30:53

Here are few basic graphs, as you can see, while I had stress going on, the graphs were going high. Munin statistics update with cron job in 5 minute intervals, so after a while the graphs will look better.

Analyzing log files

Here is a log file of syslog about the cron job I mentioned earlier

Sep  9 08:25:01 ubuntu CRON[15601]: (root) CMD (if [ -x /etc/munin/plugins/apt_all ]; then munin-run apt_all update 7200 12 >/dev/null; elif [ -x /etc/munin/plugins/apt ]; then munin-run apt update 7200 12 >/dev/null; fi)

On September 9th at 8:25:01 am, on machine ubuntu trigger CRON job with PID (process id) 15601 as user  root. It runs a shell script as stated after CMD (CMD mean just command)

Edited and specified on 10th of September

Resources

http://guide.munin-monitoring.org/en/latest/tutorial/getting-started.html

Tero Karvinen, classes

LAMP and basic tooling in Ubuntu 14.04 – old course exam

In course Linux as a Server I was given a task to do an old exam. I chose one where the job was to create simple LAMP (Linux, Apache, MySQL, PHP) environment, for 4 users, a shell script to print diskspace status and Ip address

Environment

I’ll be using Vagrant for this job, because it’s easy to test this kind of things without messing up your own computer

Here is a quick guide how to setup Vagrant on your computer

I added these 2 lines in my Vagrantfile so I can locally test my apache configurations from given ip address

 config.vm.network "private_network", ip: "192.168.33.15"
 config.vm.hostname = "ubuntu-machine0"

My hardware is Macbook Pro (mid-2014) and Vagrant installation will be Ubuntu 14.04 64-bit

Operating system: OSX Yosemite

Specifications

Naming usernames, I’ve gotten fond to a way of using 5 letters from last name and 3 of first name. If last name happens to be less than 5, then I’ll add more from first name

My name as username for example: auvinaxe

For scandinavian letters ä -> a, ö -> o and å -> a

Task

Before anything, let’s update repositories and package lists and upgrade the machine

sudo apt-get update
sudo apt-get upgrade -y

Let’s start with setting up LAMP environment.

Apache

First off, we’ll need apache. Task states that we’ll need user directory based websites so a2enmod userdir is required also

sudo apt-get install apache2 -y
sudo a2enmod userdir
sudo service apache2 restart

Always test even small steps so ifconfig gives you your ip and insert that into your browser and it should print out “It works! “-web page

PHP

sudo apt-get install libapache2-mod-php5

To enable php in apache’s configuration we must change file php5.conf from apache confs like so

sudo nano /etc/apache2/mods-available/php5.conf

And comment out row that states php_admin_flag engine Off like so:

#php_admin_flag engine Off

After this, restart apache with

sudo service apache2 restart

You can test this by creating public_html folder in you /home/username/ directory and creating index.php file into that with this content:

            <?php
            $ip=$_SERVER['REMOTE_ADDR'];
            echo "IP address= $ip";
            ?>
This should print out your IP address from address http://ipaddress/~username, in my case http://192.168.33.15/~vagrant

MySQL

Next we’ll install MySql server

sudo apt-get install mysql-server -y

It will ask you to create root password so do so

After that you can access your database with that root username like this

mysql -u root -p

Where -u flag is for user(name) and -p flag is for asking a password

It is recommended to rename the root user and create proper password for it

Creating users

Next up is to create 4 users with public_html folders and simple php webpage in those. For this I’m using skel configuration like this:

vagrant@ubuntu-machine0:/etc/skel$ tree
.
`-- public_html
 `-- index.php

Where index.php’s content is the example php code I show’d earlier

With this done, I can begin creating the users

sudo adduser vahakein
sudo adduser winhapek
sudo adduser anderake
sudo adduser lailalei

Command prompt will ask you for some information, give it those. Always use secure and well-formed password, with small and capital letters, numbers, special characters and so that is is atleast 10 digits long

Always use command where the verb comes first, it does everything you need.

After this, you should test that your users work (su username for logging in as another user) and in this case also test that their apache userdirectories work (in my case for example http://192.168.33.15/~vahakein/)

Global shell script

The given task was to create shell script that can be ran everywhere and it had to print out basic disk information and ipaddress

First let’s create the file in your home directory

nano mystatus

The content you’ll want is

#!/bin/bash
df -h
hostname -i

Next we have to modify file privileges so it’s executable

chmod +x mystatus

To make it global we have to move it into /usr/local/bin folder. When the file is there, you are able to say mystatus anywhere in your system (with any user) and it prints out the information

Additional stuff

Task also stated that I have to install text editor. I prefer editor called Atom (hackable and totally configurable)

To install Atom, you need to add external repository, update repository list and then you can install the software

sudo add-apt-repository ppa:webupd8team/atom
sudo apt-get update
sudo apt-get install atom

OpenSSH

I forgot to install openssh-server to my computer (it was in the task) so here I go

sudo apt-get install openssh-server

And then I test it locally by this command

ssh vahakein@localhost

So it authenticated as vahakein by ssh to local machine

Resources

Tero Karvinen -website, the old exam

Tero Karvinen, learning from his courses in general

Daily usage of unix systems

MySql best practises

Atom installation on Ubuntu 14.04

Edited on 10th of September (added SSH installation and testing)

Setup simple Vagrant environment (Ubuntu 14.04) on OS X Yosemite

This is simple guide to setup Vagrant on OS X Yosemite.

I’m setting up one virtual machine with Ubuntu 14.04 distribution and will go through some basic vagrant commands.

I will be using Homebrew for this and I highly recommend it as your default package manager in OS X.

Tutorial

First lets install dependencies:

brew cask install virtualbox
brew cask install vagrant

Next we’ll add Ubuntu 14.04 to virtualbox. This will take for a while (for more distros, check here):

vagrant box add ubuntu/trusty64

Then I’m going to create folder structure like this:

/Users/axel/vagrantboxes/ubuntu-machine0

In debian-based (and several other *nix) distros this would be /home/username/…

After structure is complete, I’m going into that folder and after these commands your virtual machine is up and running (will take for a while):

vagrant init ubuntu/trusty64
vagrant up

You’ll see Vagrantfile generated in your folder. That is the whole configuration file for your virtual machine. For more about Vagrantfile and configuration I can suggest their documentation for more. Also google is your friend to find preconfigured Vagrantfiles.

Basic commands

All these commands are run in your local folder, in this case ../vagrantboxes/ubuntu-machine0.

Access box (simulates ssh, so command ‘exit’ will leave)

vagrant ssh

Stop box

vagrant halt

Suspend box

vagrant suspend

(re)Start box

vagrant up

See status

vagrant status

Check status of all vagrant boxes (prints id’s, names, states and directories also)

vagrant global-status

Also if you want to install plugin, you can install them like so:

vagrant plugin install <plugin-name>

Useful plugin to move files from local to box is vagrant-scp, here is how to use it:

vagrant scp filename ab8f4b6:/home/vagrant

Where text ab8f4b6 refers to id of the box (vagrant global-status)

Resources

Vagrant setup guide

Vagrant documentation

USB Live Boot Ubuntu 14.04 with unetbootin and OSX Yosemite

Description

Short tutorial how to create live usb boot stick with unetbootin.

Environment: OSX Yosemite, MacBook Pro 2014 (mid-summer)

Tools: Google Chrome and unetbootin

Tutorial

  1. Download unetbootin from their website
  2. Install software to your computer.
    1. It may complain about allowing apps to be run from foreign sources, so you need to change your Security and Privacy from System Preferences (General > Allow apps downloaded from > Everywhere)
  3. When your software is installed, run it and you’ll see window where you have select distribution and select your USB stick like so
    1. Screen Shot 2015-09-01 at 19.00.24
  4. After you have selected the distribution and version you want (In my case I selected Ubuntu 14.04_Live_x64) and the target USB drive, press OK and it will start the progress.
  5. When progress is done, you should always assure that the boot stick works

Sources

Unetbootin http://unetbootin.github.io/

 

Arduino: Project: Photoresistor to shutdown a computer, FlashlightToggle

The big idea of this project is to find alternative ways to shutdown / start up computers. I’ve already thought about clap-on, clap off toggle, but the sensor I was trying it with was bad. It didn’t give much or any changes in readings when sound was short. When sound was continious it gave little changes.

So to this project. The FlashlightToggle works like this: blink a flashlight to the photoresistor 5 times. Then python-serial reads the value serial is giving and runs shutdown command, computer shuts down. If you only flash light one to four times, nothing happens and if you wait for 20 seconds of the first flashing, it resets.

Testing arduino:

ALWAYS before starting a new project, one must test arduino with hello world (blink). Check my earlier blog posts for this. Never skip it.

Installing Python and pySerial

To command line in Ubuntu 12.04:

sudo apt-get update
sudo apt-get install python
sudo apt-get install python-serial

Testing:

So to test out, I’m going to insert my arduino to testing machine, type:

sudo python

and write down:

import serial
ser = serial.Serial('/dev/ttyACM0', 9600)
while True:
   print ser.readline()

then after last line is written, unix command line starts printing arduino serial monitor

Example image from this project:

commandline

Tools and components:

Components:

Arduino UNO 3.0 (basicly any Arduino should fit)

Photoresistor

USB-cable

5x 220 Ohm resistors

1x 10k Ohm resistor

several jumper wires

Sketch:

Here is beautiful sketch made by me. Simply connect leds to digital ports and ground through 220 ohms. Photoresistor need to have 10k ohm to ground, and between photoresistor and 10k you wire jumperwire to analog port. Also you have to give it 5v power.

arduino_breadboard

Tools:

I used Arduino IDE for coding and to insert my codes to Arduino.

Arduino C++ code:

const int gled1 = 13;
const int yled1 = 12;
const int yled2 = 11;
const int rled1 = 10;
const int rled2 = 9;
const int lightsensor = 0;

double sensorreading = 0.0;
int rbit2 = 0;
int rbit1 = 0;
int ybit2 = 0;
int ybit1 = 0;
int gbit1 = 0;
int time;
int x = 0;
int target = 0;

void setup() {
  Serial.begin(9600);  
  Serial.println("Serial started:");
  pinMode(gled1, OUTPUT);
  pinMode(yled1, OUTPUT); 
  pinMode(yled2, OUTPUT); 
  pinMode(rled1, OUTPUT); 
  pinMode(rled2, OUTPUT);  
}

void loop() {
  sensorreading = analogRead(lightsensor) / 1023.0;
  Serial.println(sensorreading);
  if(sensorreading > 0.88 && rbit2 == 0){
    digitalWrite(rled2, HIGH);
    delay(500);
    rbit2 = 1;
  }
  sensorreading = 0.00;
  sensorreading = analogRead(lightsensor) / 1023.0;
  if(sensorreading > 0.88 && digitalRead(rled2) && rbit1 == 0){
    digitalWrite(rled1, HIGH);
    delay(500);
    rbit1 = 1;
  }
  sensorreading = 0.00;
  sensorreading = analogRead(lightsensor) / 1023.0;
  if(sensorreading > 0.88 && digitalRead(rled1) && ybit2 == 0){
    digitalWrite(yled2, HIGH);
    delay(500);
    ybit2 = 1;
  }
  sensorreading = 0.00;
  sensorreading = analogRead(lightsensor) / 1023.0;
  if(sensorreading > 0.88 && digitalRead(yled2) && ybit1 == 0){
    digitalWrite(yled1, HIGH);
    delay(500);
    ybit1 = 1;
  }
  sensorreading = 0.00;
  sensorreading = analogRead(lightsensor) / 1023.0;
  if(sensorreading > 0.88 && digitalRead(yled1) && gbit1 == 0){
    digitalWrite(gled1, HIGH);
    delay(500);
    gbit1 == 1;
    lightshow();
  }
  delay(100);
  wait();
}
void wait(){
    time = millis()/1000;
    while(x == 0){
      if(rbit1 == 1 || rbit2 == 1 || ybit1 == 1 || ybit2 == 1 || gbit1 == 1){ 
        target = time + 20;
        x++;
      }
      x++;
    }
    if(time >= target){
     digitalWrite(gled1,LOW);
     digitalWrite(yled1,LOW);
     digitalWrite(yled2,LOW); 
     digitalWrite(rled2,LOW); 
     digitalWrite(rled1,LOW);
     rbit1 = 0;
     rbit2 = 0;
     ybit1 = 0;
     ybit2 = 0;
     gbit1 = 0;
     x=0; 
    }
}
void lightshow(){
     digitalWrite(gled1,HIGH);
     delay(50);
     digitalWrite(yled2,HIGH);
     delay(50);
     digitalWrite(yled1,HIGH);
     delay(50);
     digitalWrite(gled1,LOW);
     digitalWrite(rled2,HIGH);
     delay(50);
     digitalWrite(rled1,HIGH);
     digitalWrite(yled2,LOW);
     digitalWrite(gled1,HIGH);
     delay(50);
     digitalWrite(yled2,HIGH);
     delay(50);
     digitalWrite(yled1,HIGH);
     delay(50);
     digitalWrite(gled1,LOW);
     digitalWrite(rled2,HIGH);
     delay(50);
     digitalWrite(rled1,HIGH);
     digitalWrite(yled2,LOW);
     digitalWrite(gled1,LOW);
     digitalWrite(rled2,HIGH);
     delay(50);
     digitalWrite(rled1,HIGH);
     digitalWrite(yled2,LOW);
     digitalWrite(yled2,HIGH);
     delay(50);
     digitalWrite(yled1,HIGH);
     delay(50);
     digitalWrite(gled1,LOW);
     digitalWrite(rled2,HIGH);
     delay(50);
     digitalWrite(rled1,HIGH);
     digitalWrite(yled2,LOW);
     digitalWrite(gled1,LOW);
     digitalWrite(rled2,HIGH);
     delay(50);
     digitalWrite(rled1,HIGH);
     digitalWrite(yled2,LOW);
     delay(50);
     digitalWrite(gled1,LOW);
     digitalWrite(yled1,LOW);
     digitalWrite(yled2,LOW); 
     digitalWrite(rled2,LOW); 
     digitalWrite(rled1,LOW);
     rbit1 = 0;
     rbit2 = 0;
     ybit1 = 0;
     ybit2 = 0;
     gbit1 = 0;
     x=0;
     Serial.println("SHUTDOWN");
     delay(1000); 
   }

Python code:

import subprocess
import serial

ser = serial.Serial('/dev/ttyACM0', 9600, timeout=1)
while True:
        print ser.readline()
        line = ser.readline().decode('utf-8')[:-2]
        if line == 'SHUTDOWN':
                subprocess.call(["sudo", "shutdown","-h", "now"])

Just save this python code to lets say like shutdown-arduino.py, then run it into screen with

sudo screen python shutdown-arduino.py

and leave screen running with CTRL+A and CTLR+D

Now when flashlight hits the sensor 5 times, computer shuts down

Results in video (sorry about the wibbily wobbilyness, cameraman was little bit tired):

Info:

Computer:

P8-P67 Rev 3.0 motherboard, AMD 6970 HD 2gb grapich card, Intel I5-2500k 6mb cache 4,5 ghz processor, 8gb 1950mhz RAM, and other important components.

Operating System:

Windows 7 64-bit Professional, Service Pack 1

Testcomputer: Old laptop, running on Ubuntu 12.04

Resources:

Arduino: Serial monitor basics

Writing to serial monitor:

void setup() {                
  Serial.begin(9600);
  Serial.println("This will be only shown at the start");
}
void loop() {
  Serial.println("This will be looping with 1 sec interval");
  delay(1000);
}

Reading sensor values in serial monitor (from my earlier project, TMP sensor):

void setup() {
  Serial.begin(9600);
}

void loop() {
  int sensorValue = analogRead(A0);
  float volt = (sensorValue/1020.0) * 5.0; //Volts
  float tempC = (volt -0.5) * 100; //Celcius
  Serial.println(tempC); //this part is sending the temperature in celcius to serial monitor
  delay(1000);
}

Sending text to serial monitor and printing it out:

char serialmsg = ' ';

void setup() {                
  Serial.begin(9600);
  Serial.println("Serial started");
}

void loop() {
  if (Serial.available()>0) {
    serialmsg = Serial.read();
    Serial.print(serialmsg);
  }
  delay(100);
}

Computer:

P8-P67 Rev 3.0 motherboard, AMD 6970 HD 2gb grapich card, Intel I5-2500k 6mb cache 4,5 ghz processor, 8gb 1950mhz RAM, and other important components.

Operating System:

Windows 7 64-bit Professional, Service Pack 1

Resources: