Friday, May 16, 2014

How to check Ubuntu server Linux version

If you are a Windows user before, there is no ver command in Linux that can be used to check the version of Ubuntu server.  In  Linux  or  Ubuntu  server specifically, there are many commands that can be used to check operating system version.

The first command that can be used to check Ubuntu server version is, as Ubuntu suggest, the lsb_release -a command. Here is the example:

luzar@ubuntu:~$ lsb_release -a
No LSB modules are available.
Distributor ID: Ubuntu
Description:    Ubuntu 8.10
Release:        8.10
Codename:       intrepid
luzar@ubuntu:~$

Second command that we can use to check Linux version is cat /proc/version. See example below:

luzar@ubuntu:~$ cat /proc/version
Linux version 2.6.27-14-server (buildd@palmer) (gcc version 4.3.2 (Ubuntu 4.3.2-1ubuntu12) ) #1 SMP Wed Apr 15 19:44:38 UTC 2009
luzar@ubuntu:~$

We can also view all information about Ubuntu server using uname -a option:

luzar@ubuntu:~$ uname -a
Linux ubuntu 2.6.27-14-server #1 SMP Wed Apr 15 19:44:38 UTC 2009 i686 GNU/Linux

How to power off Ubuntu server with Linux shutdown command

The Linux shutdown command has several options that you can use to bring down the Linux system. In the previous post, we've seen how to reboot Ubuntu server with shutdown command. In this post,  we are going to use the Linux shutdown command again. This time is to power off the Ubuntu server.

There are several options available with shutdown command that can be used to power off Linux system. One example is -h option, which means to halt the system after it has been brought down. We can add other things such as a comment message when invoking shutdown -h command. As you can see from the example of Ubuntu restart post before, we have to specify a time argument after the shutdown option so the system know when to shutdown the system. Here are some examples on how to power off Ubuntu server using shutdown command with other things that you can do:

1) Using Linux shutdown command with -h option example:


luzar@ubuntu:~$ sudo shutdown -h now
[sudo] password for luzar:

Broadcast message from luzar@ubuntu
        (/dev/pts/0) at 11:32 ...

The system is going down for halt NOW!

The example above show a basic shutdown command used to power off Ubuntu server. We used '-h' option and a time argument 'now' which means to bring down the system after we press enter.

 2) Using Linux shutdown command -p option example:

luzar@ubuntu:~$ sudo shutdown -h -P +1

Broadcast message from luzar@ubuntu
        (/dev/pts/0) at 11:47 ...

The system is going down for power off IN ONE MINUTE! 

The example above shows the '-P' option is added after the '-h' option. The -P option means 'power off'. When -P is used after -h option, it means we tell the system to power off after the system halt. Also this time we used +1 in the time argument. That means we want to bring down the system after 1 minute.

3) If you have to warn all your users, you can write a message after the time argument. See the example below:

luzar@ubuntu:~$ sudo shutdown -h -P +3 Please save your work now!

Broadcast message from luzar@ubuntu
        (/dev/pts/0) at 11:57 ...

The system is going down for power off in 3 minutes!
Please save your work now!
shutdown: Shutdown cancelled

If you want to cancel shutdown after invoked the command, you can press Ctrl+C combination keys. That will work if you do not use the 'now' time argument. If you just want to warn users to log out and prevent other user to login without actually bring the system down, you can use '-k' option.

luzar@ubuntu:~$ sudo shutdown -k +3 Please save your work now!

Broadcast message from luzar@ubuntu
        (/dev/pts/0) at 12:11 ...

The system is going down for maintenance in 3 minutes!
Please save your work now!
luzar@ubuntu:~$

That's all.

How to mount external hard drive in Ubuntu server

This is a step by step guide on how to mount external hard drive in Linux for Ubuntu server beginner and Linux beginner in general. The guide includes error happened during the process to show how it to mount device in real situation.

Mount external hard drive in Ubuntu server

Insert external hard drive usb connector into the Ubuntu server usb port.  Ubuntu server automatically detect the external hard drive as a usb device. Below is the example screenshot when ubuntu detected the external hard drive:


 
We can see that the external hard drive has been detected as sdb. That is the name of the external hard drive to use when we are going to mount the device. We can check the device in /proc/scsi/scsi file. To do that, issue the command as in the example below:

luzar@ubuntu:~$ cat /proc/scsi/scsi
Attached devices:
Host: scsi1 Channel: 00 Id: 00 Lun: 00
  Vendor: NECVMWar Model: VMware IDE CDR10 Rev: 1.00
  Type:   CD-ROM                           ANSI  SCSI revision: 05
