Linux presentation

linux-ppt

I have been asked to do a linux presentation for my work colleagues, so I did just that. I prepared a 80 pages Linux presentation, oriented for people that do not know what linux realy is and how it works, so this is oriented towards Windows user mostly.

I have presented basic stuff like:
– linux history,
– type of distros,
– statistics about linux usage,
– simplified architecture,
– how to remote access the server via SSH,
– BASH
– system information & current load
– copying, renaming and deleting files
– filter bash output with grep
– users and groups
– permissions
– installing software
– iptables,
– cron
– networking

And other interesting facts about Linux.
Feel free to use it !

Linux presentation

Install truecrypt on Linux CentOS

Truecrypt is probably the greatest encryption software that I’ve used to protect my files. Unfortunately it has been discontinued by it’s developers for some very strange reasons.

However, that doesn’t mean that it is not still available to install on your linux box.

So here goes the install process for truecrypt 7.1a:

1. (Optional) Check https://www.grc.com/misc/truecrypt/truecrypt.htm for some nice info

2.  Download https://www.grc.com/misc/truecrypt/truecrypt-7.1a-linux-console-x86.tar.gz

- wget https://www.grc.com/misc/truecrypt/truecrypt-7.1a-linux-console-x86.tar.gz


3. Extract the truecrypt archive:

tar -xvf ./ truecrypt-7.1a-linux-console-x86.tar.gz

cd ./truecrypt-7.1a-linux-console-x86.tar



3.  Install the requirements: libstdc++.so.6 and libfuse.so.2

yum install libfuse.so.2

yum install libstdc++.so.6


4. Run the truecrypt installer:

[root@fcsteaua truecrypt]# ./truecrypt-7.1a-setup-console-x86

- select option 1


5.  Create a new volume with:

/usr/bin/truecrypt -c

- follow the easy steps in the volume setup


6. Mount the container to a specified directory:

[root@fcsteaua truecrypt]# truecrypt -t -k "" --protect-hidden=no container1 /media/truecrypt1
Enter password for /home/cristi/truecrypt/container1:
[root@fcsteaua truecrypt]# cd /media/truecrypt1
[root@fcsteaua truecrypt1]# ls
[root@fcsteaua truecrypt1]# pwd
/media/truecrypt1

7. Dismount a container:
truecrypt -d 

That’s it. Have fun hiding your stuff!

Guess my number python script

Modify the Guess My Number game so that the player has a
limited number of guesses. If the player fails to guess in time,
the program should display an appropriately chastising
message.

# guess my number game
# the computer generates a number between 1 and 100
# and tells the user if the number entered is smaller or higher
# than the number picked randomally by the computer

import random
print("I'm thinking of a number between 1 and 100\n")
print("Try to guess it in 5 attempts\n")

guess_total = 0
random_number = int(random.randint(1, 100))
my_number = int(input("Introduceti numarul: "))


while guess_total < = 5 :
    if guess_total >= 4:
        print("You've reached the max number of tries")
        break
           
    elif my_number == random_number:
        guess_total += 1
        guess_total = int(guess_total)
        print("Great. You've guessed it in", guess_total,"tries")
        break
        
    elif my_number < random_number:
        guess_total += 1
        guess_total = int(guess_total)
        print("You're number is too low\n")
        my_number = int(input("Introduceti numarul: "))
        
    elif my_number > random_number:
        guess_total += 1
        guess_total = int(guess_total)
        print("You're number is too high")
        my_number = int(input("Introduceti numarul: "))

# end of my wannabe program

My python journey (1)

So I’m trying to learn python using “Python for the absolute beginner, 3rd edition”
Challenges:
. Write a program that simulates a fortune cookie. The program
should display one of five unique fortunes, at random, each
time it’s run.

# program to display fortune cookies
# display random one of 5 fortune cookies

import random
cookie = int(random.randint(1, 5))

if cookie == 1:
    print(cookie, "it is.", "You will win the lottery this week.")
elif cookie == 2:
    print(cookie, "it is.", "You will get laid with a hot blonde...someday.")
elif cookie == 3:
    print(cookie, "it is.", "You will get an extra hour of sleep.")
elif cookie == 4:
    print(cookie, "it is.", "You will be a successful hacker.")
