awstats for apache webserver

https://hottiehunter.com/awstats/awstats.pl?config=hottiehunter.com
Ubuntu 14.04, awstat version=7.2

#apt-get install awstats libgeo-ipfree-perl libnet-ip-perl
#a2enmod cgi 
 
 cp /etc/awstats/awstats.conf /etc/awstats/awstats.hottiehunter.com.conf
 
LogFile="/var/log/apache2/access.log"
LogFormat=1
 
SiteDomain="example.com"
#HostAliases="localhost 127.0.0.1 example.com"  #lesser is better for performance
 HostAliases="www.hottiehunter.com"
DirCgi="/awstats"
 
LoadPlugin="tooltips"
LoadPlugin="graphgooglechartapi"
LoadPlugin="geoipfree"
 
SkipDNSLookupFor="REGEX[^192\.168\.]"
 
AllowFullYearView=3 


Manually running update
========================

/usr/lib/cgi-bin/awstats.pl -config=hottiehunter.com -update
 
 

Automatic Stat Updates

To maintain the stats on a regular basis you will need a cron job to run the awstats update script. Change the user who will be running the script from www-data to root. There area bunch of permission errors when run as www-data.
The cron job below will run every 10 minutes, adjust the time to your needs.

*/10 * * * * root /usr/lib/cgi-bin/awstats.pl -config=hottiehunter.com -update > /dev/null
 
Configure Apache2 for awstats

vim /etc/apache2/sites-available/awstats.conf
 #for user password authentication to view stats
<Directory /usr/lib/cgi-bin/>
 AuthName "Enter Your User Name and Password"
  AuthType Basic
  AuthUserFile /etc/apache2/auth_users
  Require valid-user
</Directory> 
#alias configuration
Alias /awstatsclasses "/usr/share/awstats/lib/"
Alias /awstats-icon/ "/usr/share/awstats/icon/"
Alias /awstatscss "/usr/share/doc/awstats/examples/css"
ScriptAlias /cgi-bin/ /usr/lib/cgi-bin/
ScriptAlias /awstats/ /usr/lib/cgi-bin/
Options +ExecCGI -MultiViews +SymLinksIfOwnerMatch

if you receive some warnings with command :
apache2ctl -t 

