Create a Simple Date and Time Script in Python

Create a Simple Date and Time Script in Python

CeleriumMind-Python-Banner2


Overview:

This script can be used to parse date and time. Open a blank file and name it for example dateParser.py Copy and paste the code below (and make sure you understand what it does) into the file.

dateParser.py:

from datetime import datetime
now = datetime.now()
mm = str(now.month)
dd = str(now.day)
yyyy = str(now.year)
hour = str(now.hour)
mi = str(now.minute)
ss = str(now.second)
print mm + "/" + dd + "/" + yyyy + " " + hour + ":" + mi + ":" + ss

Now save and exit the file and run it by:
$ python dateParser.py

Time.sleep:

In Python you can use time.sleep() to suspend execution for the given number of seconds. The seconds are being given between the parentheses.

# How to sleep for 5 seconds in python:
import time
time.sleep(5)
# How to sleep for 0.5 seconds in python:
import time
time.sleep(0.5)

How to get the current date and time:

import datetime
now = datetime.datetime.now()
print
print "Current date and time using str method of datetime object:"
print str(now)
print
print "Current date and time using instance attributes:"
print "Current year: %d" % now.year
print "Current month: %d" % now.month
print "Current day: %d" % now.day
print "Current hour: %d" % now.hour
print "Current minute: %d" % now.minute
print "Current second: %d" % now.second
print "Current microsecond: %d" % now.microsecond
print
print "Current date and time using strftime:"
print now.strftime("%Y-%m-%d %H:%M")

The result:

Current date and time using str method of datetime object:

2013-02-17 16:02:49.338517

Current date and time using instance attributes:

Year Month Day House Minute Second Microsecond
2013 2 17 16 2 49 338517

Current date and time using strftime:
2013-02-17 16:02

Conclusion:

I hope this quick guide helps you on your way.  We all have to start somewhere and for me a simple script like this can be the gateway to something much greater.

Thank you


logo3


Building a portable Minecraft server

Minecraft-BannerOriginal Article

Minecraft is a lot of fun, especially when you play with friends. Minecraft servers are great but they aren’t very portable and rely on a good Internet connection. What about if you could take your own portable server with you – say to the park – and it will fit inside a lunchbox?

This post is about doing just that, building a small, portable minecraft server that you can use to host pop up crafting sessions no matter where you are when the mood strikes.

CeleriumMind-Minecraft_1

where shell instructions are provided in this document, they are presented assuming you have relevant permissions to execute them. If you run into permission denied errors then execute using sudo or switch user to elevate your permissions.

Bill of Materials

The following components are needed.

Item QTY Notes
Raspberry Pi 2 Model B 1 Older version will be too laggy. Get a new one
4GB MicroSD card with raspbian installed on it 1 The faster the class of SD card the better
WiPi wireless USB dongle 1 Note that “cheap” USB dongles often won’t support hostmode so can’t create a network access point. The “official” ones cost more but are known to work.
USB Powerbank 1 Make sure it’s designed for charging tablets (ie 2.1A) and the higher capacity the better (5000mAh or better is good).

Prerequisites

I am assuming you’ve done the following with regards to getting your Raspberry Pi operational.

  • Latest Raspbian is installed and is up to date – run ‘apt-get update && apt-get upgrade’ if unsure.
  • Using raspi-config you have set the correct timezone for your location and you have expanded the file system to fill the SD card.
  • You have wireless configured and you can access your network using wpa_supplicant
  • You’ve configured the Pi to be accessible over SSH and you have a client that allows you do this (eg ssh, putty etc).

Setup

I’ll break the setup into a few parts, each focussing on one aspect of what we’re trying to do. These are:

  • Getting the base dependencies you need to install everything on the RPi
  • Installing and configuring a minecraft server that will run on the Pi
  • Configuring the wireless access point.
  • Automating everything to happen at boot time.

Configure your Raspberry Pi

Before running minecraft server on the RPi you will need a few additional packaged than you have probably installed by default. From a command line install the following:

sudo apt-get install oracle-java8-jdk git avahi-daemon avahi-utils hostapd dnsmasq screen

Java is required for minecraft and building the minecraft packages

  • git will allow you to install various source packages
  • avahi (also known as ZeroConf) will allow other machines to talk to your machine by name rather than IP address (which means you can connect to minecraft.local rather than 192.168.0.1 or similar).
  • dnsmasq allows you to run a DNS server and assign IP addresses to the machines that connect to your minecraft box
  • hostapd uses your wifi module to create a wireless access point (so you can play minecraft in a tent with your friends).

Now you have the various components we need, it’s time to start building your minecraft server.

Download the script repo

To make this as fast as possible I’ve created a repository on Github that has all of the config files in it. Download this using the following commands:

mkdir ~/tmp
cd ~/tmp
git clone https://gist.github.com/f61c89733340cd5351a4.git

This will place a folder called ‘mc-config’ inside your ~/tmp directory. Everything will be referenced from there.

Get a spigot build

It is possible to run Minecraft using the Vanilla Minecraft server however it’s a little laggy. Spigot is a fork of CraftBukkit that seems to be a bit more performance oriented and a lot more stable. Using the Vanilla minecraft server I was experiencing lots of lag issues and crashes, with Spigot these disappeared entirely.

The challenge with Spigot is you have to build the server from scratch as it can’t be distributed. This takes a little while on an RPi but is mostly automated. Run the following commands.

mkdir ~/tmp/mc-build
cd ~/tmp/mc-build
wget https://hub.spigotmc.org/jenkins/job/BuildTools/lastSuccessfulBuild/arti...
java -jar BuildTools.jar --rev 1.8

If you have a dev environment setup on your computer you can do this step locally and it will be a lot faster. The key thing is at the end to put the spigot-1.8.jar and the craftbukkit-1.8.jar files on the RPi in the ~/tmp/mc-build/ directory. You can do this with scp.

