Mezgani blog

February 12, 2013

Installing smog mongodb viewer

Filed under: linux, system — Tags: , — Ali MEZGANI @ 2:02 am

First of all install dependency packages
sudo apt-get update && apt-get install git-core curl build-essential openssl libssl-dev

Install Node.js & NPM
git clone https://github.com/joyent/node.git
cd node

Run git tag to show all available versions
git tag -l

select the latest stable.
git checkout v0.9.9

Run configure and make
./configure
make
sudo make install

Get npm Node package manager using curl
curl https://npmjs.org/install.sh | sudo sh

Install smog using node package manager by running
npm install smog -g

Start smog on background:
smog&

smog will start on default port 8080

February 11, 2013

How to create an Apache Module

Filed under: linux, system — Tags: , , , — Ali MEZGANI @ 8:49 pm

1. Use apxs2 to create a skeleton module named mod_hello:
apxs2 -g -n hello

2. Modify the automatically generated mod_hello.c file:
3. Run make and install the .so file into Apache’s libexec directory
apxs2 -iac mod_hello.c
4. Modify httpd.conf to load the module and to install it as the content handler for the URL of your choice:

# httpd.conf
LoadModule hello_module libexec/mod_hello.so

<Location /hello_demo>
SetHandler hello
</Location>

February 8, 2013

How to deploy PHP/MySQL web application with several external dependancies, across multiple Linux platforms

If you would create a deployment system for PHP/MySQL web application with several external dependancies, across multiple *nix platforms usually you can use rsync or may be scp, git, and pear for dependencies and some custom scripts.

In the fact, there are a nice solution and interesting one based on three tools : capistrano, jenkins and composer

Capistrano to deploy project to remote servers and be able to rollback when screw up.
Capistrano is a nice ruby application that can perform pre and post-deploy functions like restarting webserver, busting cache, renaming files, running database migrations, with capistrano we can easily copy code from source ( control repository ) to production server.

Capistrano by itself isn’t enough to make my deployment complete, that why my capistrano script will runs composer on the app to gather dependencies.

First , you can get capistrano using gem like that:
sudo gem install capistrano
sudo gem install capistrano-ext

You may get composer using git like this, run :
git clone https://github.com/composer/composer.git

In general, you’ll use Capistrano as follows:

You will create a recipe file (“capfile” or “Capfile”) usgin capify command line as follow :
capify .
This will create config directory and a deploy.rb file that we will edit
vim confing/deploy.rb

deploy.rb is ruby file with a very simple syntax, here is my recipe file that i use to deploy my blog:



set :application, "blog"
#You probably want to change this to be the location of the repo you just forked
set :repository,  "git://github.com/WordPress/WordPress.git"

set :php_bin, "/usr/bin/php"

#The following is not the document root, but just the app root 
set :deploy_to, "/home/mezgani/www/#{application}/"

set :current, "/home/mezgani/www/#{application}/current"

role :web, "server1", "server2"                          # Your HTTP server, Apache/etc
role :app, "server1", "server2"                          # This may be the same as your `Web` server
role :db,  "database-server", :primary => true # This is where Rails migrations will run
role :db,  "database-server"

set :local_path, "/home/mezgani/config/wordpress/config"

# SSH Settings
set :user, "mezgani"
#set :password, "password"
ssh_options[:keys] = %w(/home/user/.ssh/id_rsa) # SSH key
ssh_options[:port] = 22

#########################
#things you'll probably not change, unless you know what you're doing 
###########################
# If you aren't using Subversion to manage your source code, specify
# your SCM below:
# set :scm, :subversion
set :scm, :git

#the following is needed because if it's not there, for some reason we don't get
#asked to accept the key from github..annoying when deploying to a new server
default_run_options[:pty] = true

#since this is PHP, we don't really need to restart apache or anything
set :use_sudo, true 

#ssh agent forwarding..
ssh_options[:forward_agent] = true

#A lot of this stuff has been overridden for PHP/Non Rails magic

namespace :deploy do
  
  task :default do
    update
    finalize_update
    composer
  end
  
  
  task :finalize_update, :except => { :no_release => true } do
    run "chmod -R g+w #{latest_release}" if fetch(:group_writable, true)
    run "cp -fr #{current}/wp-content #{shared_path}/"
    run "cp #{current}/.htaccess #{shared_path}/"
    run "cp #{current}/wp-config.php #{shared_path}/configs/"
    run "cp #{shared_path}/configs/wp-config.php #{latest_release}/"
    run "cp -fr #{shared_path}/wp-content #{latest_release}/"
    run "chmod -R 777 #{latest_release}/wp-content"
    run "cp #{shared_path}/.htaccess #{latest_release}/"
  end
end 

task :composer do
  top.upload("#{local_path}/composer.json", "#{shared_path}/install", {:via => :scp, :recursive => true})
  run "cd #{shared_path}/install && curl -s http://getcomposer.org/installer | #{php_bin}"
  run "cd #{shared_path}/install && ./composer.phar install"
end

task :setup do
  run "sudo apt-get install curl"
  run "mkdir #{shared_path}/"
  run "mkdir #{shared_path}/install/"
  run "mkdir #{shared_path}/configs/"
  
  set(:wp_environment_ready, Capistrano::CLI.ui.ask("Is wp-config.php ready for this environment? (yes/no): "))
  if wp_environment_ready == 'yes'
    #top.upload("htdocs/wp-config.php", "#{shared_path}/configs/wp-config.php", :via => :scp)
    run "cp #{deploy_to}/wp-config.php #{shared_path}/configs/wp-config.php "
  end
  run "mkdir #{shared_path}/wp-content"
  run "mkdir #{shared_path}/wp-content/uploads"
end

Before deploy we have to define a composer.json file that defines all
the dependencies my application has, whether they’re composer enabled or not.

Edit composer.json, specify your dependencies and run composer on capistrano to get the dependencies:
vim composer.json

Finally, use the cap script to execute your recipe. Use the cap script as follows:
cap deploy

June 20, 2012

Upgrade FreeBSD 8.1 to 9.0 stable release

Filed under: system — Tags: — Ali MEZGANI @ 12:54 am

For upgrading my FreeBSD box i use the binary freebsd-update. Well, i logged as root and i type:

# freebsd-update upgrade -r 9.0-RELEASE
# freebsd-update fetch
# freebsd-update install
# reboot

The system will reboot with the new kernel after the reboot, run freebsd-update install again
to install userland components and rebbot

# freebsd-update install
# reboot

You also need to update all packages, type:
# portsnap fetch update
# pkg_version -vIL=
# portupgrade -a

May 16, 2012

Installation of mod_evasive on cPanel/WHM

This article is about installing of apache’s mod_evasive on cpanel/whm, to help against DOS and DDOS attack.

Get the latest source of mod_evasive
$ wget http://www.zdziarski.com/blog/wp-content/uploads/2010/02/mod_evasive_1.10.1.tar.gz
$ tar zxvf mod_evasive_1.10.1.tar.gz
$ cd mod_evasive

Load mod_evasive into apache
$ /usr/local/apache/bin/apxs -i -a -c mod_evasive20.c

Next, distill the module to apache
$ /usr/local/cpanel/bin/apache_conf_distiller –update

Last, edit apache config file
$ vim /usr/local/apache/conf/httpd.conf

and Add this directive

<IfModule mod_evasive20.c>
DOSHashTableSize 3097
DOSPageCount 2
DOSSiteCount 50
DOSPageInterval 1
DOSSiteInterval 1
DOSBlockingPeriod 3600
DOSEmailNotify admin@domain.tld
DOSSystemCommand “sudo /sbin/iptables -A INPUT -s %s -j DROP”
DOSLogDir “/var/log/evasive/”
</IfModule>

January 2, 2011

Sending text message using AT command

Filed under: linux, system, tools — Tags: , , — Ali MEZGANI @ 5:00 pm

Playing with my USB dongle that is a 3g modem, i felt the need to send message using this modem.
but i saw that it has no support to send message using AT command, well to check this use the AT+CSMS command before any shake.

In the case when you have a GSM/GPRS modem/mobile phone with full support of what we talk about before :
You can easily sending message using the great Kannel, or from scratch:
In this article we will focus on how to send message using AT command and we can resume this in five steps :
1. Initializing the modem
2. Setting SMSC
3. Storing the message into storage
4. Sending
5. Delete the message from storage

First of all, to interact with the device you need a serial tools like screen or may be minicom.
Well i recommend the use of screen when you work on pseudo devices :

Let’s connect to the device (ttyUSB0) using screen with a baud of 9600 :
$ screen /dev/ttyUSB0 9600

1. Send the initialize strings :
AT
OK
ATZ
OK

2. Define the service center address as follow and verify that it is correct:
AT+CSCA=”+85290000000″,145

145 means that we deal with formatted address using typical ISDN/telephony numbering plan
(ITU E.164/E.163) and it is an international number.

3. In the fact if you may send a text messages to +85291234567, write the message first to storage area, as like as:
AT+CMGW=”+85291234567″,145,”STO UNSENT”Hello world

4. And finally you can now send the message, referenced with it index:
AT+CMSS=3

You can also do this if you rather to send it to mutli destinations:
AT+CMSS=3,”91234567″
AT+CMSS=3,”97777777″
AT+CMSS=3,”96666666″

Lastly, delete the message from storage area.
5. AT+CMGD=3

To read the first message indexed with 1 :
AT+CMGR=1

Also if you need to play or list all the message in the storage
AT+CMGL=”ALL”


Great document about this can be found here

June 16, 2010

How to send a bit to the parallel port on Linux (2nd part)

Filed under: linux, programming c/c++, system — Tags: , — Ali MEZGANI @ 2:19 am

In this second part of how to send bits to the parallel port on Linux, i describe here basics on how to do the same on kernel space.
Here is a simple linux kernel module, that create a char device named parlport, and you can communicate directly with device using the /dev/parlport

#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/fs.h>
#include <linux/unistd.h>
#include <asm/uaccess.h>
#include <linux/file.h>
#include <asm/io.h>

#define NAME “parlp”
#define VERSION “0.1″
#define LICENSE “GPL”
#define DESCPT “Simple Parallel Port LED driver”
#define AUTHOR “Mezgani Ali\n”\
“mail: mezgani [AT] nativelabs [.] org\n”\
“blog: http://securfox.wordpress.com/&#8221;

#define SUCCESS 0
#define DEVICE_NAME “parlport”
#define BASEPORT 0×0378

static int major = 61; /* major number assigned to our device driver */

static int __init start_module(void);
static void __exit clean_module(void);

static int device_open(struct inode *, struct file *);
static int device_release(struct inode *, struct file *);
static ssize_t device_read(struct file *, char *, size_t, loff_t *);
static ssize_t device_write(struct file *, char *, size_t, loff_t *);

static struct file_operations fops = {
.open = device_open,
.release = device_release,
.read = device_read,
.write = device_write
};

static int
__init start_module(void)
{
int result;

result = register_chrdev(major, DEVICE_NAME, &fops);

if (result < 0) {
printk(KERN_ALERT “Registering device failed with %d\n”, major);
return result;
}

if (!(request_region(BASEPORT, 1, DEVICE_NAME))){
printk(KERN_WARNING “Winbond error request region: %X\n”, BASEPORT);
release_region(BASEPORT, 1);

return result;
}

printk(KERN_INFO “I was assigned major number %d. To talk to\n”, major);
printk(KERN_INFO “the driver, create a dev file with\n”);
printk(KERN_INFO “‘mknod /dev/%s c %d 0′.\n”, DEVICE_NAME, major);

return SUCCESS;
}

static void
__exit clean_module(void)
{
release_region(BASEPORT, 1);

unregister_chrdev(major, DEVICE_NAME);
printk(KERN_ALERT “unregister_chrdev && cleaning module\n”);

}

static int
device_open(struct inode *inode, struct file *file)
{
try_module_get(THIS_MODULE);
return SUCCESS;
}

static int
device_release(struct inode *inode, struct file *file)
{
module_put(THIS_MODULE);
return 0;
}

static ssize_t
device_read(struct file *filp, char *buffer, size_t length, loff_t * offset)
{
unsigned char pbuffer;
int len;

/* input a byte (8 bits) from a port, call inb(port), it returns the byte it got */
pbuffer = inb(BASEPORT);

len = copy_to_user(buffer, &pbuffer, 1);
if (len) return -EFAULT;

if (*offset == 0) {
*offset += 1;
return 1;
} else {
return 0;
}
}

static ssize_t
device_write(struct file *filp, char *buffer, size_t length, loff_t * offset)
{

char pbuffer, *ptr;
int len;

ptr = buffer + length – 1;
len = copy_from_user(&pbuffer, ptr, 1);
if (len) return -EFAULT;

/* output the data to parallel port */
outb(pbuffer, BASEPORT);
return 1;
}