grep search in /etc/apache2 with "alias and scriptalias as keywords"
for example
grep -i -R "ScriptAlias" /etc/apache2/*   #find duplicatoins and remove accordingly
Currently my config looks like:
 
Alias /awstatsclasses "/usr/share/awstats/lib/"
Alias /awstats-icon/ "/usr/share/awstats/icon/"
Alias /awstatscss "/usr/share/doc/awstats/examples/css"
#ScriptAlias /cgi-bin/ /usr/lib/cgi-bin/    #this is commented due to duplicaton
ScriptAlias /awstats/ /usr/lib/cgi-bin/
Options +ExecCGI -MultiViews +SymLinksIfOwnerMatch 


Stop Unauthorised Users

As the above setup stands anyone, that is the world and his dog can now see your web serrver stats. Probably not a good idea or something you want. We can let Awstats protect itself with the rather well named parameter AllowAccessFromWebToFollowingIPAddresses or as it is also simple to restrict access by forcing the user to enter a password or simple only allow IP addresses on your local LAN not from external IPs.
To allow awstats to protect itself edit the config file and add a list of IP addresses or ranges see the comment above the option of the syntax.
sudo nano /etc/awstats/awstats.example.com.conf
 
AllowAccessFromWebToFollowingIPAddresses="127.0.0.1 192.168.2.0-192.168.2.255" 
 

Access via a User Name and Password

To create a new user file and add the username “richard” to the file /etc/apache2/auth_users

To append other users do not use the -c flag.

htpasswd -c /etc/apache2/auth_users richard
 
#configuration is already on top for awstats.conf file for user/pass authentication

#service apache2 restart
 

Logging Data From Old logs

If you want to log the data in old log files rotated out of the way you can do that using a command line similar to the below. This may take some time depending on the number and size of your log files and the files need to be run in chronological order. If you ran the manual update above you will need to delete the database. Anyway, it was worth while as that is generally very quick and you can see some data being displayed. Also, it is worth moving the cron file for awstats to stop that from running.
The database files are where ever you pointed the option DirData to, it defaults to /var/lib/awstats. The second command mv the awstats cron job out of the way.

sudo rm /var/lib/awstats/*
 
sudo mv /etc/cron.d/awstats /root
 
Now we can run the log import or update from the command line. My Apache
 logs are compressed and called access.log,  access.log.1 or 
access.log.n.gz. Giving the following command line to import them all. 
Depending on the size and number of files this may put a heavy load on 
the server, so i also run the command through nice.

Note: the command should all be on one line.
 
sudo nice /usr/lib/cgi-bin/awstats.pl -update -config="example.com" -LogFile="/usr/share/awstats/tools/logresolvemerge.pl /var/log/apache2/access.log* |"
 

Remember to put the cron file back again.
sudo mv /root/awstats  /etc/cron.d
 
1) The URL should be
http://example.com/awstats/awstats.pl?config=example.com
2) Unless the CGI module is enabled, the perl script will be offered for download instead of being executed.
An additional step was required on my Ubuntu 14.04 system:
a2enmod cgi
 
Additional resource:
http://computers.in4mnation.com/install-and-secure-awstats-ubuntu-apache2/#set_up_cron_to_update_awstats
http://blogging.dragon.org.uk/installing-awstats-on-ubuntu-14-04-lts/




Nginx brief introduction

why exactly is nginx so much faster than the typical Apache setup of the prefork MPM and mod_php? The technical explanation is that nginx is a non-blocking event based architecture while Apache is a blocking process based architecture. To simplify it heavily the theory is like this:

Apache "Prefork Processes":

    Receive PHP request, send it to a process.
    Process receives the request and pass it to PHP.
    Receive an image request, see process is busy.
    Process finishes PHP request, returns output.
    Process gets image requests and returns the image.

While the process is handling the request it is not capable of serving another request, this means the amount of requests you can do simultaneously is directly proportional to the amount of processes you have running.
Apache + PHP setup has the PHP binary embedded directly into the Apache processes. This means Apache can talk to PHP incredibly fast and without much overhead, but it also means that the Apache process is going to be 25-50MB in size. Not just for requests for PHP requests, but also for all static file requests. This is because the processes keep PHP embedded at all times due to cost of spawning new processes. This effectively means you will be limited by the amount of memory you have as you can only run a small amount of processes and a lot of image requests can quickly make you hit your maximum amount of processes.

Nginx "Event Based Processing:"

    Receive request, trigger events in a process.
    The process handles all the events and returns the output


Nginx
Nginx, on the other hand, requires the use of PHP-FPM if you want to run a PHP application. It
doesn’t have a module to load in PHP like Apache can. I always use Nginx, as it does everything I
need with a simpler configuration, and better overall performance.

Process Management
PHP-FPM’s master process creates child processes to handle all PHP requests. Processes are
expensive to create and manage. How we treat them is important.
PHP-FPM is an implementation of FastCGI, which uses “persistent processes”. Rather than killing
and re-creating a process on each request, FPM will re-use processes.
This is much more efficient than Apache’s mod_php, which requires Apache to create and destroy a
process on every request.

nginx –s stop Stops the daemon immediately (using the TERM signal)
nginx –s quit Stops the daemon gracefully (using the QUIT signal)
nginx –s reopen Reopens the log files
nginx –s reload Reloads the configuration

part 5 apache MOD REWRITE

url rewrite with mod_rewrite.so  engine#
 
feature:
1)changes url or underlying request based on condition
2)based on perl regex
  important characters are
  . = matches a  single character
  * = matches zero or more of previous character
  + = matches one or more
  ? = optional match
  [] = character class  i,e '/prod[123]*'
  [^] = character class negation
  () = groups character for assignation to backreference , eg '/(prod|products)'
3) ability to parse:
  HTTP headers
  Server VARs - %{HTTP_HOST}
  enviromental VARs i,e IE
 
 http://hostname/URI
 HTTP= scheme
 host=hostname
 urlpath = /.. = basic rewrites operate here

  •        <Directory>
  •        .htaccess
      
      
RewirteRule - basic requirement - Takes 3 argument
usage: 'RewriteRule Pattern(URL-Path) Substitution [flag[s]]
Note: URL-Path matches after HOST and before Query String
eg http://site2.example.com/prod/index.php?pid=1&user=current

Note: substitution can be:
    a) File system path(mod_alias):
    RewriteRule ^/docs /usr/local/share/apache2/docs
    Note: The above uses 'mod_rewrite' as mod_alias
   
    b)web path:
    RewirteRule ^/docs$ /documents
    note: '/documents' exists beneath the DocumentRoot
   
    c)absolute URL: 'RewirteRule ^/docs$ http://www.testing.com/docs [R]'
    rewrites users browser URL to reflect new absolute URL
   
    Redirect
    No Change: '-'
    RewriteRule \.(jpg|png) - [E=image:1]  =>this enable VAR for later usage
Note Flags are optional can be multiple [f1,f2,f3...] and include common option
[NC] = case insensitive
[E=Var:Value] - setting of enviroment VAR -useful in logs,other rewrite rule, CGI
[F] = Returns 403 to client forbidding access to resource
[G] = Returns 410 to client resource is no longer available
[R] = returns redirect 300-399 to client

note: consult mod_rewrite docs for more flags

======================================================================

ensure module is loaded

ln -s . /etc/apache2/mods-available/rewrite.loaded

vim 000-default.conf
<virtualhost>
..
#request for example.com/index.html is sent to example.com/index2.html
RewriteEngine on   #enables processing
RewriteRule ^/index.html$ /index2.html #fetches new content but does not Redirect BROWSER (eg. example.com/index.html will serve content from index2.html but BROWSER url bar is not changed )
RewriteRule ^/index.html$ /index2.html [R] #fetches new content ALSO Redirect bROWSER #url is changed in browser
RewriteRule ^/docs$ http://testing.com/docs [R]


</virtualhost>


#mod rewrite - rewrite condition
 

features:

 stackability of logic
 rules are implicitly ANDed: use [OR] to enable ORing
 one or more tests may be performed on current request
 Supports backreferences using: %N - %1..%9
 Usage 'RewriteCond TestString CondPattern (RegEx) [OR, ornext, NC,NV
   teststring:
      RewriteRule
     
Task:
omit localhost (127.0.x.y) from apache logs
 a)  RewriteCond %{REMOTE_ADDR} ^127\.0\.
 b)  RewriteRule .* - [E=localnolog] => Defines VAR to indicate request from localhost
 c)  'CustomLog /var/log/apache/access.log combined env=!localnolog'



 Force SSL for url path '/login$'

 'RewriteCond %{REQUEST_URI} ^/login'
 'RewriteCond ${SERVER_PORT} !443'
 'RewriteRule .* https://%{HTTP_HOST}/login'
OR
 RewriteCond %{REQUEST_URI} ^(/login.*)
RewriteCond %{SERVER_PORT} !443
RewriteRule .* https://%{HTTP_HOST}/login.html

Force ssl for all
RewriteCond %{SERVER_PORT} !443
RewriteRule .* https://%{HTTP_HOST}%{REQUEST_URI

RewriteEngine on
RewriteCond %{HTTP_HOST} ^lokeshworhandicraft.com.np [NC,OR]
RewriteCond %{HTTP_HOST} ^www.lokeshworhandicraft.com.np [NC]
RewriteCond %{REQUEST_URI} !^/public/
RewriteRule ^(.*)$ /public/$1 [L]

 

RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}





Back reference

##mod rewrite##
Backreferences

feature
 #tokenize portion of URL for reuse
 #token range form $1 .. $9
 #uses '()' to create token
 #per server and per directory (.htaccess | <Directory>)
 Note: normally placed at site-wide or virtualHost layer
 Note: normally used to match: URL-Path

 task:
 rewrite index.html -> /new/index.html
 ------------------------------------------
 RewriteRule ^/(index.html)$ /new/$1  #equivalent to redirect[Match]
 RewriteRule ^/(index.html)$ /new/$1 [R] #equivalent to Redirect[Match] - Force redirect


 Rewrite 'localhost/docs*' -> 'http://www.facebook.com/docs*
 a. RewriteRule ^(/docs.*)$ http://linuxorg.com$1 - Redirects: '/docs* to remote server










part 4 apache conditional handling

conditional handling features:

A) make decisions based on current conditions:
 1) modules available
 2) remote HOST
 3) browser type - useragent(http header request)

B) <IfDefine> parameter - directives to be processed at server startup
C) <IfModule> - directive to be processed based on module existence. Eg mod_ssl
D) <IfVersion> - directive processed based on version of apache
E) SetEnvIf[NoCase] -sets environmental VAR (variable) based on :
   HTTP Request Header : i,e User-Agent, Referer , Accept-Language
   Remote_(Addr|Host) server_addr, Request_(method|Protocol), Request_URI
   Predefined Environmental VARs using : SetEnvIf[NoCase]
  
Task:

 Explore <IfModule>

 apachectl -D DUMP_MODULES 
 or
 apache2ctl -M | grep -E "(static|shared)" | wc -l

 cd /etc/apache2 && grep -R -i 'ifmodule' *   --searches for ifmodule

 inside the <VirutalHost>
 <VirtualHost>
 ..
 SetEnvIf Referer "site1.linuxcbt.internal" site1_referrer
 CustomLog /var/log/apache2/site2.site1_referral.access.log combined env=site1_referrer
 </VirtualHost>

part 3 apache content negotiation and content restriction

content negotiation

responds to http/1.1 request header options
presents client with bestmatch resources http/1.1
-alternate language, character set ,media type etc
handled by - mod_negotiation

content negotiation is based on 2 methods-
1 type maps - *.var file -include variants
2 MultiViews - server auto searches for alternatives based on client request

task:
negotiate content based on language

vim  index.html.var

URI: index.html

URI: index.html
Content-type: text/html
Content-language: en

URI: index.html.es
Content-type: text/html
Content-language: es


content restriction

restricts access to content based on
1 <Directory>
2 <Location> -url webspace
3 <Files>
4 <Auth> authentication related directives

default config restricts access to .htaccess , .ht* files

Tasks:
1) <Directory> - applies to filesystem location
<Directory /home/site2/www/private>
  Order allow,deny
  Allow from 127.0.0.1 192.179.90.22
</Directory>

 effectively take content offline from webspace
 <Directory /home/site2/www/private>
     Order deny,allow
     Deny from all
 </Directory>

 Use <Location> applies restriction based on URL string

 <LocationMatch ^/priv> - traps variants including but not limited to "/private , /priv ,/privilege , /primary etc"
 <LocationMatch ^/priv>
     Order deny,allow
     Deny from all
 </LocationMatch>
   eg -  example.com/privtt is restricted OR
  
   <Location ~ ^/priv>
   Order deny,allow
   Deny from all
   </Location>

 <Files> to restrict based on files
 NOTE:- it should be placed under <Directory> block or in .htaccess in particular directory as needed
 <Files ~ "\.(xls|docx|sql|pdf)">
 Order deny,allow
 deny from all
 </Files>
 <FilesMatch "\.">
   Order deny,allow
   Deny from all
 </FilesMatch




part 2 apache socket binding and htaccess

default port 80
binding facilitate virtual hosting
bindings are tagged to virtual host containers
Listen - key directive
grep -i listen #across apache config
on debian system check ports.conf

#bind to alternates ports



HTACCESS

-on demand configuration  updates to your sites managed by Apache
-substitute for "<Directory></Directory>" directives
-configure per directory options
-indirect site control via ftp,sftp etc
-

Options +Indexes
<Files *xls>
Order allow,deny
allow from 127.0.0.127 192.168.0.12/24
</Files>


Redirect /docs http://facebook.com

 

part 1 apache url mapping and redirect

Alias /doc/ "/usr/share/doc/"

if any other new directory except document root then it must be published with <Directory /your/directory/> </Directory>

AliasMatch
==========
AliasMatch ^/docs/(.*pdf) /var/www/docs2/$1

#$1 is first parenthesized block (.*pdf)<=its called reference


#anything terminating with pdf suffix

AliasMatch ^/docs/(.*pdf|txt) /var/www/docs2/$1
#anything terminating with pdf OR txt suffix
AliasMatch ^/docs/(.*) /var/www/docs2/$1
#reroute every thing to/docs2

AliasMatch ^/(docs)/(projectx)/(.*) /var/www/$2/$1/TXT/$3
#same as above but variablized

AliasMatch ^/(docs)/(projectx)/(.*\.pdf) /var/www/$2/$1/PDF/$3

                                                                                                                       

Redirect sends client to new destination
remaps url path beginning with '/' to new url
implementation of mod_alias as Redirect, RedirectMatch , RedirectPermanent, RedirectTemp
dafault status : 302
301: permanent
302:temporary

Redirect /docs  /docs2
#docs is redirected to docs2

Redirect /docs http://192.123.12.33/docs
#sends client to remote system

Redirect /docs http://www.google.com/docs

#invoke-rc.d apache2 reload


#  Using Redirect Match

RedirectMatch (.*)\.doc  $1.pdf #applies .pdf substitution across the site
eg.  google.com/docs2/TXT/file.doc

google.com/docs2/TXT/file # this is preserved and
.doc is replaced with .pdf and redirected


RedirectMatch /docs/(.*)\.doc /PDF/$1.pdf
anyfile terminating with .doc extension is redirected with same scheme
and same server









SED editor sed

Remove multiple spaces
= = = = = = =
 Remove leading spaces and number from history cmmand output

history | sed 's/^ *[0-9][0-9]* *//'

 
root@vm2:~# cat hello 
#ab 12
cd      99
   zz    te