Host: scsi2 Channel: 00 Id: 00 Lun: 00
  Vendor: VMware,  Model: VMware Virtual S Rev: 1.0
  Type:   Direct-Access                    ANSI  SCSI revision: 02
Host: scsi3 Channel: 00 Id: 00 Lun: 00
  Vendor: Generic  Model: USB Disk         Rev: 9.02
  Type:   Direct-Access                    ANSI  SCSI revision: 02
luzar@ubuntu:~$

Create a proper directory in Ubuntu server to mount the external hard drive. In this example, we create a directory named extdisk in /mnt directory:

luzar@ubuntu:~$ sudo mkdir /mnt/extdisk
[sudo] password for luzar:
luzar@ubuntu:~$ ls /mnt/
dvd  extdisk  usb  win

Now we can mount the external hard drive with Linux mount command:

luzar@ubuntu:~$ sudo mount /dev/sdb /mnt/extdisk/
mount: you must specify the filesystem type

The external hard drive cannot be mounted. This happened when we mount a windows formatted external hard drive. We must specify the filesystem. Windows filesystem format is known as nsfs-3g in Linux. So we mount the external hard drive again with the complete command:

luzar@ubuntu:~$ sudo mount -t ntfs-3g /dev/sdb /mnt/extdisk/
NTFS signature is missing.
Failed to mount '/dev/sdb': Invalid argument
The device '/dev/sdb' doesn't have a valid NTFS.
Maybe you selected the wrong device? Or the whole disk instead of a
partition (e.g. /dev/hda, not /dev/hda1)? Or the other way around?

We still cannot mount the external hard drive. Again, we mount the external hard drive but this we change the device name from /dev/sdb to /dev/sdb1 as suggested by Ubuntu message above.

luzar@ubuntu:~$ sudo mount -t ntfs-3g /dev/sdb1 /mnt/extdisk/
luzar@ubuntu:~$ ls /mnt/extdisk/
ghost dell170l  ghost mimos  RECYCLER  System Volume Information
luzar@ubuntu:~$

We successfully mounted the external hard drive this time. Now that the external drive has been mounted, we can use it as other directory in Ubuntu.

To unmount the external hard drive, we can use the Linux umount command like in the example below:

luzar@ubuntu:~$ sudo umount /mnt/extdisk/
[sudo] password for luzar:
luzar@ubuntu:~$

That's all.

Ubuntu server mount usb drive

Ubuntu server automatically detect usb drive when you plug it in the usb port. Here is an example of how Ubuntu detected my usb drive or thumb drive when I plugged it:



Ubuntu automatically assign the usb drive as sdb. If your Ubuntu doesn't detect the usb drive, pull it out and try connect it again.

Before mount the usb drive, normally I would create a new directory called usb in /mnt to be a destination place for the mounted usb drive.
luzar@ubuntu:~$ sudo mkdir /mnt/usb 

You can mount it in /mnt if you want, it doesn't matter. I created a special directory for usb drive because sometimes I need to mount several file systems and devices, so I need a mount point for each of them.

The mount syntax is mount device destination. Don't forget the sudo command. Here is an example of Ubuntu server mount usb drive:
luzar@ubuntu:~$ sudo mount /dev/sdb1 /mnt/usb/
luzar@ubuntu:~$ ls /mnt/usb/
logo.png  usbthumbdrive.bmp
luzar@ubuntu:~$

That's it.

Thursday, May 15, 2014

Connect to Your Amazon EC2 Instance from Windows Using PuTTY