module_init(start_module);
module_exit(clean_module);

MODULE_LICENSE(LICENSE);
MODULE_AUTHOR(AUTHOR);
MODULE_DESCRIPTION(DESCPT);
MODULE_VERSION(VERSION);

Example of use after compilation ;

# insmod parlport.ko
# mknod /dev/parlport c 61 0
# chown 666 /dev/parlport
# echo F > /dev/parlport

June 6, 2010

How to send a bit to the parallel port on Linux

Filed under: linux, nagios, system — Tags: , — Ali MEZGANI @ 5:58 pm

It will be nice idea To do a network monitoring  project with LEDs, the fastest way is to use a Perl module called Device::ParallelPort, this module provides an API to all parallel ports. Device::ParallelPort has a number of drivers for multiple operating systems that includes a direct access module for Linux and the Linux ParPort driver. Work almost on  windows and FresBSD.

In python, there are a  module named pyparallel, and in c in userspace we may use Unix Standard and System Input/Output routines.

Here a simple example that make all LEDS connected to parallel port blinking 5 times.

  #include <stdio.h>
  #include <unistd.h>     /* For sleep(), ioperm(), inb() and outb(). */
  #include <sys/io.h>     /* Perhaps asm/io.h on other systems. */

  /* Address of the first parallel port. found in BIOS settings. */
  #define kDATA_REG (0x0378)          /* Base address = data register. */
  #define kSTAT_REG (DATA_REG + 1)    /* Status register. */
  #define kCONT_REG (DATA_REG + 2)    /* Control register. */

  int main()
  {
      int i;

      if (ioperm(kDATA_REG, 1, 1))    /* Get permission to access this port. */
          {
          printf("ioperm(%x) failed.\nYou must be root to execute!\n", kDATA_REG);
          return 1;
          }

      /* Assume port is already in output mode (bit 5 in control register). */
      for (i = 0; i < 5; i++)        /* Let the LED(s) blink. */
          {
          outb(255, kDATA_REG);       /* All 8 datalines high. */
          sleep(1);
          outb(0, kDATA_REG);         /* All 8 datalines low.  */
          sleep(1);
          }

      return 0;
  }

May 6, 2010

Recording a Sound File

Filed under: debian, linux, system, tools — Tags: , , — Ali MEZGANI @ 1:54 am

To record a simple WAV sample from the microphone and save it to a file called `hello.wav’, install sox and type:
$ rec hello.wav

this command begins an 8,000 Hz, monaural 8-bit WAV recording to the file `hello.wav’, and keeps recording until you interrupt it with C-c.
While the default is to make a low-fidelity recording — 8,000 Hz, monaural 8-bit samples — you can specify that a high-fidelity recording be made.
(But remember that high-fidelity recordings take up much more disk space.)

To make a stereo recording, use the `-c’ option to specify the number of channels, giving 2 as the argument. To make a 16-bit recording, give `w’ (“wide”) as the argument to the `-s’ (“sample size”) option.
Set the recording sample rate by giving the samples per second to use as an argument to the `-r’ option. For CD-quality audio at 44,100Hz, use `-r 44100′.
Finally, to record a file in a particular format, either give the name of the format as an argument to the `-f’ option, or use the traditional file name extension for that format in the output file name (see Sound File Formats).

To make a high-fidelity recording from the microphone and save it to a WAV-format file called `goodbye.wav’, type:
$ rec -s w -c 2 -r 44100 goodbye.wav

(From DSL cookbook)

April 29, 2010

Merge the remote changes before pushing again. “not a fast forward”

Filed under: informational, linux, system, tools — Tags: — Ali MEZGANI @ 3:26 am

When you try to push and you get this message that’s mean that someone else has changed after your last fetch.
Well in this case you have to incorporate their changes before you can add yours typically, you’ll want to rebase rather than merge and you’ll also want to test the joined version.

$ git fetch
$ git diff master…origin/master

that’ll show changes of upstream
$ git fetch origin
$ git rebase origin/master
$ git push prigin master

Older Posts »

Theme: Silver is the New Black. Blog at WordPress.com.

Follow

Get every new post delivered to your Inbox.