#ef
    test
      #tellso


root@vm2:~# cat hello  | sed 's/^\s\+//g'

#ab 12
cd      99
zz    te
#ef
test
#tellso

Combinig sed expression
root@vm2:~# cat hello  | sed 's/^\s\+//g;s/\s\+/ /g'
#ab 12
cd 99
zz te
#ef
test
#tellso


sed 'p' passwd  #prints file content but double content
sed -n '1p' file.txt  #print 1st line
sed -n  '2p' file.txt  #print 2nd line
sed -n 4,13p file.txt #print 4 to 14 line
sed -n '$p'  file.txt  #print last
sed -n '1!p' file.txt  #print all except line 1
sed -n '1,3!p' file.txt #print all except line 1 to 3

AWK

will print all but very first column:

awk '{$1=""; print $0}' somefile

will print all but two first columns:

awk '{$1=$2=""; print $0}' somefile

history | awk '{$1=$1;print}' | cut -d' ' -f2-       #remove beginning spaces and history number , cut -f2- will start printing from 2nd field to last
history | awk '{$1=$1;print}' | cut -d' ' -f1-4     # cut -f1-4 will print from field 1 to 4

SED editor sed

cat test | sed 's#first#second#Ig'     ## use `I` for case insensitive

Remove multiple spaces
= = = = = = =
root@vm2:~# cat hello
#ab 12
cd      99
   zz    te
#ef
    test
      #tellso


root@vm2:~# cat hello  | sed 's/^\s\+//g'
#ab 12
cd      99
zz    te
#ef
test
#tellso

Combinig sed expression
root@vm2:~# cat hello  | sed 's/^\s\+//g;s/\s\+/ /g'
#ab 12
cd 99
zz te
#ef
test
#tellso


sed 'p' passwd  #prints file content but double content
sed -n '1p' file.txt  #print 1st line
sed -n  '2p' file.txt  #print 2nd line
sed -n 4,13p file.txt #print 4 to 14 line
sed -n '$p'  file.txt  #print last
sed -n '1!p' file.txt  #print all except line 1
sed -n '1,3!p' file.txt #print all except line 1 to 3
=======================using regular expression=======================
we use '-e' option when we use expression

sed -n -e '/2011/p' file.txt     # print line containing 2011
sed -n -e '/^root/p' passwd      # print lines starting with word 'root'
sed -n -e '/root$/p' passwd      # print lines Ending with word 'root'
sed -n -e '/^harke101$/p' passwd
sed -n -e '/^harke101.*$/p' passwd     # print lines Starting and Ending with word 'root'
sed -n -e '/[0-9]/p' firewall.txt     # print lines containing number 0-9
sed -n -e '/^[0-9][0-9][0-9]$/p'  firewall.txt #print beginning and ending with 3 char number
sed -n -e '/[0-9]\{3\}/p' firewall.txt # print beginning and ending with 3 char number
sed -n -e '/^[0-9]\{3\}$/p' firewall.txt # print beginning and ending with 3 char number