Now wait a while. If you’re impatient, open up another SSH connection to your server and configure your access point while the build process is happening.

//time passes

After about 45 minutes, you should have your own spigot build. Time to configure that with the following commands:

cd ~/tmp/mc-config
./configuremc.sh

This will run a helper script which will then setup some baseline properties for your server and some plugins to help it be more stable. It will also move the server files to the right spot, configure a minecraft user and set minecraft to run as a service when you boot up.

Once that is complete, you can start your server.

service minecraft-server start

The first time you do this it will take a long time as it has to build out the whole world, create config files and do all sorts of set up things. After this is done the first time however, it will usually only take 10 to 20 seconds to start after this.

Administer your server

We are using a tool called “screen” to run our minecraft server. Screen is a useful utility that allows you to create a shell and then execute things within it and just connect and detach from it as you please. This is a really handy utility say when you are running something for a long time and you want to detach your ssh session and reconnect to it later – perhaps you have a flaky connection.

When the minecraft service starts up it creates a new screen session, and gives it the name “minecraft_server” and runs the spigot server command. The nice thing with this is that once the spigot server stops, the screen will close too.

Now if you want to connect to your minecraft server the way you do it is like this:

sudo screen -r minecraft_server

To leave your server running just hit <CRTL+a> then hit the “d” key. CTRL+A sends an “action” and then “d” sends “detach”. You can keep resuming and detaching like this as much as you like.

To stop the server you can do it two ways. The first is to do it manually once you’ve connected to the screen session then type “stop”. This is good as it means you can watch the minecraft server come down and ensure there’s no errors.

Alternatively just type:

service minecraft-server stop

And this actually simulates doing exactly the same thing.

Connect to your server

Once you’ve got your minecraft server running, attempt to connect to it from your normal computer using multiplayer and then direct connect. The machine address will be minecraft.local (unless you changed it to something else).

CeleriumMind-Minecraft_2

Figure: Server selection

Now you have the minecraft server complete you can simply ssh in, run ‘service minecraft-server start’ and your server will come up for you and your friends to play. The next sections will get you portable and automated.

Setting up the WiFi host

The way I’m going to show you to set up the Raspberry Pi is a little different than other tutorials you’ll see. The objective is that if the RPi can discover an SSID that it is allowed to join (eg your home network) then it should join that. If the RPi can’t discover a network it knows, then it should create it’s own and allow other machines to join it.

This means that when you have your minecraft server sitting in your kitchen you can update the OS, download new mods and use it on your existing network. When you take it to the park to have a sunny Crafting session with your friends, the server will create it’s own network that you can all jump onto.

Turn off auto wlan management

By default the OS will try and do the “right thing” when you plug in a network interface so when you go to create your access point, it will actually try and put it on the wireless network again – not the desired result. To change this make the following modifications to /etc/default/ifplugd

change the lines:

INTERFACES="all"
HOTPLUG_INTERFACES="ALL"

to:

INTERFACES="eth0"
HOTPLUG_INTERFACES="eth0"

Configure hostapd

Now, stop hostapd and dnsmasq from running at boot. They should only come up when needed so the following commands will make them manual.

update-rc.d -f hostapd remove
update-rc.d -f dnsmasq remove

Next, modify the hostapd daemon file to read the hostapd config from a file. Change the /etc/default/hostapd file to have the line:

DAEMON_CONF="/etc/hostapd/hostapd.conf"

Now create the /etc/hostapd/hostapd.conf file using this command using the one from the repo.

cd ~/tmp/mc-config
cp hostapd.conf /etc/hostapd/hostapd.conf

If you look at this file you can see we’ve set the SSID of the access point to be “minecraft”, the password to be “minecraft12345” and it has been set to use wlan0. If you want to change any of these things, feel free to do it.

Now you’ll probably want to kill your wireless device with

ifdown wlan0

Make sure all your other processes are finished if you’re doing this and compiling spigot at the same time (or make sure you’re connected via the wired ethernet as well).

Now run hostapd to just check any config errors.

hostapd -d /etc/hostapd/hostapd.conf

If there are no errors, then background the task (ctrl + z then type ‘bg 1’) and look at ifconfig. You should now have the wlan0 interface up as well as a wlan0.mon interface. If this is all good then you know your config is working for hostapd. Foreground the task (‘fg 1’) and stop the hostapd process (ctrl + c).

Configure dnsmasq

Now to get dnsmasq running – this is pretty easy.

Download the dnsmasq example and put it in the right place using this command:

cd ~/tmp/mc-config
mv /etc/dnsmasq.conf /etc/dnsmasq.conf.backup
cp dnsmasq.conf /etc/dnsmasq.conf

dnsmasq is set to listen on wlan0 and allocate IP addresses in the range 192.168.40.5 – 192.168.40.40. The default IP address of the server will be 192.168.40.1.

That’s pretty much all you really need to get dnsmasq configured.

Testing the config

Now it’s time to test all this configuration. It is probably useful to have your RPi connected to a keyboard and monitor or available over eth0 as this is the most likely point where things may need debugging. The following commands will bring down wlan0, start hostapd, configure your wlan0 interface to a static IP address then start up dnsmasq.

ifdown wlan0
service hostapd start
ifconfig wlan0 192.168.40.1
service dnsmasq start

Assuming you had no errors, you can now connect to your wireless access point from your laptop or phone using the SSID “minecraft” and password “minecraft12345”. Once you are connected you should be given an IP address and you should be able to ping 192.168.40.1 and shell onto minecraft.local.

Congratulations – you’ve now got a Raspberry Pi Wireless Access Point.

As an aside, were you to write some iptables rules, you could now route traffic from the wlan0 interface to the eth0 interface and out onto the rest of your wired network – thus turning your RPi into a router.

Running everything at boot