elif cookie == 5:
    print(cookie, "it is.", "Nothing special will happen today. Tough luck!")
else:
    print("Error happend")

input("\nPress enter to exit!")


And here is the output of the program.

python for beginners

Me and my luck… :)

Install Logwatch in Linux CentOS

Logwatch is a Linux application that parses log files, analyses them and sends periodical reports, based on specific criteria, to one or more email addresses.
In order to install it in linux you have to issues the following command:

yum install logwatch

Edit the configuration file:

nano /usr/share/logwatch/default.conf/logwatch.conf

Check and edit the following directives in order to suit your needs:

LogDir = /var/log
MailFrom = Logwatch@mydomain.com
Range = yesterday //(or today)
Detail=Medium // (other: Low, Medium, High)
Service=all //(other examples would be httpd, sshd2, ftp)

Run logwatch manually:

logwatch --detail High --mailto myemail@domain.com --service http --range today

The output should be like this:


 ################### Logwatch 7.3.6 (05/19/07) ####################
        Processing Initiated: Tue May 19 14:21:59 2015
        Date Range Processed: today
                              ( 2015-May-19 )
                              Period is day.
      Detail Level of Output: 5
              Type of Output: unformatted
           Logfiles for Host: fcsteaua.ro
  ##################################################################

 --------------------- courier mail services Begin ------------------------

 **Unmatched Entries**
   courier-pop3d - 2 Times
      Connection, ip=[::ffff:182.118.53.150] - 1 Time
      Disconnected, ip=[::ffff:182.118.53.150] - 1 Time



 ---------------------- courier mail services End -------------------------


 --------------------- Cron Begin ------------------------

sshd:
    Authentication Failures:
       root (43.255.188.163): 4930 Time(s)
       root (43.255.188.155): 3524 Time(s)
       root (61-218-247-185.hinet-ip.hinet.net): 925 Time(s)
       unknown (61-218-247-185.hinet-ip.hinet.net): 391 Time(s)
       root (61.133.63.14): 137 Time(s)
       root (58.218.205.72): 114 Time(s)
       root (222.186.160.48): 98 Time(s)
       root (218.65.30.61): 90 Time(s)
       root (221.229.166.81): 80 Time(s)
       root (58.218.205.66): 69 Time(s)
       root (58.218.199.195): 68 Time(s)

Block failure notice emails in qmail

I have Plesk on my Linux server and I receive lots of spam emails from the root account on my server.
Here’s what happened. My forum used to send emails to non-existent email accounts around the web and I used to receive the failure notices for them.
To block failure notice emails in qmail that were forwarded to my main email I had to modify the aliases from

/var/qmail/alias

Here’s a sample email I received:

MAILER-DAEMON@nixware.net
Mar 30 (7 days ago)

to postmaster 
Hi. This is the qmail-send program at nixware.net.
I tried to deliver a bounce message to this address, but the bounce bounced!

:
2a00:1450:4013:0c01:0000:0000:0000:001a does not like recipient.
Remote host said: 550-5.1.1 The email account that you tried to reach does not exist. Please try
550-5.1.1 double-checking the recipient's email address for typos or
550-5.1.1 unnecessary spaces. Learn more at
550 5.1.1 http://support.google.com/mail/bin/answer.py?answer=6596 q5si14669450wjx.9 - gsmtp
Giving up on 2a00:1450:4013:0c01:0000:0000:0000:001a.

--- Below this line is the original bounce.

Return-Path: &lt;&gt;
Received: (qmail 8634 invoked for bounce); 29 Mar 2015 23:50:02 +0200
Date: 29 Mar 2015 23:50:02 +0200
From: MAILER-DAEMON@nixware.net
To: root@nixware.net
Subject: failure notice

As you can see, the postmaster account was receiving the spam from MAILER-DAEMON and MAILER-DAEMON was forwarding them to my gmail.com account. Pretty nasty…

The fix:
Go to

/var/qmail/alias

do a

ls -alh

and you will see a couple of hidden config files.

Inside each of those file I had my @gmail account. With the next script I overwrote the gmail account with a non-existent email:

Qmail alias hidden files

 

 

 

 

 

 

 