3.3 Overview of Regular Expression Syntax

To know how to use sed, people should understand regular expressions (regexp for short). A regular expression is a pattern that is matched against a subject string from left to right. Most characters are ordinary: they stand for themselves in a pattern, and match the corresponding characters in the subject. As a trivial example, the pattern
     The quick brown fox
matches a portion of a subject string that is identical to itself. The power of regular expressions comes from the ability to include alternatives and repetitions in the pattern. These are encoded in the pattern by the use of special characters, which do not stand for themselves but instead are interpreted in some special way. Here is a brief description of regular expression syntax as used in sed.
char
A single ordinary character matches itself.
*
Matches a sequence of zero or more instances of matches for the preceding regular expression, which must be an ordinary character, a special character preceded by \, a ., a grouped regexp (see below), or a bracket expression. As a GNU extension, a postfixed regular expression can also be followed by *; for example, a** is equivalent to a*. POSIX 1003.1-2001 says that * stands for itself when it appears at the start of a regular expression or subexpression, but many nonGNU implementations do not support this and portable scripts should instead use \* in these contexts.
\+
As *, but matches one or more. It is a GNU extension.
\?
As *, but only matches zero or one. It is a GNU extension.
\{i\}
As *, but matches exactly i sequences (i is a decimal integer; for portability, keep it between 0 and 255 inclusive).
\{i,j\}
Matches between i and j, inclusive, sequences.
\{i,\}
Matches more than or equal to i sequences.
\(regexp\)
Groups the inner regexp as a whole, this is used to:
  • Apply postfix operators, like \(abcd\)*: this will search for zero or more whole sequences of ‘abcd’, while abcd* would search for ‘abc’ followed by zero or more occurrences of ‘d’. Note that support for \(abcd\)* is required by POSIX 1003.1-2001, but many non-GNU implementations do not support it and hence it is not universally portable.
  • Use back references (see below).