The final setup task is to make the wifi detection happen at boot time. Most flavours of linux have a boot script called rc.local which is pretty much the final thing to run before giving you your login prompt at a terminal.

Download the rc.local file using the following commands.

mv /etc/rc.local /etc/rc.local.backup
cp rc.local /etc/rc.local
chmod a+x /etc/rc.local

This script checks to see if the RPi came up on the network. If not it will wait a couple of seconds, then start setting up hostapd and dnsmasq.

To test this is all working, modify your /etc/wpa_supplicant/wpa_supplicant.conf file and change the SSID so it’s clearly incorrect. For example if your SSID was “home” change it to “home2”. This way when the RPi boots it won’t find it and the access point will be created.

Park Crafting

Now you have your RPi minecraft server and it can detect networks and make good choices about when to create it’s own network, the next thing you need to do it make it portable.

The new version 2 RPi is more energy efficient, though running both minecraft and a wifi access point is going to use some power.

The easiest way to go mobile is to get a high capacity USB powerbank that is designed for charging tablets. They can be expensive but a large capacity one will keep you going for hours.

This powerbank is 5000mAh and can deliver 2.1amps over it’s USB connection. Plenty for several hours crafting in the park.

Setting this up couldn’t be easier, plug a usb cable into the powerbank and then into the RPi. When you’re done, simply plug the powerbank into your USB charger or computer and charge it up again.