for FILE in ./.qmail-*;do echo "nonexistent@nodomain.tld" > $FILE;done

Restart/reload qmail:

service qmail reload

That’s it! You should not receive any spam from any of the root, mailman or postmaster accounts.

Batch download files from a website

I needed a quick bash script that will batch download all files from a public web server.
The files had the names like 1.gif, 2.gif, etc and were accessible via a CDN subdomain like http://images.mydomain.com.

So here it is:

for i in {1..18000}; do wget images.mydomain.com/$i.gif; sleep 5;done

Replace mydomain.com with your site and that’s it.
Alternatively you can get rid of “sleep 5″ and put the whole script in a file and execute it with:


[root@nix]# nohup ./script.sh &

This will keep your script running even if you disconnect from the shell console.

Restore mysql database from sql file

If you want to restore a mysql database from a sql file you have to issue this command:

[root@enix ~]#mysql -uroot -pxxx my-database < my-database-backup.sql

– where: my-database is your databse where you want to restore data;
– my-database-backup.sql is your sql backup file
– change root to your mysql user
– change xxx with your mysql password

And that’s it.

When dumping the database with mysqldump, use the option –no-create-db.
This will suspress the CREATE DATABASE statement in your dump file.
Then restore the database with

mysql -h <host> -u <user> -p <databasename> < dump.sql

In this way you can restore your data in whatever database you like (But that database has to exist!).

Substitution operators

Substitution operators are used for expanding parameters and variable values.

Examples:

${variablename:-some word}

-If varname exists and isn’t null, return its value; otherwise return word.

Purpose: Returning a default value if the variable is undefined.

[root@euve59329 ~]# echo ${PWDx:-non existent variable}
non existent variable

${varname:=word}
– If varname exists and isn’t null, return its value; otherwise set it to
word and then return its value. Positional and special parameters

[root@euve59329 ~]# echo ${ID:=0}
0

– ID variable does not exist. In this case, the value is set to 0.

Purpose:Setting a variable to a default value if it is undefined.


${varname:?message} 

If varname exists and isn’t null, return its value; otherwise print
varname: followed by message, and abort the current command or
script (non-interactive shells only). Omitting message produces the
default message parameter null or not set.

 

[root@euve59329 ~]# echo ${thevariable:?does not exist}
bash: thevariable: does not exist
[root@euve59329 ~]#

– Purpose: Catching errors that result from variables being undefined.


${varname:+word}

[root@euve59329 ~]# echo ${count:+1}
1
[root@euve59329 ~]# echo ${countX:+1}

Purpose: Testing for the existence of a variable.
Example: ${count:+1} returns 1 (which could mean “true”) if count is
defined.


 

${varname:offset:length}

 

Performs substring expansion.[5] It returns the substring of $varname
starting at offset and up to length characters. The first character in
$varname is position 0. If length is omitted, the substring starts at
offset and continues to the end of $varname. If offset is less than 0 then
the position is taken from the end of $varname. If varname is @, the
length is the number of positional parameters starting at parameter
offset.
Purpose: Returning parts of a string (substrings or slices).
Example:

 

[root@euve59329 ~]# count=MyCoolText
[root@euve59329 ~]# echo ${count:4}
olText
[root@euve59329 ~]# echo ${count:4:4}
olTe
[root@euve59329 ~]#

Inspired from Learning the bash Shell: Unix Shell Programming (In a Nutshell (O’Reilly))

String Manipulation and Expanding Variables

String Manipulation and Expanding Variables

For your ready references here are all your handy bash parameter substitution operators. Try them all; enhance your scripting skills like a pro:

${parameter:-defaultValue} Get default shell variables value
${parameter:=defaultValue} Set default shell variables value
${parameter:?”Error Message”} Display an error message if parameter is not set
${#var} Find the length of the string
${var%pattern} Remove from shortest rear (end) pattern
${var%%pattern} Remove from longest rear (end) pattern
${var:num1:num2} Substring
${var#pattern} Remove from shortest front pattern
${var##pattern} Remove from longest front pattern
${var/pattern/string} Find and replace (only replace first occurrence)
${var//pattern/string} Find and replace all occurrences
REFERENCES:

via http://www.cyberciti.biz/tips/bash-shell-parameter-substitution-2.html