Thursday, 24 March 2016

How to install python and configure django on a CentOS 6.7 Linux server with CPanel?

I recently had a chance to play with CentOS 6.7 server. My task was to re-install(reconfigure) run a Django site on it. Actually it was done by my around 2 years before. Then some system admin guy updated the system (especially PHP related stuff), and essentially he screwed up my (ie. I worked tm.) django website. I had lost the track on installing those things. So I would like to share my experience on reaching the point.

First of all I tried to locate the apache config file. My initial thoughts were about this file.
/etc/apache2/apache.conf
I roamed here and there, to get some idea about the system.Here are my commands which I use these sort of tasks.
which httpd
which apache
which apache2
type httpd
locate apache.conf
locate httpd.conf
whatis httpd 
 Sure, You should use man pages to get more info of these commands like which,type and locate. Try `man man` to know what man is.

Anyway, I got some ideas regarding where the conf files lies, especially with the help of locate command

I also had used below command to find CentOS version.
cat /etc/redhat-release

Since, I found some more useful commands from the internet those helped me to get an hint to the problem.  The most useful one in my case was
/etc/init.d/httpd status
This command gave me the hint, the wsgi module was not in the new apache.

Advise

You should use either locate, whatis, type, which etc to get relevant info.
Using file would be nice to check the file exists or not. See
file /path/to/file

Install Python

Now, I checked version of python. It is 2.6.6 in that server. I decided to install Python-2.7 as the site was developed against it.

I did refer this article to get an idea
http://toomuchdata.com/2014/02/16/how-to-install-python-on-centos/

In my case these were the relevant parts.
# install essential dependencies
yum groupinstall "Development tools"
yum install zlib-devel bzip2-devel openssl-devel ncurses-devel  sqlite-devel \
 readline-devel tk-devel gdbm-devel db4-devel libpcap-devel xz-devel

# Python 2.7.6:
wget http://python.org/ftp/python/2.7.6/Python-2.7.6.tar.xz
tar xf Python-2.7.6.tar.xz
cd Python-2.7.6
./configure --prefix=/usr/local --enable-unicode=ucs4 --enable-shared LDFLAGS="-Wl,-rpath /usr/local/lib"
# altinstall make python available on as python2.7,
# leaving existing python,python2,python2.6
# so it won't break anything existing
make && make altinstall

# Install pip
wget https://bitbucket.org/pypa/setuptools/raw/bootstrap/ez_setup.py
python2.7 ez_setup.py
easy_install-2.7 pip

# It's a good idea to install virtualenvwrapper
pip2.7 install virtualenvwrapper

If you are interested in virtualenvwrapper, you must read their docs. It's an excellent doc. See http://virtualenvwrapper.readthedocs.org/en/latest/

Install WSGI

 First of all, I refered this link,
cd ~
wget http://modwsgi.googlecode.com/files/mod_wsgi-3.2.tar.gz
gzip -dc mod_wsgi-3.2.tar.gz | tar xf -
cd mod_wsgi-3.2
./configure --with-apxs=/usr/local/apache/bin/apxs --with-python=/usr/local/bin/python2.7
make && make install 
 

Include the configuration file


After compiling the module, 
I was given the path to where it was located (/usr/lib/httpd/modules/mod_wsgi.so).

I logged in to WHM
WHM -> Server Configuration -> Apache Setup -> Include Editor
to add the following line to load the module
LoadModule wsgi_module /usr/lib/httpd/modules/mod_wsgi.so

Connecting django app

In order to connect django app you have to create an apache conf file in 

mkdir -p /usr/local/apache/conf/userdata/std/2/fcabi/fcabi.net/

The above path may not be same for you. Try ls /usr/local/apache/conf/userdata/std/. It may be 2 or something like 2_2. In my case it was 2_2.

So I used some thing like this
mkdir -p /usr/local/apache/conf/userdata/std/2_2/username/mysite.com>/
In above username was the one I created with CPanel for this site and mysite.com was the address of my site.

Now, create config file
vi /usr/local/apache/conf/userdata/std/2_2/myuser/mysite.net/mysite.conf

ServerAdmin support@mysite.com
Alias /media/ /srv/Test/app/mysite/media/
Alias /static/ /srv/Test/app/mysite/static/
Alias /robots.txt /srv/Test/app/mysite/robots.txt
Alias /favicon.ico /srv/Test/app/mysite/static/images/favicon.ico

CustomLog "|/usr/sbin/rotatelogs /srv/Test/logs/access.log.%Y%m%d-%H%M%S 5M" combined
ErrorLog "|/usr/sbin/rotatelogs /srv/Test/logs/error.log.%Y%m%d-%H%M%S 5M"
LogLevel warn