If you want something a little more custom then 7.4v lipo batteries with a step down voltage regulator (such as this one from Pololu: https://www.pololu.com/product/2850) connected to the power and ground pins on the RPi works very well. The challenge here is charging the LiPo again, however if you have the means to balance charge lipos then this will probably be a very cheap option.

If you connect more than 5V to the RPi you WILL destroy it. There are no protection circuits when you use the GPIO pins.

To protect your setup simply put it in a little plastic container like a lunch box. This is how mine travels with me.

Minecraft, Raspberry Pi

A plastic lunchbox will protect your server from spilled drinks, enthusiastic dogs and toddlers attracted to the blinking lights.

Take your RPi and power supply to the park, along with your laptop and some friends then create your own little wifi hotspot and play some minecraft together in the sun.

Going further

If you want to take things a little further, here are some ideas:

  • Build a custom enclosure – maybe something that looks like your favorite minecraft block.
  • Using WiringPi (C) or RPI.GPIO (Python), attach an LCD screen that shows the status of your server and who is connected to the minecraft world.
  • Add some custom LEDs to your enclosure then using RaspberryJuice and the python interface to the API, create objects in your gameworld that can switch the LEDs on and off.
  • Add a big red button to your enclosure that when pressed will “nuke” the game world, removing all blocks and leaving only water.
  • Go a little easier and simply use the button to kick everyone off the server when it’s time to go or your battery is getting low.

Thank you


cropped-logo3.png


 

20 Linux YUM (Yellowdog Updater, Modified) Commands for Package Management


20 Linux YUM (Yellowdog Updater, Modified) Commands for Package Management


Overview

In this article, we will learn how to install, update, remove, find packages, manage packages and repositories on Linux systems using YUM (Yellowdog Updater Modified) tool developed by RedHat. The example commands shown in this article are practically tested on our CentOS 6.3 server, you can use these material for study purpose, certifications or just to explore ways to install new packages and keep your system up-to-date. The basic requirement of this article is, you must have a basic understanding of commands and a working Linux operating system, where you can explore and practice all the commands listed below.

What is YUM?

YUM (Yellowdog Updater Modified) is an open source command-line as well as graphical based package management tool for RPM (RedHat Package Manager) based Linux systems. It allows users and system administrator to easily install, update, remove or search software packages on a systems. It was developed and released by Seth Vidal under GPL (General Public License) as an open source, means anyone can allowed to download and access the code to fix bugs and develop customized packages. YUM uses numerous third party repositories to install packages automatically by resolving their dependencies issues.

1. Install a Package with YUM

To install a package called Firefox 14, just run the below command it will automatically find and install all required dependencies for Firefox.

# yum install firefox
Loaded plugins: fastestmirror
Dependencies Resolved

================================================================================================
Package Arch Version Repository Size
================================================================================================
Updating:
firefox i686 10.0.6-1.el6.centos updates 20 M
Updating for dependencies:
xulrunner i686 10.0.6-1.el6.centos updates 12 M

Transaction Summary
================================================================================================
Install 0 Package(s)
Upgrade 2 Package(s)

Total download size: 32 M
Is this ok [y/N]: y
Downloading Packages:
(1/2): firefox-10.0.6-1.el6.centos.i686.rpm | 20 MB 01:10
(2/2): xulrunner-10.0.6-1.el6.centos.i686.rpm | 12 MB 00:52
------------------------------------------------------------------------------------------------
Total 63 kB/s | 32 MB 02:04

Updated:
firefox.i686 0:10.0.6-1.el6.centos

Dependency Updated:
xulrunner.i686 0:10.0.6-1.el6.centos

Complete!

The above command will ask confirmation before installing any package on your system. If you want to install packages automatically without asking any confirmation, use option -y as shown in below example.

# yum -y install firefox

2. Removing a Package with YUM

To remove a package completely with their all dependencies, just run the following command as shown below.

# yum remove firefox
Loaded plugins: fastestmirror
Setting up Remove Process
Resolving Dependencies
--> Running transaction check
---> Package firefox.i686 0:10.0.6-1.el6.centos set to be erased
--> Finished Dependency Resolution

Dependencies Resolved

====================================================================================================
 Package                    Arch        Version                        Repository            Size        
====================================================================================================
Removing:
 firefox                    i686        10.0.6-1.el6.centos            @updates              23 M

Transaction Summary
====================================================================================================
Remove        1 Package(s)
Reinstall     0 Package(s)
Downgrade     0 Package(s)

Is this ok [y/N]: y
Downloading Packages:
Running rpm_check_debug
Running Transaction Test
Transaction Test Succeeded
Running Transaction
  Erasing        : firefox-10.0.6-1.el6.centos.i686                                                                                                                          1/1

Removed:
  firefox.i686 0:10.0.6-1.el6.centos

Complete!

Same way the above command will ask confirmation before removing a package. To disable confirmation prompt just add option -y as shown in below.

# yum -y remove firefox

3. Updating a Package using YUM

Let’s say you have outdated version of MySQL package and you want to update it to the latest stable version. Just run the following command it will automatically resolves all dependencies issues and install them.

# yum update mysql
Loaded plugins: fastestmirror
Dependencies Resolved

============================================================================================================
Package Arch Version Repository Size
============================================================================================================
Updating:
vsftpd i386 2.0.5-24.el5_8.1 updates 144 k

Transaction Summary
============================================================================================================
Install 0 Package(s)
Upgrade 1 Package(s)

Total size: 144 k
Is this ok [y/N]: y
Downloading Packages:
Running rpm_check_debug
Running Transaction Test
Finished Transaction Test
Transaction Test Succeeded
Running Transaction
Updating : vsftpd 1/2
Cleanup : vsftpd 2/2

Updated:
vsftpd.i386 0:2.0.5-24.el5_8.1

Complete!

4. List a Package using YUM

Use the list function to search for the specific package with name. For example to search for a package called openssh, use the command.

# yum list openssh
Loaded plugins: fastestmirror
Loading mirror speeds from cached hostfile
* base: mirror.neu.edu.cn
* epel: mirror.neu.edu.cn
* extras: mirror.neu.edu.cn
* rpmforge: mirror.nl.leaseweb.net
* updates: mirror.nus.edu.sg
Installed Packages
openssh.i386 4.3p2-72.el5_6.3 installed
Available Packages 4.3p2-82.el5 base

To make your search more accurate, define package name with their version, in case you know. For example to search for a specific version openssh-4.3p2 of the package, use the command.

# yum list openssh-4.3p2

5. Search for a Package using YUM

If you don’t remember the exact name of the package, then use search function to search all the available packages to match the name of the package you specified. For example, to search all the packages that matches the word .

# yum search vsftpd
Loaded plugins: fastestmirror
Loading mirror speeds from cached hostfile
* base: mirror.neu.edu.cn
* epel: mirror.neu.edu.cn
* extras: mirror.neu.edu.cn
* rpmforge: mirror.nl.leaseweb.net
* updates: ftp.iitm.ac.in
============================== Matched: vsftpd ========================
ccze.i386 : A robust log colorizer
pure-ftpd-selinux.i386 : SELinux support for Pure-FTPD
vsftpd.i386 : vsftpd - Very Secure Ftp Daemon

6. Get Information of a Package using YUM

Say you would like to know information of a package before installing it. To get information of a package just issue the below command.

# yum info firefox
Loaded plugins: fastestmirror
Loading mirror speeds from cached hostfile
* base: mirror.neu.edu.cn
* epel: mirror.neu.edu.cn
* extras: mirror.neu.edu.cn
* rpmforge: mirror.nl.leaseweb.net
* updates: ftp.iitm.ac.in
Available Packages
Name : firefox
Arch : i386
Version : 10.0.6
Release : 1.el5.centos
Size : 20 M
Repo : updates
Summary : Mozilla Firefox Web browser
URL : http://www.mozilla.org/projects/firefox/
License : MPLv1.1 or GPLv2+ or LGPLv2+
Description: Mozilla Firefox is an open-source web browser, designed for standards
: compliance, performance and portability.

7. List all Available Packages using YUM

To list all the available packages in the Yum database, use the below command.

# yum list | less

8. List all Installed Packages using YUM

To list all the installed packages on a system, just issue below command, it will display all the installed packages.

# yum list installed | less

9. Yum Provides Function

Yum provides function is used to find which package a specific file belongs to. For example, if you would like to know the name of the package that has the /etc/httpd/conf/httpd.conf.

# yum provides /etc/httpd/conf/httpd.conf
Loaded plugins: fastestmirror
httpd-2.2.3-63.el5.centos.i386 : Apache HTTP Server
Repo : base
Matched from:
Filename : /etc/httpd/conf/httpd.conf

httpd-2.2.3-63.el5.centos.1.i386 : Apache HTTP Server
Repo : updates
Matched from:
Filename : /etc/httpd/conf/httpd.conf

httpd-2.2.3-65.el5.centos.i386 : Apache HTTP Server
Repo : updates
Matched from:
Filename : /etc/httpd/conf/httpd.conf

httpd-2.2.3-53.el5.centos.1.i386 : Apache HTTP Server
Repo : installed
Matched from:
Other : Provides-match: /etc/httpd/conf/httpd.conf

10. Check for Available Updates using Yum

To find how many of installed packages on your system have updates available, to check use the following command.

# yum check-update

11. Update System using Yum

To keep your system up-to-date with all security and binary package updates, run the following command. It will install all latest patches and security updates to your system.

# yum update

12. List all available Group Packages

In Linux, number of packages are bundled to particular group. Instead of installing individual packages with yum, you can install particular group that will install all the related packages that belongs to the group. For example to list all the available groups, just issue following command.

# yum grouplist
Installed Groups:
Administration Tools
DNS Name Server
Dialup Networking Support
Editors
Engineering and Scientific
FTP Server
Graphics
Java Development
Legacy Network Server
Available Groups:
Authoring and Publishing
Base
Beagle
Cluster Storage
Clustering
Development Libraries
Development Tools
Eclipse
Educational Software
KDE (K Desktop Environment)
KDE Software Development

13. Install a Group Packages

To install a particular package group, we use option as groupinstall. Fore example, to install “MySQL Database“, just execute the below command.

# yum groupinstall 'MySQL Database'
Dependencies Resolved

=================================================================================================
Package Arch Version Repository Size
=================================================================================================
Updating:
unixODBC i386 2.2.11-10.el5 base 290 k
Installing for dependencies:
unixODBC-libs i386 2.2.11-10.el5 base 551 k

Transaction Summary
=================================================================================================
Install 1 Package(s)
Upgrade 1 Package(s)

Total size: 841 k
Is this ok [y/N]: y
Downloading Packages:
Running rpm_check_debug
Running Transaction Test
Finished Transaction Test
Transaction Test Succeeded
Running Transaction
Installing : unixODBC-libs 1/3
Updating : unixODBC 2/3
Cleanup : unixODBC 3/3

Dependency Installed:
unixODBC-libs.i386 0:2.2.11-10.el5

Updated:
unixODBC.i386 0:2.2.11-10.el5

Complete!

14. Update a Group Packages

To update any existing installed group packages, just run the following command as shown below.

# yum groupupdate 'DNS Name Server'

Dependencies Resolved
================================================================================================================
Package Arch Version Repository Size
================================================================================================================
Updating:
bind i386 30:9.3.6-20.P1.el5_8.2 updates 981 k
bind-chroot i386 30:9.3.6-20.P1.el5_8.2 updates 47 k
Updating for dependencies:
bind-libs i386 30:9.3.6-20.P1.el5_8.2 updates 864 k
bind-utils i386 30:9.3.6-20.P1.el5_8.2 updates 174 k

Transaction Summary
================================================================================================================
Install 0 Package(s)
Upgrade 4 Package(s)

Total size: 2.0 M
Is this ok [y/N]: y
Downloading Packages:
Running rpm_check_debug
Running Transaction Test
Finished Transaction Test
Transaction Test Succeeded
Running Transaction
Updating : bind-libs 1/8
Updating : bind 2/8
Updating : bind-chroot 3/8
Updating : bind-utils 4/8
Cleanup : bind 5/8
Cleanup : bind-chroot 6/8
Cleanup : bind-utils 7/8
Cleanup : bind-libs 8/8

Updated:
bind.i386 30:9.3.6-20.P1.el5_8.2 bind-chroot.i386 30:9.3.6-20.P1.el5_8.2

Dependency Updated:
bind-libs.i386 30:9.3.6-20.P1.el5_8.2 bind-utils.i386 30:9.3.6-20.P1.el5_8.2

Complete!

15. Remove a Group Packages

To delete or remove any existing installed group from the system, just use below command.

# yum groupremove 'DNS Name Server'

Dependencies Resolved

===========================================================================================================
Package Arch Version Repository Size
===========================================================================================================
Removing:
bind i386 30:9.3.6-20.P1.el5_8.2 installed 2.1 M
bind-chroot i386 30:9.3.6-20.P1.el5_8.2 installed 0.0

Transaction Summary
===========================================================================================================
Remove 2 Package(s)
Reinstall 0 Package(s)
Downgrade 0 Package(s)

Is this ok [y/N]: y
Downloading Packages:
Running rpm_check_debug
Running Transaction Test
Finished Transaction Test
Transaction Test Succeeded
Running Transaction
Erasing : bind 1/2
warning: /etc/sysconfig/named saved as /etc/sysconfig/named.rpmsave
Erasing : bind-chroot 2/2

Removed:
bind.i386 30:9.3.6-20.P1.el5_8.2 bind-chroot.i386 30:9.3.6-20.P1.el5_8.2

Complete!

16. List Enabled Yum Repositories

To list all enabled Yum repositories in your system, use following option.

# yum repolist

repo id repo name status
base CentOS-5 - Base enabled: 2,725
epel Extra Packages for Enterprise Linux 5 - i386 enabled: 5,783
extras CentOS-5 - Extras enabled: 282
mod-pagespeed mod-pagespeed enabled: 1
rpmforge RHEL 5 - RPMforge.net - dag enabled: 11,290
updates CentOS-5 - Updates enabled: 743
repolist: 20,824

16.2 List all Enabled and Disabled Yum Repositories

The following command will display all enabled and disabled yum repositories on the system.

# yum repolist all

repo id repo name status
C5.0-base CentOS-5.0 - Base disabled
C5.0-centosplus CentOS-5.0 - Plus disabled
C5.0-extras CentOS-5.0 - Extras disabled
base CentOS-5 - Base enabled: 2,725
epel Extra Packages for Enterprise Linux 5 - i386 enabled: 5,783
extras CentOS-5 - Extras enabled: 282
repolist: 20,824

17. Install a Package from Specific Repository

To install a particular package from a specific enabled or disabled repository, you must use –enablerepo option in your yum command. For example to Install PhpMyAdmin 3.5.2 package, just execute the command.

# yum --enablerepo=epel install phpmyadmin

Dependencies Resolved
=============================================================================================
Package Arch Version Repository Size
=============================================================================================
Installing:
phpMyAdmin noarch 3.5.1-1.el6 epel 4.2 M

Transaction Summary
=============================================================================================
Install 1 Package(s)

Total download size: 4.2 M
Installed size: 17 M
Is this ok [y/N]: y
Downloading Packages:
phpMyAdmin-3.5.1-1.el6.noarch.rpm | 4.2 MB 00:25
Running rpm_check_debug
Running Transaction Test
Transaction Test Succeeded
Running Transaction
Installing : phpMyAdmin-3.5.1-1.el6.noarch 1/1
Verifying : phpMyAdmin-3.5.1-1.el6.noarch 1/1

Installed:
phpMyAdmin.noarch 0:3.5.1-1.el6

Complete!

18. Interactive Yum Shell

Yum utility provides a custom shell where you can execute multiple commands.

# yum shell
Loaded plugins: fastestmirror
Setting up Yum Shell
> update httpd
Loading mirror speeds from cached hostfile
 * base: mirrors.sin3.sg.voxel.net
 * epel: ftp.riken.jp
 * extras: mirrors.sin3.sg.voxel.net
 * updates: mirrors.sin3.sg.voxel.net
Setting up Update Process
>

19. Clean Yum Cache

By default yum keeps all the repository enabled package data in /var/cache/yum/ with each sub-directory, to clean all cached files from enabled repository, you need to run the following command regularly to clean up all the cache and make sure that there is nothing unnecessary space is using. We don’t want to give the output of the below command, because we like to keep cached data as it is.

# yum clean all

20. View History of Yum

To view all the past transactions of yum command, just use the following command.

# yum history

Loaded plugins: fastestmirror
ID | Login user | Date and time | Action(s) | Altered
-------------------------------------------------------------------------------
10 | root | 2012-08-11 15:19 | Install | 3
9 | root | 2012-08-11 15:11 | Install | 1
8 | root | 2012-08-11 15:10 | Erase | 1 EE
7 | root | 2012-08-10 17:44 | Install | 1
6 | root | 2012-08-10 12:19 | Install | 2
5 | root | 2012-08-10 12:14 | Install | 3
4 | root | 2012-08-10 12:12 | I, U | 13 E< 3 | root | 2012-08-09 13:01 | Install | 1 >
2 | root | 2012-08-08 20:13 | I, U | 292 EE
1 | System | 2012-08-08 17:15 | Install | 560
history list

We have tried to cover all the basic to advance yum commands with their examples. If anything related to yum commands may have missed out. Please update us through our comment box. So, we keep updating the same based on feedback’s received.

Apache Virtual Hosting: IP Based and Name Based Virtual Hosts


Creating Virtual Host on Linux Based Systems


Original/Source

Apache Virtual Hosting in Linux

Concept of Shared web hosting and Reseller web hosting is based on this facility of Apache only.

Types of Virtual Host

There are two types of virtual hosting is available with Apache.

Name Based Virtual Hosting

With the name based virtual hosting you can host several domains/websites on a single machine with a single IP. All domains on that server will be sharing a single IP. It’s easier to configure than IP based virtual hosting, you only need to configure DNS of the domain to map it with its correct IP address and then configure Apache to recognize it with the domain names.

Name Based Virtual Hosting

IP Based Virtual Hosting

With the IP based virtual hosting, you can assign a separate IP for each domain on a single server, these IP’s can be attached to the server with single NIC cards and as well as multiple NICs.

IP Based Virtual Hosting

Lets set up Name Based Virtual Hosting and IP based Virtual hosting in RHEL, CentOS and Fedora.

Testing Environment
  1. OSCentOS 6.5
  2. ApplicationApache Web Server
  3. IP Address192.168.0.100
  4. IP Address192.168.0.101
  5. Domainwww.example1.com
  6. Domainwww.example2.com

How to Setup IP Based and Name Based Apache Virtual Hosts

Before setting up virtual hosting with Apache, your system must have Apache Web software installed. if not, install it using default package installer called yum.

[root@celerium ~]# yum install httpd

Setup Name Based Virtual Host

But, before creating a virtual host, you need to create a directory where you will keep all your website’s files. So, create directories for these two virtual hosts under /var/www/html folder. Please remember /var/www/html will be your default Document Root in the Apache virtual configuration.

[root@celerium ~]# mkdir /var/www/html/example1.com/
[root@celerium ~]# mkdir /var/www/html/example2.com/

To set up Name based virtual hosting you must need to tell Apache to which IP you will be using to receive the Apache requests for all the websites or domain names. We can do this with NameVirtualHost directive. Open Apache main configuration file with VI editor.

[root@celerium ~]# vi /etc/httpd/conf/httpd.conf

Search for NameVirtualHost and uncomment this line by removing the # sign in front of it.

NameVirtualHost

Next add the IP with possible in which you want to receive Apache requests. After the changes, your file should look like this:

NameVirtualHost 192.168.0.100:80

Now, it’s time to setup Virtual host sections for your domains, move to the bottom of the file by pressing Shift + G. Here in this example, We are setting up virtual host sections for two domains

  1. www.example1.com
  2. www.example2.com

Add the following two virtual directives at the bottom of the file. Save and close the file.

    ServerAdmin webmaster@example1.com
    DocumentRoot /var/www/html/example1.com
    ServerName www.example1.com
ErrorLog logs/www.example1.com-error_log
CustomLog logs/www.example1.com-access_log common



    ServerAdmin webmaster@example2.com
    DocumentRoot /var/www/html/example2.com
    ServerName www.example2.com
ErrorLog logs/www.example2.com-error_log
CustomLog logs/www.example2.com-access_log common

You are free to add as many directives you want to add in your domains virtual host section. When you are done with changes in httpd.conf file, please check the syntax of files with following command.

[root@celerium ~]# httpd -t

Syntax OK

It is recommended to check the syntax of the file after making some changes and before restarting the Web server because if any syntax goes wrong Apache will refuse to work with some errors and eventually affect your existing web server go down for a while. If syntax is OK. Please restart your Web server and add it to chkconfig to make your web server start in runlevel 3 and 5 at the boot time only.

[root@celerium ~]# service httpd restart
Stopping httpd:                                            [  OK  ]
Starting httpd:                                            [  OK  ]
[root@celerium ~]# chkconfig --level 35 httpd on

Now it’s time to create a test page called index.html add some content to the file so we will have something to check it, when the IP calls the virtual host.

[root@celerium ~]# vi /var/www/html/example1.com/index.html

Hello, Welcome to www.example1.com.

[root@celerium ~]# vi /var/www/html/example2.com/index.html

Hello, Welcome to www.example2.com.

Once you’re done with it, you can test the setup by accessing both the domains in a browser.

http://www.example1.com

http://www.example2.com
Preview: www.example1.com

Virtual Hosting: www.example1.com

Preview: www.example2.com

Virtual Hosting: www.example2.com

Setup IP Based Virtual Hosting Linux

To setup IP based virtual hosting, you must have more than one IP address/Port assigned to your server or your Linux machine.

It can be on a single NIC card , For example: eth0:1, eth0:2, eth0:3 … so forth. Multiple NIC cards can also be attached. If you don’t know how to create multiple IP’s on single NIC, follow the below guide, that will help you out in creating.

  1. Create Multiple IP Addresses to One Single Network Interface

Purpose of implementing IP based virtual hosting is to assign implementing for each domain and that particular IP will not be used by any other domain.

This kind of set up required when a website is running with SSL certificate (mod_ssl) or on different ports and IPs. And You can also run multiple instances of Apache on a single machine. To check the IPs attached in your server, please check it using ifconfig command.

root@celerium ~]# ifconfig
Sample Output
 