.
Matches any character, including newline.
^
Matches the null string at beginning of the pattern space, i.e. what appears after the circumflex must appear at the beginning of the pattern space. In most scripts, pattern space is initialized to the content of each line (see How sed works). So, it is a useful simplification to think of ^#include as matching only lines where ‘#include’ is the first thing on line—if there are spaces before, for example, the match fails. This simplification is valid as long as the original content of pattern space is not modified, for example with an s command.
^ acts as a special character only at the beginning of the regular expression or subexpression (that is, after \( or \|). Portable scripts should avoid ^ at the beginning of a subexpression, though, as POSIX allows implementations that treat ^ as an ordinary character in that context.
$
It is the same as ^, but refers to end of pattern space. $ also acts as a special character only at the end of the regular expression or subexpression (that is, before \) or \|), and its use at the end of a subexpression is not portable.
[list]
[^list]
Matches any single character in list: for example, [aeiou] matches all vowels. A list may include sequences like char1-char2, which matches any character between (inclusive) char1 and char2. A leading ^ reverses the meaning of list, so that it matches any single character not in list. To include ] in the list, make it the first character (after the ^ if needed), to include - in the list, make it the first or last; to include ^ put it after the first character.
The characters $, *, ., [, and \ are normally not special within list. For example, [\*] matches either ‘\’ or ‘*’, because the \ is not special here. However, strings like [.ch.], [=a=], and [:space:] are special within list and represent collating symbols, equivalence classes, and character classes, respectively, and [ is therefore special within list when it is followed by ., =, or :. Also, when not in POSIXLY_CORRECT mode, special escapes like \n and \t are recognized within list. See Escapes.
regexp1\|regexp2
Matches either regexp1 or regexp2. Use parentheses to use complex alternative regular expressions. The matching process tries each alternative in turn, from left to right, and the first one that succeeds is used. It is a GNU extension.
regexp1regexp2
Matches the concatenation of regexp1 and regexp2. Concatenation binds more tightly than \|, ^, and $, but less tightly than the other regular expression operators.
\digit
Matches the digit-th \(...\) parenthesized subexpression in the regular expression. This is called a back reference. Subexpressions are implicity numbered by counting occurrences of \( left-to-right.
\n
Matches the newline character.
\char
Matches char, where char is one of $, *, ., [, \, or ^. Note that the only C-like backslash sequences that you can portably assume to be interpreted are \n and \\; in particular \t is not portable, and matches a ‘t’ under most implementations of sed, rather than a tab character.
Note that the regular expression matcher is greedy, i.e., matches are attempted from left to right and, if two or more matches are possible starting at the same character, it selects the longest.
Examples:
‘abcdef’
Matches ‘abcdef’.
‘a*b’
Matches zero or more ‘a’s followed by a single ‘b’. For example, ‘b’ or ‘aaaaab’.
‘a\?b’
Matches ‘b’ or ‘ab’.
‘a\+b\+’
Matches one or more ‘a’s followed by one or more ‘b’s: ‘ab’ is the shortest possible match, but other examples are ‘aaaab’ or ‘abbbbb’ or ‘aaaaaabbbbbbb’.
‘.*’
‘.\+’
These two both match all the characters in a string; however, the first matches every string (including the empty string), while the second matches only strings containing at least one character.
‘^main.*(.*)’
This matches a string starting with ‘main’, followed by an opening and closing parenthesis. The ‘n’, ‘(’ and ‘)’ need not be adjacent.
‘^#’
This matches a string beginning with ‘#’.
‘\\$’
This matches a string ending with a single backslash. The regexp contains two backslashes for escaping.
‘\$’
Instead, this matches a string consisting of a single dollar sign, because it is escaped.
‘[a-zA-Z0-9]’
In the C locale, this matches any ASCII letters or digits.
‘[^ tab]\+’
(Here tab stands for a single tab character.) This matches a string of one or more characters, none of which is a space or a tab. Usually this means a word.
‘^\(.*\)\n\1$’
This matches a string consisting of two equal substrings separated by a newline.
‘.\{9\}A$’
This matches nine characters followed by an ‘A’.
‘^.\{15\}A’
This matches the start of a string that contains 16 characters, the last of which is an ‘A’.

generate entropy to help speed up key generation

apt-get install rng-tools

vim /etc/default/rng-tools
HRNGDEVICE=/dev/urandom

/etc/init.d/rng-tools start
 /etc/init.d/rng-tools stop

fstab file insights

There's a file called /etc/fstab in your Linux system. Learn what its contents mean and how it's used in conjunction with the mount command. When you learn to understand the fstab file, you'll be able to edit its contents yourself, too.
In this tuXfile I assume you already know how to mount file systems and partitions with the mount command. If you don't, I suggest reading theMounting tuXfile before reading this one.

What is fstab and why it's useful

fstab is a configuration file that contains information of all the partitions and storage devices in your computer. The file is located under /etc, so the full path to this file is /etc/fstab.
/etc/fstab contains information of where your partitions and storage devices should be mounted and how. If you can't access your Windows partition from Linux, aren't able to mount your CD or write to your floppy as a normal user, or have problems with your CD-RW, you probably have a misconfigured /etc/fstab file. So, you can usually fix your mounting problems by editing your fstab file.
/etc/fstab is just a plain text file, so you can open and edit it with any text editor you're familiar with. However, note that you must have the root privileges before editing fstab. So, in order to edit the file, you must either log in as root or use the su command to become root.

Overview of the file

Of course everybody has a bit different /etc/fstab file because the partitions, devices and their properties are different on different systems. But the basic structure of fstab is always the same. Here's an example of the contents of /etc/fstab:
/dev/hda2   /              ext2 defaults             1 1
/dev/hdb1   /home          ext2 defaults             1 2
/dev/cdrom  /media/cdrom   auto ro,noauto,user,exec  0 0
/dev/fd0    /media/floppy  auto rw,noauto,user,sync  0 0
proc        /proc          proc defaults             0 0
/dev/hda1   swap           swap pri=42               0 0
What does all this gibberish mean? As you see, every line (or row) contains the information of one device or partition. The first column contains the device name, the second one its mount point, third its file system type, fourth the mount options, fifth (a number) dump options, and sixth (another number) file system check options. Let's take a closer look at this stuff.

1st and 2nd columns: Device and default mount point

The first and second columns should be pretty straightforward. They tell themount command exactly the same things that you tell mount when you mount stuff manually: what is the device or partition, and what is the mount point. The mount point specified for a device in /etc/fstab is its default mount point. That is the directory where the device will be mounted if you don't specify any other mount point when mounting the device.
Like you already learned from the Mounting tuXfile, most Linux distros create special directories for mount points. Most distros create them under/mnt, but some (at least SuSE) under /media. As you probably noticed when looking at the example fstab, I use SuSE's mount points as an example.
What does all this mean? If I type the following command:
$ mount /dev/fd0
my floppy will be mounted in /media/floppy, because that's the default mount point specified in /etc/fstab. If there is no entry for /dev/fd0 in my fstab when I issue the command above, mount gets very confused because it doesn't know where to mount the floppy.
You can freely change the default mount points listed in /etc/fstab if you're not satisfied with the defaults your distro has given you. Just make sure the mount point is a directory that already exists on your system. If it doesn't, simply create it.
Some partitions and devices are also automatically mounted when your Linux system boots up. For example, have a look at the example fstababove. There are lines that look like this:
/dev/hda2 / ext2 defaults 1 1
/dev/hdb1 /home ext2 defaults 1 2
As you've learned, these lines mean that /dev/hda2 will be mounted to / and /dev/hdb1 to /home. This is done automatically when your Linux system boots up... if it wouldn't, you'd have a hard time using your cool Linux system because all the programs you use are in / and you wouldn't be able to run them if / wasn't mounted! But how does the system know where you want to mount /dev/hda2 and /dev/hdb1? By looking at the/etc/fstab file of course.

3rd column: Filesystem type

The third column in /etc/fstab specifies the file system type of the device or partition. Many different file systems are supported but we'll take a look at the most common ones only.
ext2 and ext3 Very likely your Linux partitions are Ext3. Ext2 used to be the standard file system for Linux, but these days, Ext3 and ReiserFS are usually the default file systems for almost every new Linux distro. Ext3 is a newer file system type that differs from Ext2 in that it's journaled, meaning that if you turn the computer off without properly shutting down, you shouldn't lose any data and your system shouldn't spend ages doing file system checks the next time you boot up.
reiserfs Your Linux partitions may very well be formatted as ReiserFS. Like Ext3, ReiserFS is a journaled file system, but it's much more advanced than Ext3. Many Linux distros (including SuSE) have started using ReiserFS as their default file system for Linux partitions.
swap The file system name is self-explanatory. The file system type "swap" is used in your swap partitions.
vfat and ntfs Your Windows partitions are probably either Vfat or NTFS. The 9x series (95, 98, ME) all use Vfat (more widely known as FAT32), and the NT series (NT, 2000, XP) use NTFS. In 2000 and XP you can choose the file system type, so 2000 and XP partitions may be formatted as Vfat, too. If you want to be able to write to your Windows partitions from Linux, I suggest formatting them as Vfat, because Linux's support for writing to NTFS partitions is a bit shabby at this moment.
auto No, this isn't a file system type :-) The option "auto" simply means that the file system type is detected automatically. If you take a look at the example fstab above, you'll see that the floppy and CD-ROM both have "auto" as their file system type. Why? Their file system type may vary. One floppy might be formatted for Windows and the other for Linux's Ext2. That's why it's wise to let the system automatically detect the file system type of media such as floppies and cdroms.

4th column: Mount options

The fourth column in fstab lists all the mount options for the device or partition. This is also the most confusing column in the fstab file, but knowing what some of the most common options mean, saves you from a big headache. Yes, there are many options available, but I'll take a look at the most widely used ones only. For more information, check out the man page of mount.
auto and noauto With the auto option, the device will be mounted automatically (at bootup, just like I told you a bit earlier, or when you issue the mount -a command). auto is the default option. If you don't want the device to be mounted automatically, use the noauto option in /etc/fstab. With noauto, the device can be mounted only explicitly.
user and nouser These are very useful options. The user option allows normal users to mount the device, whereas nouser lets only the root to mount the device. nouser is the default, which is a major cause of headache for new Linux users. If you're not able to mount your cdrom, floppy, Windows partition, or something else as a normal user, add the useroption into /etc/fstab.
exec and noexec exec lets you execute binaries that are on that partition, whereas noexec doesn't let you do that. noexec might be useful for a partition that contains binaries you don't want to execute on your system, or that can't even be executed on your system. This might be the case of a Windows partition.
exec is the default option, which is a good thing. Imagine what would happen if you accidentally used the noexec option with your Linux root partition...
ro Mount the file system read-only.
rw Mount the file system read-write. Again, using this option might cure the headache of many new Linux users who are tearing their hair off because they can't write to their floppies, Windows partitions, or something else.
sync and async How the input and output to the file system should be done. sync means it's done synchronously. If you look at the examplefstab, you'll notice that this is the option used with the floppy. In plain English, this means that when you, for example, copy a file to the floppy, the changes are physically written to the floppy at the same time you issue the copy command.
However, if you have the async option in /etc/fstab, input and output is done asynchronously. Now when you copy a file to the floppy, the changes may be physically written to it long time after issuing the command. This isn't bad, and may sometimes be favorable, but can cause some nasty accidents: if you just remove the floppy without unmounting it first, the copied file may not physically exist on the floppy yet!
async is the default. However, it may be wise to use sync with the floppy, especially if you're used to the way it's done in Windows and have a tendency to remove floppies before unmounting them first.
defaults Uses the default options that are rw, suid, dev, exec, auto, nouser, and async.

5th and 6th columns: Dump and fsck options

Dump and, uh, what options? Well, dump is a backup utility and fsck is a file system check utility. I won't discuss them in great length here (they would both need their own tuXfile), but I'll mention them, because otherwise you'd spend the rest of the day wondering what on God's green Earth do these things mean.
The 5th column in /etc/fstab is the dump option. Dump checks it and uses the number to decide if a file system should be backed up. If it's zero, dump will ignore that file system. If you take a look at the example fstab, you'll notice that the 5th column is zero in most cases.
The 6th column is a fsck option. fsck looks at the number in the 6th column to determine in which order the file systems should be checked. If it's zero, fsck won't check the file system.

Example /etc/fstab entries

As an example, we'll take a look at a couple of fstab entries that have been a source of endless frustration for new Linux users: floppy and CD-ROM (although these days floppies aren't that important anymore).
/dev/fd0 /media/floppy auto rw,noauto,user,sync 0 0
This line means that the floppy is mounted to /media/floppy by default and that its file system type is detected automatically. This is useful because the type of the floppy may wary. Note especially the rw and user options: they must be there if you want to be able to mount and write to the floppy as a normal user. If you have trouble with this, check your fstabfile to see if these options are there. Also note the sync option. It can be async just as well, but it's sync because of reasons discussed a bit earlier.
/dev/cdrom /media/cdrom auto ro,noauto,user,exec 0 0
Note, again, the user option that enables you to mount the CD as a normal user. The CD-ROM has the ro option because it's no use mounting a CD-ROM read-write because you wouldn't be able to write to it anyway. Also note the exec option. It's especially useful if you'd like to be able to execute something from your CD.
Also note that the noauto option is used with the floppy and CD-ROM. This means that they won't be automatically mounted when your Linux system boots up. This is useful for removable media, because sometimes there won't be any floppy or CD-ROM when you boot up your system, so there isn't any reason to try to mount something that doesn't even exist.