If you are running Windows from your local machine, you will need to install PuTTy and PuTTyGen since SSH is not built in. To connect to a Linux instance, you must retrieve the initial administrator password first, and then use it with Microsoft Remote Desktop. You'll need the contents of the private key file that you created (e.g., mykeypair.pem) in Step 5: Create a Key Pair.
To connect to your Amazon EC2 instance from a Windows machine
  1. Install PuTTy and PuTTyGen.
    1. Download and install PuTTy. A search on "download Putty" on Google returns a list of download sites. Be certain that you install both PuTTy and PuTTyGen, because you will need both of them.
  2. Convert the key pair using PuTTyGen. (For information on key pairs see Step 5: Create a Key Pair).
    1. Launch PuTTyGen and select Import Key from the Conversions menu.
    2. Browse for mykeypair.pem, and import the key.
    3. Click Save private key. Ignore the dialog box that asks if you want to do this without a passphrase. Save the key as mykeypair.ppk.
    4. Close PuTTyGen.
  3. Configure the SSH settings.
    1. Launch PuTTy, expand the SSH node, and click Auth.
    2. Enter the location for mykeypair.ppk.
  4. Modify the keepalive.
    1. In the PuTTy Configuration window, in the Category pane, click Connection.
    2. Type 60 in the Seconds between keepalives (0 to turn off) box. If you don't change this value, your session will time out.
  5. Save the session settings.
    1. In the PuTTy Configuration window, in the Category pane, click Session.
    2. Inside the Load, save, or delete a stored session box, click Default Settings, and click Save.
  6. Type the DNS address of your Amazon EC2 instance.
    1. Sign in to the AWS Management Console and open the Amazon EC2 console at https://console.aws.amazon.com/ec2/.
    2. Make sure US East (N. Virginia) is selected in the region selector of the navigation bar.
    3. In the navigation pane, click Instances.
    4. Select your running instance and note the public DNS address in the bottom pane.
    5. In the PuTTy Configuration window, click Sessions in the Category pane, and in the Host Name (or IP address) box, type <ec2-user@DNS address of your Amazon EC2 instance>.
      Note
      We put ec2-user in front of the DNS name because the username for the AMI is ec2-user.
    6. Click Open. When the PuTTY Security Alert dialog box appears, click Yes to confirm that the fingerprint is OK. The SSH PuTTY window will launch.
      Note
      The SSH fingerprint will eventually show up in the system log. You can use the SSH fingerprint as a comparison to protect against a man in the middle attack.
      Your screen should look similar to the following screen.
    7. Use the sudo service httpd start command to start the web server.
      sudo service httpd start
      Your screen should look similar to the following screen.

Access EC2 Linux box over ssh without .pem file

1. Login to your EC2 instance using your .pem file
ssh -i your_pem_file.pem ubuntu@ec2-________.compute-1.amazonaws.com
2. Create a new user that will access the instance using a password:
 $ sudo useradd -s /bin/bash -m -d /home/USERNAME  -g root USERNAME
where:
  • -s /bin/bash : use /bin/bash as the standard shell
  • -m -d /home/USERNAME : create a home directory at /home/USERNAME
  • -g root : add to group root
  • USERNAME : the username of the new user
3. Create a strong password for the new user:
$ sudo passwd USERNAME
Enter new UNIX password:
Retype new UNIX password:
4. Add user to sudoers file by using sudo visudo and add the following line:
USERNAME  ALL=(ALL:ALL) ALL
5. Enable password authentication by editing /etc/ssh/sshd_config: change PasswordAuthentication no to PasswordAuthentication yes
6. Restart ssh:
sudo /etc/init.d/ssh restart
Logout of your instance (exit) and try your new login without the .pem file:
$ ssh USERNAME@ec2-________.compute-1.amazonaws.com
USERNAME@ec2-________.compute-1.amazonaws.com's password:

Rsnapshot Backups Server


# rpm -ivh http://dl.fedoraproject.org/pub/epel/6/i386/epel-release-6-8.noarch.rpm
# yum install rsnapshot
# mkdir /etc/rsnapshot
# mkdir /srv/backups/snapshots
# mkdir /var/log/rsnapshot

Setting up SSH passwordless login

# ssh-keygen -t dsa
# cat ~/.ssh/id_dsa.pub | ssh root@remote_host "cat >> ~/.ssh/authorized_keys2"
# chmod 700 .ssh; chmod 400 .ssh/authorized_keys2

Configuring rsnapshot hosts

# vim /etc/rsnapshot/rsnapshot.conf
config_version 1.2
snapshot_root /srv/backups/snapshots/laptop/
cmd_cp /bin/cp
cmd_rm /bin/rm
cmd_rsync /usr/bin/rsync
cmd_ssh /usr/bin/ssh
cmd_logger /usr/bin/logger
cmd_du /usr/bin/du
interval daily 7
interval weekly 4
interval monthly 3
verbose 2
loglevel 4
logfile /var/log/rsnapshot/laptop.log
exclude_file /etc/rsnapshot/laptop.exclude
rsync_long_args --delete --numeric-ids --delete-excluded
lockfile /var/run/rsnapshot.pid
backup root@laptop:/ laptop/
backup_script /etc/rsnapshot/laptop.dump_databases.sh laptop_databases/

# rsnapshot configtest

Host .exclude file