eth0      Link encap:Ethernet  HWaddr 08:00:27:4C:EB:CE  
          inet addr:192.168.0.100  Bcast:192.168.0.255  Mask:255.255.255.0
          inet6 addr: fe80::a00:27ff:fe4c:ebce/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:17550 errors:0 dropped:0 overruns:0 frame:0
          TX packets:15120 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000
          RX bytes:16565983 (15.7 MiB)  TX bytes:2409604 (2.2 MiB)

eth0:1    Link encap:Ethernet  HWaddr 08:00:27:4C:EB:CE  
          inet addr:192.168.0.101  Bcast:192.168.0.255  Mask:255.255.255.0
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1

lo        Link encap:Local Loopback  
          inet addr:127.0.0.1  Mask:255.0.0.0
          inet6 addr: ::1/128 Scope:Host
          UP LOOPBACK RUNNING  MTU:16436  Metric:1
          RX packets:1775 errors:0 dropped:0 overruns:0 frame:0
          TX packets:1775 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:0
          RX bytes:3416104 (3.2 MiB)  TX bytes:3416104 (3.2 MiB)

As you can see in above output, two IPs 192.168.0.100 (eth0) and 192.168.0.101 (eth0:1) is attached to the server, both IPs are assigned to the same physical network device (eth0).

Now, assign a specific IP/Port to receive http requests, you can simply do it by changing Listen directive in httpd.conf file.

[root@celerium ~]# vi /etc/httpd/conf/httpd.conf

Search for word “Listen”, You find a section where the short description about Listen directive is written. In that section, comment the original line and write your own directive below that line.

# Listen 80

Listen 192.168.0.100:80

Now,  create a Virtual host sections for both the domains. Go the bottom of the file and add the following virtual directives.

VirtualHost 192.168.0.100:80>
    ServerAdmin webmaster@example1.com
    DocumentRoot /var/www/html/example1
    ServerName www.example1.com
ErrorLog logs/www.example1.com-error_log
TransferLog logs/www.example1.com-access_log



    ServerAdmin webmaster@example2.com
    DocumentRoot /var/www/html/example2
    ServerName www.example2.com
ErrorLog logs/www.example2.com-error_log
TransferLog logs/www.example2.com-access_log

Now, since you have modified main Apache conf file, you need to restart the http service like below.

[root@celerium ~]# service httpd restart
Stopping httpd:                                            [  OK  ]
Starting httpd:                                            [  OK  ]

Test your IP based Virtual hosting setup by accessing the URLs on web browser as shown below.

http://www.example1.com

http://www.example2.com

That’s all with Apache virtual host today, If you’re looking to secure and harden your Apache configuration, then read our article that guides.

  1. 13 Apache Web Server Security and Hardening Tips

Reference Links

Apache Virtual Host Documentation

I’ll be again come with some other Apache tips and trick in my future articles, till then Stay Geeky and connected to Tecmint.com. Do not forget to leave your suggestions about the article in our comment section below.

Beer Tempature Monitering with Raspberry Pi

BEER MONITORING WITH MY RASPBERRY PI

The secret to brewing great beer at home is making sure that you keep it at the right temperature. This can be tricky when your house doesn’t have a thermostat and you’re not in the house for most of the day. However, by using a cheap and cheerful sensor with a raspberry pi, you can record a log of the temperature and check it over the internet to make sure your beer is brewing nicely.

Hardware

The sensor I used is the DHT11 which, at the time of writing, you can order on eBay for £1.12 delivered. It has a digital interface, so you don’t need to do any calibration or digital conversion as you would with a thermistor. To connect the sensor to the RPi, all you need is a 10k resistor to pull-up the data signal and to make the following connections (see pic).Raspberry Pi Beer Interface

RPi VCC (pin 1) -> DHT11 pin 1

RPi GPIO4 (pin 7) -> DHT11 pin 2

RPi GND (pin 6) -> DHT11 pin 4

 

Interfacing

The DHT11 uses its own serial interface, which can be interrogated using the wiringPi C library. To install and compile the library, use the following commands:

sudo apt-get install git-core build-essential

git clone git://git.drogon.net/wiringPi

cd wiringPi

./build

This blog post details the code necessary to read the sensor data. The code below has been modified to return only the current temperature and to repeat the request if there is an error. Place the following into a file named dht11.c.

#include <wiringPi.h>

#include <stdio.h>

#include <stdlib.h>

#include <stdint.h>

#define MAX_TIME 85

#define DHT11PIN 7

#define ATTEMPTS 5

int dht11_val[5]={0,0,0,0,0};

int dht11_read_val()

{

uint8_t lststate=HIGH;

uint8_t counter=0;

uint8_t j=0,i;

for(i=0;i<5;i++)

dht11_val[i]=0;

pinMode(DHT11PIN,OUTPUT);

digitalWrite(DHT11PIN,LOW);

delay(18);

digitalWrite(DHT11PIN,HIGH);

delayMicroseconds(40);

pinMode(DHT11PIN,INPUT);

for(i=0;i<MAX_TIME;i++)

{

counter=0;

while(digitalRead(DHT11PIN)==lststate){

counter++;

delayMicroseconds(1);

if(counter==255)

break;

}

lststate=digitalRead(DHT11PIN);

if(counter==255)

break;

// top 3 transistions are ignored

if((i>=4)&&(i%2==0)){

dht11_val[j/8]<<=1;

if(counter>16)

dht11_val[j/8]|=1;

j++;

}

}

// verify checksum and print the verified data

if((j>=40)&&(dht11_val[4]==((dht11_val[0]+dht11_val[1]+dht11_val[2]+dht11_val[3])& 0xFF)))

{

printf("%d.%d,%d.%d\n",dht11_val[0],dht11_val[1],dht11_val[2],dht11_val[3]);

return 1;

}

else

return 0;

}

int main(void)

{

int attempts=ATTEMPTS;

if(wiringPiSetup()==-1)

exit(1);

while(attempts)

{

int success = dht11_read_val();

if (success) {

break;

}

attempts--;

delay(500);

}

return 0;

}

Compile and execute the source code with the following commands:

gcc -o dht11 dht11.c -L/usr/local/lib -lwiringPi

sudo ./dht11

The program should return two numbers – one for relative humidity and the other for temperature.

Logging

The simplest method of creating a log of the temp/humidity is to use a cronjob. The program must be run as root, so use the following command to edit the cron config file:

sudo crontab -e

Add the following line to the end. It will save a timestamp and the temp/humidity every minute to temp.log.

* * * * * echo `date +\%Y\%m\%d\%H\%M\%S`,`/home/pi/wiringPi/dht11` >> /home/pi/temp.log

If that doesn’t seem to be working, the system cron may not be running. The following command will start it, and the line after will make sure it starts every time the RPi turns on:

sudo service cron start

sudo update-rc.d cron defaults

Display

Reading a log file isn’t the easiest way to check how the temp/humidity is changing, but we can use a graphing library to read the log file and plot it. For this, I used DyGraph which is a Javascript library for plotting time-based information. Here is the final .html file I used:

You can set this up on the RPi by installing a web server like Apache, creating a symlink to the log file, downloading dygraph and saving the above html file as /var/www/temp.html.

sudo apt-get install apache2

ln -s /home/pi/temp.log /var/www/temp.log

wget -P /var/www http://dygraphs.com/dygraph-combined.js

Then use your browser to navigate to 192.168.1.2/temp.html, replacing the IP address with that of your RPi. To be able to access the page from the internet, you’ll have to set up NAT on your router.
Beer-Graph


cropped-logo3.png


OverClocking the Raspberry Pi

How to OverClock a Raspberry Pi Model B

 

The makers of the Pi have very conveniently created a file called config.txt located in the /boot directory. In this file you can set all kinds of settings, such as forcing HDMI, resolution, and yes, clock frequencies and voltages. Now, there are two things you can do. One is simply overclocking and leaving the voltages as they are, and the other is to also overvolt (increase the voltage to the chips) which results is more heat generated (shouldn’t be much of an issue), shorter lifespan  and a guaranteed voiding of warranty. Once you have tried overvolting just once a flag is set and your warranty is void forever. The upside to overvolting is, of course, that you can generally squeeze just a little bit more out of the chips increasing the frequencies, but some have reported not much higher frequencies even with overvolting compared to simply overclocking. It’s up to you if it’s worth voiding the warranty.

Its also go to note that you can do all of this via a graphical interface (except overvolting) but I wanted to see how the config.txt file worked.

Section 1.0: Overclocking

There are seven different frequencies you can change, here’s a list of them (and their default values in MHz):

  • arm_freq = 700 # frequency of the ARM processor
  • sdram_freq = 400 # frequency of the SDRAM memory
  • gpu_freq = 250 # sets all the following values related to the GPU (graphics processor):
  • core_freq = 250 # frequency of the GPU core
  • h264_freq = 250 # frequency of the hardware video block
  • isp_freq = 250 # frequency of image sensor pipeline block
  • v3d_freq = 250 # frequency of 3D block

You will want all the GPU frequencies to be the same or integer multiples. That means if you change core_freq to 400 you will want to change h264_freq, isp_freq and v3d_freq to either 200 or 400 as well.

To change the frequencies edit (or create if it doesn’t exist) /boot/config.txt and add one or more of the above lines (without the # comments) and reboot. Your Pi will now run at the new frequency. As I mentioned before results vary between chips but squeezing it up to 800 for arm_freq, 450 for sdram_freq and 300 for gpu_freq seems to be a good starting point that most chips can reach without difficulty. From there you can increase the different values incrementally until you hit your limit (resulting in crashes and kernel panics and general stability issues).

Section 2.0: Overvolting

Again, overvolting will irreversibly void your warranty. Proceed at your own risk. The two values (maybe exclusively the first) you may want to touch are the following:

  • over_voltage = 0 # CPU and GPU voltage, 0 means 1.2V with each positive or negative step representing 0.025V. 1 is 1.2+0.025=1.225V and so on
  • over_voltage_sdram = 0 # voltage for the SDRAM, works just like the previous setting. This, just like gpu_freq, breaks down into three different values, but unless you know what you’re doing I don’t suggest touching this or them. I don’t see much talk about it so I suggest you don’t fiddle with it without further research.

It seems to be a generally bad idea to go over 8 on the over_voltage setting, with most people seemingly settling in at 6.

When you’ve found a nice clock that runs stable I think the community would appreciate you adding your values to the table at the bottom of this page to help future overclockers in their endeavour: http://elinux.org/RP…t#Tested_values

Thank you


 cropped-logo3.png