WSGIDaemonProcess mysite.com user=myuser group=mygroup
WSGIProcessGroup mysite.com
WSGIScriptAlias / /srv/Test/app/conf/apache/mysite.wsgi

<Directory /srv/Test/app/mysite/media>
Order deny,allow
Allow from all
</Directory>

<Directory /srv/Test/app/mysite/static>
Order deny,allow
Allow from all
</Directory>

<Directory /srv/Test/app/conf/apache>
Order deny,allow
Allow from all
</Directory>

On reading through above you get the idea of apache configuration. We specify various things like wsgi file, static directory, media directory etc. You must replace them with your own.

Now create the wsgi file. In my case wsgi was in
/srv/Test/app/conf/apache/mysite.wsgi 

In my case, the wsgi file is almost the same as the one provided by django
ie. the file in mysite/wsgi.py (in settings folder).

But a little modification to include virtualenv settings.

vi /srv/Test/app/conf/apache/mysite.wsgi
#
import os
import sys

# Activate venv
activate_this = '/home/{}/.virtualenvs/mysiteenv/bin/activate_this.py'.format('myuser')
execfile(activate_this, dict(__file__=activate_this))

os.environ['DJANGO_SETTINGS_MODULE'] = 'myproject.settings'

from django.core.wsgi import get_wsgi_application

application = get_wsgi_application()

http://virtualenv.readthedocs.org/en/latest/userguide.html#using-virtualenv-without-bin-python

Look at the two lines after # Activate venv those lines determine the venv.
Since I use virtualenvwrapper.
I usually activate virtualenv  by either
workon mysiteenv
or
source env/bin/activate

Then I type which python which resulsts some thing like ~/.virtualenvs/mysiteenv/python. Now I replace python with activate_this.py. So ~/.virtualenvs/mysiteenv/activate_this.py.

Rebuild the config file and restart apache

It is nice check for syntax errors in apache config file first.
/usr/sbin/apachectl configtest
#or
/usr/sbin/apachectl -t
#or may be even
 
httpd -t
httpd configtest


You can use following commands to rebuild the configuration file.
/usr/local/cpanel/bin/build_apache_con

/usr/sbin/apachectl restart

That's it. I have provided enough information, links and debugging tips. Hope you enjoy it.

Sunday, 4 October 2015

How i changed my keyboard's Space key to Space and Ctrl in Ubuntu 14.04

The thing i wanted was to change my keyboard's behavior like this. When i press Space alone it is Space key. If i pressed with some other key, it is Ctrl.
That is Space+X gives Ctrl+X.

Install needed libs

sudo apt-get install libx11-dev libxtst-dev
Get the source
git clone https://github.com/r0adrunner/Space2Ctrl
Install
cd Space2Ctrl
make
sudo make install

How to use?

Start by typing this in a terminal

s2cctl start

And now Stop by

s2cctl stop

How do i use it?

I added it to ~/.bash_login. So when i login to computer it works.

Reference
https://github.com/r0adrunner/Space2Ctrl

Tuesday, 7 April 2015

How to run android apk in your Google Chrome browser with Google's ARC

Google's plan on merging android with ChromeOS is on the way.



What you need is

1. Google Chrome 41+. It works on PC,Linux,Mac.
Or Chromebook on Chrome Version 41+.
2. You apk files to run
3. The ARC Welder app

1. To get chrome
https://www.google.com/intl/en/chrome/browser/desktop/index.html

In ubuntu/debian you can install *.deb file by


sudo dpkg -i google*.deb 

In fedora/ RedHat Linux 


rpm -ivh google*.rpm

2. To get your apk files
Either use
https://play.google.com/store/apps/details?id=mobi.infolife.appbackup
Or some sites like
http://apps.evozi.com/apk-downloader/

3. Go to The ARC Welder app.And install it from Google Chrome browser.

I used this game (2048) for testing.

http://apps.evozi.com/apk-downloader/?id=com.digiplex.game

This is the result i got.






NB:- There is a limitation. It's is only possible to do one app at time


I tested on Ubuntu 14.04 and Fedora 21.

Reference:-
https://developer.chrome.com/apps/getstarted_arc

Sunday, 22 March 2015

Brython: Python in Browser

Brython is python in browser.

Yes, You can just run it in the browser.

What you need is to get brython.js from their github.

https://raw.githubusercontent.com/brython-dev/brython/master/www/src/brython.js

And put it into some folder of your choice.

Now create a html file and call that js.


<html>
<head>
<script src="brython.js"></script>
</head>
<body onload="brython()">
<script type="text/python">
from browser import document, alert, console

def echo(ev):
    alert(document["zone"].value)

console.log('Hi, this is from python')
document['mybutton'].bind('click',echo)
</script>
<input id="zone"><button id="mybutton">click !</button>
</body>
</html>

Here is piece of code i copied from their website (Infact, modified a little bit).

What is important?
1. including

 <script src="brython.js"></script>

Yes this line, calling/including browser.js file.

3.Body onload function 

<html>

<head>
<script src="brython.js"></script>
</head>

<body onload="brython()">
<script type="text/python" src="test.py"></script>
<input id="zone"><button id="mybutton">click!</button>
</body>

</html>

And here is python code (test.py) i used


from browser import document, alert, console

def echo(ev):
    alert(document["zone"].value)

console.log('Hi, this is from python')
document['mybutton'].bind('click',echo)


Here you can try it online

http://brython.info/tests/console.html

OR Here

http://brython.info/tests/editor.html

Thursday, 10 July 2014

DKIM Signing for postfix mail server Ubuntu Server 12.04


85171738-17ee-4b99-8447-a0f3dae6005e.jpg

DomainKeys Identified Mail (DKIM)

  Lets an organization take responsibility for a message that is in transit. The organization is a handler of the message, either as its originator or as an intermediary. Their reputation is the basis for evaluating whether to trust the message for further handling, such as delivery. Technically DKIM provides a method for validating a domain name identity that is associated with a message through cryptographic authentication.
In essence, it will help you to avoid going your mail into spam. Follow each steps remember to change example.com with your domain.
And selector with your selector(ie, any text).

1.Login to root and install opendkim

sudo su
   sudo apt-get install opendkim opendkim-tools

2.Making directory and generating keys

mkdir /etc/opendkim/
   cd /etc/opendkim
-s means selector so change the word after it we have to chose a selector, here selector
-d means domain so change the word after it as our need,here example.com
opendkim-genkey -s selector -d example.com 

thus two files selector.txt selector.private are created

3.Adding user and making appropriate permissions

To check user a user ‘opendkim’ exists or not
grep opendkim /etc/passwd
Now run this also
chmod 700 /var/run/opendkim
If user is not already there we have to add the user
useradd -r -g opendkim -G mail -s /sbin/nologin -d /var/run/opendkim -c "OpenDKIM" opendkim
Change ownership to opendkim
chown opendkim:opendkim selector.private
To check the ownership of any file use also may use
ls -la /etc/opendkim | grep selector

4.Publishing DNS Record

cat selector.txt
On typing above command, you get a result like  this
selector._domainkey IN TXT "v=DKIM1; k=rsa; p=MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC5N3lnvvrYgPCRSoqn+awTpE+iGYcKBabe8HHbcFfCIIVty76o4PhCoGZSaKVHOjDm4yefKXhQjM7iKzEPuBatE7O47hAx1CJpNuIdLxhILSbEmbMxJrJAG0HZVn8z6EAoOHZNaPHmK2h4UUrjOG8zA5BHfzJf7tGwI+K619fFUwIDAQAB" ; ----- DKIM key mail for example.com
Add TXT record from your hosting websites (for example, digitalocean’s) control panel.  A
selector._domainkey
. In our case, copy
selector._domainkey
in name field copy the text included in “” (including “) to text field from above result. A selector mail is shown in example given below
image
To check the status of dns // or you can use http://dkimcore.org/tools/
dig selector._domainkey.example.com txt  +short 
Test the key with server
opendkim-testkey -d example.com -s selector -k selector.private -vvv

5.Edit the OpenDKIM configuration file


cp /etc/opendkim.conf /etc/opendkim.conf.bk
nano /etc/opendkim.conf
cat /etc/opendkim.conf
On entering above command you can see my configuratoin of opendkim, # is used to comment
# Log to syslog
Syslog         yes
# Required to use local socket with MTAs that access the socket as a non-
# privileged user (e.g. Postfix)
UMask          022
# Sign for example.com with key in /etc/mail/dkim.key using
# selector '2007' (e.g. 2007._domainkey.example.com)
#Domain     example.com
#KeyFile     /etc/opendkim/key1.private 
#Selector     key1
# Commonly-used options; the commented-out versions show the defaults.
Canonicalization     relaxed/simple
Mode             sv #s sign v verify
SubDomains          yes
#ADSPDiscard          no
# Log to syslog
Syslog              yes
SyslogSuccess          yes
LogWhy              yes
# Required to use local socket with MTAs that access the socket as a non-
# privileged user (e.g. Postfix)
UMask              022
UserID              opendkim:opendkim
#
KeyTable          /etc/opendkim/key
SigningTable          refile:/etc/opendkim/sign
ExternalIgnoreList     refile:/etc/opendkim/TrustedHosts
InternalHosts         refile:/etc/opendkim/TrustedHosts
# Hashing Algorithm
SignatureAlgorithm     rsa-sha256
#
Socket             inet:8891@localhost
# Always oversign From (sign using actual From and a null From to prevent
# malicious signatures header fields (From and/or others) between the signer
# and the verifier. From is oversigned by default in the Debian pacakge
# because it is often the identity key used by reputation systems and thus
# somewhat security sensitive.
OversignHeaders      From
# List domains to use for RFC 6541 DKIM Authorized Third-Party Signatures
# (ATPS) (experimental)
PidFile         /var/run/opendkim/opendkim.pid AutoRestart         Yes AutoRestartRate     10/1h #ATPSDomains         example.com #EOF

5.Working with text files (TrustedHosts,SigningTable,KeyTable)

Edit /etc/default/opendkim: Uncomment this row and use port 8891:

SOCKET="inet:8891@localhost" # listen on loopback on port

To allow connection through firewall
 
sudo iptables -A INPUT -i lo -j ACCEPT

Now create a file
 
nano /etc/opendkim/key

 And add the line
 
selector._domainkey.example.com example.com:selector:/etc/opendkim/selector.private

Create another file
 
nano /etc/opendkim/TrustedHosts

And add the following lines
 
127.0.0.1 
localhost 
example.com
*.example.com 
123.123.123.123 #(IP address of your server, if applicable)

Create another file
 
nano /etc/opendkim/sign

And add the following line at end
 
*@example.com selector._domainkey.example.com

Take a backup of postfix configuration file, which may be useful incase any errors.
 
cp /etc/postfix/main.cf /etc/postfix/main.cf.bk

Edit /etc/postfix/main.cf and add the lines to the end

nano /etc/postfix/main.cf
milter_default_action = accept 
milter_protocol = 2 
smtpd_milters=inet:localhost:8891 
non_smtpd_milters=inet:localhost:8891

6.Restart opendkim and postfix

service opendkim restart
service postfix restar
#also use service postfix status to check the status

Logs

#you can look at logs, THIS HIGHLY USEFUL
vim /var/log/mail.log
vim /var/log/mail.err

Now if we want many domains

Do replace example.com and selector for each domains
What we have to do is to
1. generate one more key
sudo su
cd /etc/opendkim
opendkim-genkey -s [selector] -d example.com 
# replace both [selector] and      example.com with new selector and domain name
2. Change permission of generated key file
chown opendkim:opendkim [selector].private #[selector] we used in above step
3.add the details in TrustedHosts,SigningTable,KeyTable
Create the file
nano /etc/opendkim/key
And add the following line at end
        [selector]._domainkey.example.com example.com:[selector]:/etc/opendkim/[selector].private
Create the file
nano /etc/opendkim/sign
And add the following line
*@example.com
[selector]._domainkey.domain.com
Create the file
nano /etc/TrustedHosts
And add the following line
       *.domain.com
       domain.com
Also remember to restart opendkim and postfix each time.
service opendkim restart
sevice postfix restart
Finally send
or http://www.brandonchecketts.com/emailtest.php
or use http://www.mail-tester.com
to check the status of DKIM Signing by sending mails to these.

Reference

http://askubuntu.com/questions/134725/setup-dkim-domainkeys-for-ubuntu-postfix-and-mailman
(i started with this, then followed his reference )
http://stevejenkins.com/blog/2010/09/how-to-get-dkim-domainkeys-identified-mail-working-on-centos-5-5-and-postfix-using-opendkim/
(I think the best tutorial but on centos)
http://www.cioby.ro/linux/configuring-opendkim-to-sign-postfix-emails.html
http://linuxaria.com/howto/using-opendkim-to-sign-postfix-mails-on-debian

https://www.digitalocean.com/community/tutorials/how-to-install-and-configure-dkim-with-postfix-on-debian-wheezy
(TXT related portion is misleading)

Wednesday, 4 June 2014

Making colorful PDFs from web pages

This article show how to print the web pages into pdf.




Press Ctrl + P after completely loading the page.

Chrome


In Google Chrome select Save as PDF, set Margins: None and tick Background colors and images.


Now press Save button and give the filename. This is gives best pdf on my experience.

Firefox


For Firefox, in windows, you may not get print to pdf options by default. So you have to install either PDFCreator or PrismoPDF.

After pressing Ctrl + P

You get  a window, shown below, from which you have to select Printer Name ( PDFCreator here)
You can make sure it is color by clicking in Properties in the above windows

Now press ok. Then get another windows in which you have to select Save.

 If you like you can also try changing options in the above figure.