# vim /etc/rsnapshot/laptop.exclude
+ /boot
+ /etc
+ /home
+ /opt
+ /root
+ /usr
+ /usr/java
+ /usr/local
- /usr/*
- /var/cache
+ /var
+ /srv
- /*

crontab

15 02 * * * /usr/bin/rsnapshot -c /etc/rsnapshot/rsnapshot.conf daily
15 03 * * Sun /usr/bin/rsnapshot -c /etc/rsnapshot/rsnapshot.conf weekly
30 03 1 * * /usr/bin/rsnapshot -c /etc/rsnapshot/rsnapshot.conf monthly
0 */4          * * *           root    /usr/bin/rsnapshot hourly 30 3   * * *           root    /usr/bin/rsnapshot daily 0  3   * * 1           root    /usr/bin/rsnapshot weekly 30 2   1 * *           root    /usr/bin/rsnapshot monthly


  • config_version 1.2 = Configuration file version
  • snapshot_root = Destination on where to store snapshots
  • cmd_cp = Path to copy command
  • cmd_rm = Path to remove command
  • cmd_rsync = Path to rsync
  • cmd_ssh = Path to SSH
  • cmd_logger = Path to shell command interface to syslog
  • cmd_du = Path to disk usage command
  • interval hourly = How many hourly backups to keep.
  • interval daily = How many daily backups to keep.
  • interval weekly = How many weekly backups to keep.
  • interval monthly = How many monthly backups to keep.
  • verbose = Self-explanatory
  • loglevel = Self-explanatory
  • logfile = Path to logfile
  • ssh_args = Optional SSH arguments, such as a different port (-p )
  • exclude_file = Path to the exclude file (will be explained in more detail)
  • rsync_long_args = Long arguments to pass to rsync
  • lockfile = Self-explanatory
  • backup = Full path to what to be backed up followed by relative path of placement.
  • backup_script = Full path to an executable script followed by relative path of placement.

How to send email alerts from Ubuntu Server using ssmtp


How to install ssmtp

Before we do anything else we should bring the Ubuntu Repository up to date. So, from a Putty Session or, if you've got a screen and keyboard attached to your server, then you can use the command line itself to type the following:
sudo apt-get update
You'll be prompted for a password. This is the password you created when you installed Ubuntu. Ubuntu tends to prompt for a password each time you issue a "sudo" command.
Next we can install the ssmtp package:
sudo apt-get install ssmtp

How to configure ssmtp

Now we've installed the package we need to configure it. I'm using my gmail account to handle all my emails but you can obviously use your favourite email address. Obviously you should alter the following to text suit your own setup:
Firstly, we'll configure the config file. I like to use vim which is a powerful but simple text editor (issue: sudo apt-get install vim if you don't have it installed already). So, let's edit the config file
sudo vim /etc/ssmtp/ssmtp.conf
This will open the config file for editing. Then press the [Insert] key once to switch into Insert Mode and edit the file as follows. I mask out the original lines using a # but you can simply edit them instead:
# Config file for sSMTP sendmail
#
# The person who gets all mail for userids < 1000
# Make this empty to disable rewriting.
#root=postmaster
root=MyEmailAddress@gmail.com

# The place where the mail goes. The actual machine name is required no
# MX records are consulted. Commonly mailhosts are named mail.domain.com
#mailhub=mail
mailhub=smtp.gmail.com:587
AuthUser=MyEmailAddress@gmail.com
AuthPass=MyPassword
UseTLS=YES
UseSTARTTLS=YES


# Where will the mail seem to come from?
#rewriteDomain=
rewriteDomain=gmail.com

# The full hostname
#hostname=MyMediaServer.home
hostname=MyEmailAddress@gmail.com

# Are users allowed to set their own From: address?
# YES - Allow the user to specify their own From: address
# NO - Use the system generated From: address
FromLineOverride=YES
Once you've finished editing the file press the [Esc] key once and type :wq to save and quit out of the file. If you make a mistake editing the file then issue :q! instead of :wq to abort your changes.

Adding reverse aliases

A reverse alias changes the "From" address. This means you can make the email appear as if it's from a different email address. I personally haven't done this but if it's something you'd like to do then edit the revaliases file as follows:
sudo vim /etc/ssmtp/revaliases
Then add a new line similar to this:
root:YourFromName@gmail.com:smtp.gmail.com:587

How to test you have configured ssmtp properly

Once you've configurd sSMTP it's time to try and send an email. The simplest way to do this is to run sSMTP in a terminal with a recipient email address. So:
ssmtp recipient_email@example.com
sSMTP will then wait for you to type your message, which needs to be formatted like this: