Home –  Tutorials
Category Archives: Tutorials

How to find Linux distribution name and version?

uname

unameSometimes we need to find out Linux distribution name and version of current installed Linux OS. Here is a tutorial addressing this problem.

There are three methods to find out Linux distribution and version:
1. /etc/*-release
2. lsb_release
3. /proc/version

Method 1: /etc/*-release

Issue following command to find out distro and version of installed Linux-

$ cat /etc/*-release

Sample output:

DISTRIB_ID=LinuxMint
DISTRIB_RELEASE=16
DISTRIB_CODENAME=petra
DISTRIB_DESCRIPTION="Linux Mint 16 Petra"
NAME="Ubuntu"
VERSION="13.10, Saucy Salamander"
ID=ubuntu
ID_LIKE=debian
PRETTY_NAME="Ubuntu 13.10"
VERSION_ID="13.10"
HOME_URL="http://www.ubuntu.com/"
SUPPORT_URL="http://help.ubuntu.com/"
BUG_REPORT_URL="http://bugs.launchpad.net/ubuntu/"

Method 2: lsb_release

lsb in lsb_release stands for Linux Standard Base

$ lsb_release -a

Sample output:

No LSB modules are available.
Distributor ID: LinuxMint
Description: Linux Mint 16 Petra
Release: 16
Codename: petra

Method 3: /proc/version

This command returns kernel version and gcc version which was used to build it.

$ cat /proc/version

Sample output:

Linux version 3.11.0-12-generic (buildd@allspice) (gcc version 4.8.1 (Ubuntu/Linaro 4.8.1-10ubuntu7) ) #19-Ubuntu SMP Wed Oct 9 16:20:46 UTC 2013

Another way to find kernel version:

This command returns kernel version of currently installed Linux OS.

$ uname -r

or

$ uname -mrs

Sample output:

Linux 3.11.0-12-generic x86_64

Thank you.

Setting up your Linux box to serve as a DHCP server or a DHCP client

DHCP is Dynamic Host Configuration Protocol. It is used to control vital networking parameters of hosts (running clients) with the help of a server. DHCP is backward compatible with BOOTP. For more information see RFC 2131 (old RFC 1541) and other. (See Internet Resources section at the end of the tutorial).

This tutorial covers both the DHCP _SERVER_ daemon as well as DHCP _CLIENT_ daemon. Most people need the client daemon which is used by workstations to obtain network information from a remote server. The server daemon is used by system administrators to distribute network information to clients so if you are just a regular user you need the _CLIENT_ daemon.

1. Client Setup

Currently there are three different DHCP client programs for Linux, dhcpcd, pump and dhclient. This tutorial deals primarily with dhcpcd.

1.1. Downloading the client daemon (dhcpcd)

Depending on your distribution you might have to download the DHCP client daemon. If you want to compile it from the source you package you need is called dhcpcd and the current version is 1.3.18. It is maintained by Sergei Viznyukand today it comes as a binary package with most distributions.

dhcpcd source can be downloaded from following location

ftp://ftp.phystech.com/pub/

Then follow the instructions below. They should be the same.

1.2. Slackware

You can download the latest copy of the DHCPcd from any Metalab mirror or following:

ftp://metalab.unc.edu/pub/Linux/system/network/daemons

ftp://ftp.phystech.com/pub/ (Primary site)

Download the latest version of dhcpcd.tar.gz.

Unpack it

tar -zxvf dhcpcd-1.3.18pl1.tar.gz

cd into the directory and make dhcpcd

cd dhcpcd-1.3.18pl1
make

Install it (you have to run the following command as root)

make install

This will create the directory /etc/dhcpc where DHCPcd will store the DHCP information and dhcpcd file will be copied into /usr/sbin.

In order to make the system initialize using DHCP during boot type:

cd /etc/rc.d
mv rc.inet1 rc.inet1.OLD

This will move the old network initialization script into rc.inet1.OLD. You now need to create the new rc.inet1 script. Following code is all you need:

#!/bin/sh
#
# rc.inet1 This shell script boots up the base INET system.
 
HOSTNAME=`cat /etc/HOSTNAME` #This is probably not necessary but I
#will leave it in anyways
 
# Attach the loopback device.
/sbin/ifconfig lo 127.0.0.1
/sbin/route add -net 127.0.0.0 netmask 255.0.0.0 lo
 
# IF YOU HAVE AN ETHERNET CONNECTION, use these lines below to configure the
# eth0 interface. If you're only using loopback or SLIP, don't include the
# rest of the lines in this file.
 
/usr/sbin/dhcpcd

Save it and reboot your computer.

When you are finished go the step 1.8.

1.3. RedHat 6.x and Mandrake 6.x

DHCPcd configuration under RedHat 6.0+ is really easy. All you need to do is start the Control Panel by typing control-panel.

  • Select “Network Configuration”
  • Click on Interfaces
  • Click Add
  • Select Ethernet

In the Edit Ethernet/Bus Interface select “Activate interface at boot time” as well as select “DHCP” as “Interface configuration protocol”

Please note that in RedHat 6.x Redhat as default includes a DHCP client called pump instead of above mentioned dhcpcd. CD-ROM does include dhcpcd RPM so if you have no luck with pump try with dhcpcd. After you install dhcpcd (e.g. rpm -i dhcpcd-1.3.17pl2-1.i386.rpm) you will have to make some changes (refer section 1.7).

Additional notes from Alexander Stevenson:

I had no luck with DHCPcd. What finally worked for me was “pump”, which comes with Linux Mandrake 6.0 (and so I assume it is included with RedHat as well). The command I used was:

pump -i eth0 -h hostname

It didn’t matter what “hostname” was, but without it the server would not respond.

I then changed the line in my /sbin/ifup script to reflect the change; the default version does not have the -h switch, and so didn’t work for me.

Basically, if you’re using linuxconf, and after setting the adapter to “DHCP” it still doesn’t work, try adding a “-h hostname” to the pump line in the /sbin/ifup script. My script now looks like this:

...
if [ -n "$PUMP" ]; then
echo -n "Determining IP information for $DEVICE..."
if /sbin/pump -i $DEVICE -h hostname; then
echo " done."
else
echo " failed."
exit 1
fi
else ...

Another more elegant way to add hostname field is provided by Aad van der Klaauw:

Currently i’m configuring a gateway system at home, needed to set the MAC address and use the ‘-h hostname’ workaround. So I decided to *not* change the script but to use the configure file. In my /etc/sysconfig/network-scripts/ifcfg-eth0 I have added the following

DEVICE="eth0"
MACADDR="00:11:22:33:44:55"
DHCP_HOSTNAME="trigger_for_terayon"

Which will survive upgrades, and is imho a “cleaner” way.

That is it. Reboot your machine or type /sbin/ifup eth0 on the command line.

1.4. RedHat 5.x

DHCPcd configuration under RedHat 5.0+ is really easy. All you need to do is start the Control Panel by typing control-panel.

  • Select “Network Configuration”
  • Click on Interfaces
  • Click Add
  • Select Ethernet
  • In the Edit Ethernet/Bus Interface select “Activate interface at boot time” as well as select “DHCP” as “Interface configuration protocol”

When you are finished go the step 1.8.

1.5. RedHat 4.x and Caldera OpenLinux 1.1/1.2

DHCPcd is included in the standard RedHat distribution as an RPM and you can find it on your distribution’s CD-ROM in RPMS directory or you can download it from:

ftp://ftp.redhat.com/pub/redhat/redhat-4.2/i386/RedHat/RPMS/dhcpcd-0.6-2.i386.rpm

Install it with rpm -i dhcpcd-0.6-2.i386.rpm.

Alternatively you can compile your own version by following the steps outlined in the Slackware.

The following information was provided to me by nothing.

Removed my static ip and name from /etc/resolv.conf. However, I did leave in the search line and my two nameserver lines (for some reason my dhcpcd never creates a /etc/dhcpc/resolv.conf, so I have to use a static /etc/resolv.conf).

In /etc/sysconfig/network I removed the HOSTNAME and GATEWAY entries. I left the other entries as is (NETWORKING, DOMAINNAME, GATEWAYDEV).

In /etc/sysconfig/network-scripts/ifcfg-eth0 I removed the IPADDR, NETMASK, NETWORK, and BROADCAST entries. I left DEVICE and ONBOOT as is. I changed the BOOTPROTO line to BOOTPROTO=dhcp.

Save the file. Reboot your computer.

When you are finished go the last step.

1.6. Debian

There is a deb package of DHCPcd (make sure it starts with dhcpcd) at:

http://ftp.debian.org/debian/dists/slink/main/binary-i386/net/

Or, follow the Slackware installation instructions at section 1.2.

To unpack the deb package type dpkg -i /where/ever/your/debian/packages/are/dhcpcd*deb.

It appears that there isn’t a need for any DHCPcd configuration because:

The dhcpcd package installs it’s startup script as usual for debian packages in /etc/init.d/package_name, here as /etc/init.d/dhcpcd, and links this to the various /etc/rc?.d/ directories.

The contents of the /etc/rc?.d/ dirs is then executed at boot time.

If you don’t reboot after installing you should consider starting the daemon manually: /etc/init.d/dhcpcd start.

When you are finished go the last step 1.8.

1.7. LinuxPPC and MkLinux

As of the “1999” (R5) release, Linuxppc is now almost completely compatible with Redhat 6, with one caveat (see below). In general the instructions are exactly the same as for the current release of RedHat 6.x and Mandrake 6.x (Step 1.3).

The remaining problem is that Redhat 6 uses the ‘pump’ client for dhcp by default, and ‘pump’ doesn’t work reliably in Linuxppc. To get around this, you should install the latest dhcpcd from Sergei Viznyuk, and then edit /sbin/ifup to use dhcpcd instead of pump.

Change

if [ "$BOOTPROTO" = bootp -o "$BOOTPROTO" = dhcp ]; then
PUMP=true
fi
 
if [ -n "$PUMP" ]; then

with

if [ "$BOOTPROTO" = bootp ]; then
echo " done."
else
echo " failed."
exit 1
fi
elif [ "$BOOTPROTO" = dhcp ]; then
echo -n "Determining IP information for $DEVICE..."
if /sbin/dhcpcd -d $DEVICE ; then
if [ -f /etc/dhcpc/dhcpcd-${DEVICE}.exe ]; then
/etc/dhcpc/dhcpcd-${DEVICE}.exe
fi

and a coresponding changes for ifdown. Change

if [ "$BOOTPROTO" = bootp -o "$BOOTPROTO" = dhcp ]; then
....
fi

with

if [ "$BOOTPROTO" = bootp ]; then
fi
 
if [ "$BOOTPROTO" = dhcp ]; then
if [ -f /var/run/dhcpcd-${DEVICE}.pid ]; then
kill `cat /var/run/dhcpcd-${DEVICE}.pid`
rm -f /var/run/dhcpcd-${DEVICE}.pid
fi
fi

A working ppc rpm for dhcpcd is included on the Linuxppc 1999 cd; a slightly later rpm is available in the contrib directory on ftp://ftp.linuxppc.org/. Sources, which compile out of the box in Linuxppc 1999, are available from ftp://ftp.phystech.com/pub/dhcpcd-1.3.17-pl9.tar.gz.

1.8. Tying it all together

After your machine reboots your network interface should be configured. Type: ifconfig.

You should get something like this:

lo Link encap:Local Loopback
inet addr:127.0.0.1 Bcast:127.255.255.255 Mask:255.0.0.0
UP BROADCAST LOOPBACK RUNNING MTU:3584 Metric:1
RX packets:302 errors:0 dropped:0 overruns:0 frame:0
TX packets:302 errors:0 dropped:0 overruns:0 carrier:0 coll:0
 
eth0 Link encap:Ethernet HWaddr 00:20:AF:EE:05:45
inet addr:24.128.53.102 Bcast:24.128.53.255 Mask:255.255.254.0
^^^^^^^^^^^^^^^^^^^^^^^
UP BROADCAST NOTRAILERS RUNNING MULTICAST MTU:1500 Metric:1
RX packets:24783 errors:1 dropped:1 overruns:0 frame:1
TX packets:11598 errors:0 dropped:0 overruns:0 carrier:0 coll:96
Interrupt:10 Base address:0x300

If you have some normal number under inet addr you are set. If you see 0.0.0.0 don’t despair, it is a temporary setting before dhcpcd acquires the IP address. If even after few minutes you are seeing 0.0.0.0 please check out Troubleshooting. DHCPcd is a daemon and will stay running as long as you have your machine on. Every three hours it will contact the DHCP server and try to renew the IP address lease. It will log all the messages in the syslog (on Slackware /var/adm/syslog, RedHat/OpenLinux /var/log/syslog).

One final thing. You need to specify your nameservers. There are two ways to do it, you can either ask your provider to provide you with the addresses of your name server and then put those in the /etc/resolv.conf or DHCPcd will obtain the list from the DHCP server and will build a resolv.conf in /etc/dhcpc.

I decided to use DHCPcd’s resolv.conf by doing the following:

Back up your old /etc/resolv.conf: mv /etc/resolv.conf /etc/resolv.conf.OLD

If directory /etc/dhcpc doesn’t exist create it: mkdir /etc/dhcpc

Make a link from /etc/dhcpc/resolv.conf to /etc/resolv.conf: ln -s /etc/dhcpc/resolv.conf /etc/resolv.conf

If that doesn’t work try this:

This last step I had to perform only because my dhcpcd doesn’t create an /etc/dhcpc/resolv.conf. In /etc/sysconfig/network-scripts/ifup I made the following changes (which are a very poor hack, but they work for me):

elif [ "$BOOTPROTO" = dhcp -a "$ISALIAS" = no ]; then
echo -n "Using DHCP for ${DEVICE}... "
/sbin/dhcpcd -c /etc/sysconfig/network-scripts/ifdhcpc-done ${DEVICE}
echo "echo \$$ > /var/run/dhcp-wait-${DEVICE}.pid; exec sleep 30" | sh
 
if [ -f /var/run/dhcp-wait-${DEVICE}.pid ]; then
^^^^
echo "failed."
exit 1

I changed to:

elif [ "$BOOTPROTO" = dhcp -a "$ISALIAS" = no ]; then
echo -n "Using DHCP for ${DEVICE}... "
/sbin/dhcpcd
echo "echo \$$ > /var/run/dhcp-wait-${DEVICE}.pid; exec sleep 30" | sh
 
if [ ! -f /var/run/dhcp-wait-${DEVICE}.pid ]; then
^^^^^^
echo "failed."
exit 1

Note: Notice the ! (bang) in if [ ! -f /var/run/dhcp-wait-${DEVICE}.pid ];

Now sit back and enjoy :-).

1.9. Various notes

Following step(s) are not necessary but might be useful to some people:

If you need network connectivity only occasionally you can start dhcpcd from the command line (you have to be root to do this) with: /usr/sbin/dhcpcd.

When you need to down (turn off) the network type /usr/sbin/dhcpcd -k.

1.10. Troubleshooting

If you have followed the steps outlined above and you are unable to access the network there are several possible explanations:

1.10.1. Your network card is not configured properly

During the boot up process your Linux will probe your network card and should say something along these lines:

eth0: 3c509 at 0x300 tag 1, 10baseT port, address 00 20 af ee 11 11, IRQ 10.
3c509.c:1.07 6/15/95 becker@cesdis.gsfc.nasa.gov

If a message like this doesn’t appear your ethernet card might not be recognized by your Linux system. If you have a generic ethernet card (a NE2000 clone) you should have received a disk with DOS utilities that you can use to set up the card. Try playing with IRQs until Linux recognizes your card (IRQ 9,10,12 are usually good).

1.10.2. Your DHCP server supports RFC 1541/My DHCP server is Windows NT

Try running dhcpcd by typing dhcpcd -r.

Use ifconfig to check if your network interface is configured (wait few seconds for the configuration process, initally it will say Inet.addr=0.0.0.0)

If this solves your problem add the “-r” flag to the boot up scripts, ie: instead of /sbin/dhcpcd you will have /sbin/dhcpcd -r.

For example under RedHat edit script /etc/sysconfig/network-scripts/ifup and change the following:

IFNAME=$[ {DEVICE} \
"/sbin/dhcpcd -r -c /etc/"- etc etc.
1.10.3. During bootup I get error message "Using DHCP for eth0 ... failed" but my system works fine.

You are most likely using RedHat and you haven’t followed instructions carefully :-). You are missing the ! (bang) in one of the if statements. Jump to 1.8 and check how to fix it.

1.10.4. My network works for few minutes and then stops responding

There are some reports of gated (gateway daemon) screwing up routing on Linux boxes which results in problem described above. Check if gated is running with: ps -auxww | grep gate.

If it is try removing it with RedHat’s RPM manager or removing the entry in /etc/rc.d/.

1.10.5. My ethernet card is recognized during boot up but I still get "NO DHCPOFFER" message in my logs. I also happen to have a PCMCIA ethernet card.

You need to make sure that you have the 10BaseT port (“phone” plug) on your network card activated. Best way to verify it is to check what kind of connector your card is configured for during bootup e.g.

eth0: 3c509 at 0x300 tag 1, 10baseT port, address 00 20 af ee 11 11, IRQ 10.
^^^^^^^^^^^^
3c509.c:1.07 6/15/95 becker@cesdis.gsfc.nasa.gov

I have received reports of laptop users having this kind of problems due to the PCMCIA utilities (specifically ifport) that would set the connector type to 10Base2 (thinnet). You have to make sure you use 10BaseT for your connection. If you are not reconfigure the card and restart the computer.

1.10.6. My DHCP client broadcasts requests but no one answers

On some systems, you need to include some hostname for your machine as part of the request. With dhcpcd, do this with dhcpcd -h foohost Probably the hostname wanted will be your account username on the network.

1.10.7. I have followed all the steps but still my machine is not able to connect

The cable modem will usually memorize the ethernet address of your network card so if you connect a new computer or switch network cards you will somehow have to “teach” your cable modem to recognize the new computer/card. Usually you can turn of the modem and bring it back up while computer is on or you will have to call tech support and tell them that you have changed a network card in the computer.

You have firewall rules (ipfwadm rules) that disallow port 67/68 traffic used by DHCP to distribute configuration info. Check your firewall rules carefully.

1.10.8. I have MediaOne Express service and I still can't connect.

It appears that MediaOne has been using adding some things to DHCP that shouldn’t be there. Supposedly this is not a problem anymore but if you experience outages check for these things. If you are (un)lucky to have Windows NT on your machine if you go into Event Viewer you will see a warning like this:

DHCP received an unknown option 067 of length 005. The raw option data is
given below.
 
0000: 62 61 73 69 63 basic

If this is the problem go to ftp://vanbuer.ddns.org/pub/ and either download a binary or get the source for the change.

1.11. Alternative DHCP client (ISC dhclient)

If you have not had success getting your Linux connection running with the dhcpcd you might want to try ISC dhclient. dhclient comes with the DHCP distribution from ISC which includes both a DHCP client and a DHCP server. Instructions on how to get and compile the DHCP distribution can be found here. When you are done with it please return to this section to configure the client.

With the current version of the DHCP client, you don’t actually need a dhclient.conf. All you have to do is invoke dhclient e.g.: /sbin/dhclient.

This will configure all broadcast interfaces. If this doesn’t work or you want to specify only one interface create a /etc/dhclient.conf file with this example configuration.

interface "eth0" {
send dhcp-client-identifier 1:xx:xx:xx:xx:xx:xx;
send dhcp-lease-time 86400;
}

Here we assume that the ethernet interface is eth0. If not change accordingly. Also replace xx:xx:xx:xx:xx with your ethernet address. This dhclient.conf makes the client look more like a Win95 client.

Continue reading…

Beginners guide to Linux directory structure

Have you ever looked in your / directory, you’ll see a lot of directories. Here we are presenting beginners guide to linux directory structure explaining what they mean and what are the contents of these directories.

Screenshot of contents of root directory:

linux directory structure

 

/

This is called root partition. All files and directories start with root partition. Write privileges under this directory are avaible with root user only. Not to confuse it with root user’s home directory, know the difference, “/” is root partition while root user’s home directory is “/root”.

/bin

This directory has binary executable files. Linux commands used in single user mode are found in this directory. It also holds commands that are used by all users. Examples: ls, ping, cp.

/sbin

Like /bin, /sbin also contains binary executable files but the commands held by this directory are used by system administrators with the prime purpose of system maintenance. Examples: iptables, reboot, fdisk.

/etc

It holds all the configuration files which are required by all programs. Shell scripts needed by programs to start or stop them are held by this very directory. Examples are /etc/resolv.conf, /etc/logrotate.conf

/dev

/dev contains device files. In Linux, everything is a file. Included are terminal device or usb or any other device connected to the computer. For example: /dev/usbmon0

/proc

All the system process information is held in /proc. It is a pseudo filesystem as it contains information about running processes. For an instance, /proc/ is the directory which holds information of the process with . It contains information about the system resources. /proc/uptime is one such directory.

/var

var denotes variable files. Those files are kept in this directory that are supposed to grow. Some of the files that reside in here are- /var/log (system log files), /var/lib (package files), /var/mail (emails), /var/spool (print queues), /var/tmp (temporary files that are needed across reboots).

/tmp

System generated and user generated temporary files are kept in this category. Important files should not be saved in here because contents of /tmp are flushed every time system boots.

/usr

/usr is the one that holds user programs. It contains documentations, libraries and source-code for all the second level applications. /usr/bin holds binaries for user programs. While looking for a binary after /bin also look in /usr/bin. Examples of binaries you mighht find in /usr/bin are awk, less, cc. Similarly binary files for system administrators are kept in /usr/sbin. Examples are cron, sshd, useradd. Libraries for /usr/bin and /usr/sbin are kept in /usr/lib. /usr/local holds user programs that a user installs from source.

/home

All user’s personal files are kept in their respective home directories.

/boot

This directory has boot loader files. While booting, files needed are found in /boot. Kernel initrd, grub and few more files reside in this directory.

/lib

Binaries located in /bin and /sbin are supported by library files kept in /lib. Library nomenclature goes like ld* or lib*.so.* . For example: ld-2.11.1.so

/opt

/opt is for add-on optional applications from individual vendors. All applications that are optional should be installed in /opt or any of its subdirectory.

/mnt

/mnt is our mount directory. It is the temporary mount location where where system administrators can mount temporary filesystems.

/media

It serves as the temporary mount point for removable devices. All removable devices are mounted in this directory. Example: /media/cdrom or /media/floppy.

/srv

srv denotes service. All the service related data used for servers is saved in this directory.

A complete fstab guide

Wherever you stand on your linux learning curve, you will have to deal with fstab one day or the other. Fstab file is edited to configure filesystems. The process is really easier if you are well versed with fstab file. Continue reading to know more about fstab and how things work.

Introduction to fstab

Every operating system has a file system table, in Linux fstab happens to be that file. Earlier in linux era, one had to manually mount any drives/files at specified locations with the help of “mount” command. Right after plugging in your device, they just didn’t show up on your desktop. They were meant to be mounted manually and then further processing was done. There existed (exists) a way through which it can be done automatically, fstab was the magic wand. Fstab is used to store configurations for different file systems and it contains what to do with them, i.e., what and where to mount.
This automatic mounting can be carried out in graphical style too with the help of a tool PySDM, it is explained here.

How does fstab file look like?

Fstab file is found at:

/etc/fstab

You can see your fstab file by executing following command:

# gedit /etc/fstab

Columns in fstab file are separated from each other by a “tab”. We will go through and explain each column in the order they appear.

File System

This is the screenshot of my fstab file:

All the fstab entries are starting with UUIDs. These UUIDs are assigned to file systems while formatting, these are considered ideal for selecting file systems while mounting as they do not and cannot be changed. This setup is best for home users but for an advanced user who wishes to use RAID in future or uses a network based device, you should pass. To get the UUID of a partition so that you can make an entry in fstab, use blkid .

Mount Point

The next section in fstab denotes mount point of that particular partition. All the sections are separated by a ‘tab’. While making an entry in fstab, a mount point is to be created before rebooting (as changes take effect after restarting).

 

Type

The next section is type of file system for that partition. Linux supports a variety of file systems, few might need some packages to be able to perform read/write on them. We are looking only over a few of them:

ext3 : Most of the systems these days have ext3 linux partitions. Older systems had ext2 type filesystems but now ext3 has replaced it for its advantages. Ext3 is journaled, that is, if the power goes off and system is not properly shut down, no data will be lost, therefore, no time wasted in disc checks.
Note: Some distros are shipping with ext4 as default.

swap : Name stands for itself. “Swap” partition is of type “swap”.

ntfs and vfat : You will find your pendrives in vfat format (also known as FAT32) and windows drives in ntfs format.

auto : When you find written “auto” in this column, it doesn’t signify type but automatic detection of filesystem type.

Options

This section of fstab contains mount options for partitions. This section can seem really confusing at first but knowing few them can get you through it. Popular ones are discussed here while rest can be checked on man page of mount .

auto/noauto

With auto , the partition will automatically be mounted on a system boot. You can prevent a partition from automounting on bootup by editing option to noauto in fstab file.

exec/noexec

It lets you choose whether the partition can execute binaries or not. For example, you can give a partition noexec which contains binaries and you don’t want them to execute.

ro/rw

ro is for read-only partition while rw denotes read-write partition. To be able to write on a partition, it should have rw option in fstab file.

user/nouser

With nouser as an option, only root has privilege of mounting a partition while user allows any non-root user to mount a partition. Many users find it annoying that they can’t mount a partition as a normal user, well, now you know that solution is to update your fstab file.

sync/async

It is responsible for files being written synchronously and asynchronously. In layman words, when you issue a “copy” command on a pendrive, writing process starts as soon as command is issued but this is not the case with internal hard drives. Write operations on hard disks are not synchronised, that is, writing might start long after command was issued. This is the reason for error “wait while changes are being wriiten”. This can also cause accidental data loss. If async is set, it might appear that files are successfully written but they might not be physically written.

defaults

It sets all the default options: rw, suid, dev, exec, auto, nouser, async.

dump

This is the fifth column in fstab file. It has zeros and ones as entries, zero is for false and one is for true . It is an old school method of backing up. Backup will be performed if option is “1”. In case of “0” option dump will ignore the partition.

fsck

fsck is short form for file system check. This makes the 6th column for fstab file. You will see 0,1 or 2 written in this section. “0” denotes that the partition will be skipped from checking. “1” is for partition which will be checked at booting time. These numbers are actually the sequence in which they will be checked. Root (/root) partition is always set at 1, partitions other than root which are supposed to be checked should be set at 2.

A complete ffmpeg tutorial

Introduction

ffmpeg is a very fast video and audio converter that can also grab from a live audio/video source. It can also convert between arbitrary sample rates and resize video on the fly with a high quality polyphase filter.

Installing ffmpeg

chankey@linuxstall:$ sudo apt-get install ffmpeg

Uses

Below are some tasks which you can perform using ffmpeg.

Getting information of a video

To get information of a video file use -i option as:

chankey@linuxstall:$ ffmpeg -i /path/videofile.avi

Making video from images

You can combine the images to make a video (like movie maker in windows) using ffmpeg as:

chankey@linuxstall:$ ffmpeg -f image2 -i image%d.jpg videofile.mpg

The above command will take all the images from the current directory (image1.jpg, image2.jpg, etc) and will join them to make a video file videofile.mpg.

Making images from video file

This is just opposite of the last step. This will take a video and will generate images from it.

chankey@linuxstall:$ ffmpeg -i videofile.mpg image%d.jpg

Encoding video for iPod/iPhone

Source file: s_videofile.avi
Audio codec: aac
Audio bitrate: 128 kb/s
Video codec: mpeg4
Video bitrate: 1200 kb/s
Video size: 320×180
Generated video: f_videofile.mp4

chankey@linuxstall:$ ffpmeg -i s_videofile.avi input -acodec aac -ab 128kb -vcodec mpeg4 -b 1200 kb -mbd 2 -flags +4mv+trell -aic 2 -cmp 2 -subcmp 2 -s 320*180 -title X f_videofile.mp4

Encoding video for PSP

Source : s_videofile.avi
Audio codec : aac
Audio bitrate : 32 kb/s
Video codec : xvid
Video bitrate : 1200 kb/s
Video size : 320×180
Generated video : f_videofile.mp4

chankey@linuxstall:$ ffmpeg -i s_videofile.avi -b 300 -s 320x240 -vcodec xvid -ab 32 -ar 24000 -acodec aac f_videofile.mp4

Video to Audio

You can extract the audio from a video file and save it as mp3 format.

chankey@linuxstall:$ ffmpeg -i s_videofile.avi -vn -ar 44100 -ac 2 -ab 192 -f mp3 soundfile.mp3

Source video : s_video.avi
Audio bitrate : 192kb/s
output format : mp3
Generated sound : soundfile.mp3

wav to mp3

chankey@linuxstall:$ ffmpeg -i s_audiofile.wav -acodec mp3 -ab 192k f_audiofile.mp3

avi to mpg

chankey@linuxstall:$ ffmpeg -i s_videofile.avi f_videofile.mpg

mpg to avi

chankey@linuxstall:$ ffmpeg -i s_videofile.mpg f_videofile.avi

avi to flv

chankey@linuxstall:$ ffmpeg -i s_videofile.avi -ab 56 -ar 44100 -b 200 -r 15 -s 320x240 -f flv f_videofile.flv

avi to dv

chankey@linuxstall:$ ffmpeg -i s_videofile.avi -s pal -r pal -aspect 4:3 -ar 48000 -ac 2 f_videofile.dv

avi to gif

chankey@linuxstall:$ ffmpeg -i s_videofile.avi f_giffile.gif

Mixing video with a sound file

chankey@linuxstall:$ ffmpeg -i s_audiofile.wav -i s_videofile.avi f_videofile.mpg

avi to mpeg (for dvd players)

chankey@linuxstall:$ ffmpeg -i s_videofile.avi -target pal-dvd -ps 2000000000 -aspect 16:9 f_videofile.mpeg

ps 2000000000 is the maximum size for the output file in bits hence it is 2 GB here.

Compress avi to divx

chankey@linuxstall:$ ffmpeg -i s_videofile.avi -s 320x240 -vcodec msmpeg4v2 f_videofile.avi

Compress Ogg Theora to mpeg dvd

chankey@linuxstall:$ ffmpeg -i s_videofile.ogm -s 720x576 -vcodec mpeg2video -acodec mp3 f_videofile.mpg

Compress avi to SVCD mpeg2

NTSC format:

chankey@linuxstall:$ ffmpeg -i s_videofile.avi -target ntsc-svcd f_videofile.mpg

PAL format:

chankey@linuxstall:$ ffmpeg -i s_videofile.avi -target pal-svcd f_videofile.mpg

Compress avi to VCD mpeg2

NTSC format:

chankey@linuxstall:$ ffmpeg -i s_videofile.avi -target ntsc-vcd f_videofile.mpg

PAL format:

chankey@linuxstall:$ ffmpeg -i s_videofile.avi -target pal-vcd f_videofile.mpg

Multipass encoding

chankey@linuxstall:$ ffmpeg -i fichierentree -pass 2 -passlogfile ffmpeg2pass fichiersortie-2

Protect your web server with SSL certificate

If you are a system administrator who is running a web server then you may want to protect it so that no one can hack into it and misuse the important data. Networks by themseleves are not secure enough, you will have to find other ways to make your server more secure. Here in this article we will examine ways in which you can help guard your important data.

Nowadays all the E-commerce applications (banking and online shopping for example) are encrypted using either SSL or TLS specifications. SSL stands for Secure Socket Layer and TLS means Transport Layer Security. Actually TLS is based on SSL 3.0 hence they are very similar in nature. For secure web connections first of all the SSL connection is established and then the HTTP communication is “tunneled” through it.

Note: Since name-based virtual hosting occurs at HTTP layer and as I said that SSL gets established before any HTTP communication, it causes problems with name-based virtual hosting. In short name-based virtual hosting does not work easily with SSL.

To verify the identities and for establishing session parameters along with a session key, asymmetric cryptography is used during connection establishment between an SSL client and SSL server. Then a symmetric encryption algorithm (DES or RC4) is used with the negotiated key to encrypt all the data which is being transmitted during the session. This means that asymmetric encryption (during the handshaking phase) provides safe communication whereas symmetric encryption works on the session data (for faster and more practical use).

For the client to verify the identity of the server, the server must have a private key and a certificate (which contains the public key and information about the server). The client also contains a public key, which it uses to verify the certificate of the server (matches public key of client with the public key of server which is mentioned in the certificate).

Certificates are generally digitally signed by third-party certificate authorities (CA) which have verified the identities of the requester and the validity of the requests to have the certificate signed. In most of the cases CA is a company which contacts with vendors of web browsers to have its own certificate installed and trusted by default client installations. Then certificate authorities earn by charging server operators for its services.

There are many commercial certificate authorities which differ in features, price but as people say “Price is not always an indication of quality“. VeriSign, InstantSSL and Thawte are some popular CAs.

Instead of going for certificate authorities you can create self-signed certificates, but those should be used only for testing if the number of people who will be accessing your server are less.

Another option is to run your own certificate authority but we are not going to cover that in this article.

Generating SSL keys

Delete the old key and certificate

chankey@linuxstall:$ rm /etc/pki/tls/private/localhost.key
chankey@linuxstall:$ rm /etc/pki/tls/certs/localhost.crt

Create your own key

chankey@linuxstall:$ cd /etc/pki/tls/certs
chankey@linuxstall:$ make genkey
umask 77 ; \
	/usr/bin/openssl genrsa -aes128 2048 > /etc/pki/tls/private/localhost.key
Generating RSA private key, 2048 bit long modulus
.................+++
.......................................................................................................................+++
e is 65537 (0x10001)
Enter pass phrase:
Verifying - Enter pass phrase:

Creating self-signed certificate

chankey@linuxstall:$ make testcert
umask 77 ; \
	/usr/bin/openssl req -utf8 -new -key /etc/pki/tls/private/localhost.key -x509 -days 365 -out /etc/pki/tls/certs/localhost.crt -set_serial 0
Enter pass phrase for /etc/pki/tls/private/localhost.key:
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Country Name (2 letter code) [XX]:IN
State or Province Name (full name) []:Rajasthan
Locality Name (eg, city) [Default City]:Jaipur
Organization Name (eg, company) [Default Company Ltd]:Linux Stall
Organizational Unit Name (eg, section) []:IT
Common Name (eg, your name or your server's hostname) []:www.linuxstall.com
Email Address []:admin@linuxstall.com

This is how it looked on my server:

ssl certificate linux

This will create a file localhost.crt in /etc/pki/tls/certs/. Now open the file ssl.conf which is located at /etc/httpd/conf.d/ and edit it with the content given below:

SSLCertificateFile /etc/pki/tls/certs/localhost.crt

Restart your web server

chankey@linuxstall:$ service httpd restart

Now you’re done. Open your browser and use httpd in front of each URL instead of http. You can ignore the certification validation message which your web browser may prompt.

Removing password encryption on private key

You will notice that whenever you restart your server it asks for certificate password. This is for security purpose so that no one can break into your server and steal your private key. You are safe in the knowledge that the private key is a jumbled mess. The cracker will not be able to make use of it but without such protection, a cracker could get your private key and easily masquerade as you, appearing to be legitimate in all cases.

If you are willing to accept the risk and cannot stand having to enter the password every time your server starts, you can remove the password encryption on private key by entering the command given below:

chankey@linuxstall:$ cd /etc/pki/tls/private
chankey@linuxstall:$ /usr/bin/openssl rsa -in localhost.key -out localhost.key
Enter pass phrase for localhost.key: *******

Now you will be able to restart the server without entering a pass phrase.

Troubleshooting

Following tips will help if you are having problems with your SSL certificate:

  • You should know that only one SSL certificate can be used for one IP. If you want to add more than one web site (SSL enabled) to your server, you must bind another IP address to the network interface.
  • Don’t block port 443 on your server. All https request come on port 443. If this port is blocked then you will not be able to get secure pages.
  • The certificate expires after one year. Don’t forget to renew your certificate with your CA before expiration.
  • mod_ssl package should be installed on your server. If it is not then you will not be able to serve any SSL-enabled traffic.

Reference in Perl

Reference in Perl

Introduction

References are the most important feature of Perl which helps in creating complex data structures. This tutorial is aimed for a complete newbie in Perl. We will start with What references are? What are their benefits? How to use them? Their syntax and examples. Wasting no more time just dive into it!

What is a reference?

If you are familiar with C language then you can consider a reference as a pointer (not literally, because there are no pointers in Perl like C language). A variable can store a reference to some variable/value/array or hash.

Reference to a variable

+----------\\       +----------\\
|     x     >      |     y     >
+----------/       +----------/
      |                  |
+-----------+      +-----------+
|     O-----+----->|   54321   |
+-----------+      +-----------+

Here the variable $x has a reference which points to the value of variable $y (which is 54321).

To create a reference to a value we use the backslash operator (\\). For example:

#!/usr/bin/perl
use warnings;
my $y = 54321;
my $x = \$y;     # $x is a reference to the value of variable $y.
print "$y\n";    # 54321
print "$x\n";    # will print the address where the value 54321 is stored like SCALAR(0x13dcac0)
print "${$x}\n"; # 54321 (dereferencing a scalar variable)
print "$$x";     # 54321 (same as above)

Reference to an array

@a		@{$aref}		# An array
reverse @a	reverse @{$aref}	# Reverse the array
$a[3]		${$aref}[3]		# An element of the array
$a[3] = 17;	${$aref}[3] = 17	# Assigning an element
+----------\\
|     x     >      +----------\\
+----------/       |     y     >
      |            +----------/
+-----------+            |
|     O-----+----->+###########+
+-----------+      +"""""""""""+
                   |    Foo    |
+----------\\       +-----------+
|     z     >      |    ABC    |
+----------/       +-----------+
      |            |    BUZ    |
+-----------+      +-----------+
|     O-----+----->|    VIZ    |
+-----------+      +-----------+

Here the refernce $x is pointing to the array @y, reference $z is pointing to the 4th element of array @y i.e. $y[4].

#!/usr/bin/perl
use warnings;
my @y = ("Foo", "ABC", "BUZ", "VIZ");
my $x = \\@y;         # creating reference of an array
print "$x\\n";        # ARRAY(0x189faf0)
print "@y\\n";        # Foo ABC BUZ VIZ
print "@{$x}\\n";     # Foo ABC BUZ VIZ (dereferencing)
print "@$x\\n";       # Foo ABC BUZ VIZ (You may omit curly brace here)
print "${$x}[1]\\n";  # ABC  (Accessing element at position 1 of array using reference variable)
print "$$x[1]\\n";    # ABC  (Another way of doing the same)
print "$x->[1]";     # ABC  (You can use -> operator too)

Reference to a hash

You can make a reference to hash in the similar way as you created from scalar variables and array.

%h		%{$href}	      # A hash
keys %h		keys %{$href}	      # Get the keys from the hash
$h{'red'}	${$href}{'red'}	      # An element of the hash
$h{'red'} = 17	${$href}{'red'} = 17  # Assigning an element

Loop over an array or hash using reference

If you want to loop over an array then

for my $element (@array) {
           ...
}

If you want to loop over an array using reference then

for my $element (@{$aref}) {
           ...
}

If you want to loop over a hash then

for my $key (keys %hash) {
          print "$key -> $hash{$key}\\n";
}

If you want to loop over a hash using reference then

for my $key (keys %{$href}) {
          print "$key => ${$href}{$key}\\n";
}

Tip

${$aref}[3] is too hard to read, so you can write $aref->[3] instead.
${$href}{red} is too hard to read, so you can write $href->{red} instead.

If $aref holds a reference to an array, then $aref->[3] is the fourth element of the array. Don’t confuse this with $aref[3], which is the fourth element of a totally different array, one deceptively named @aref. $aref and @aref are unrelated the same way that $item and @item are.

Similarly, $href->{‘red’} is part of the hash referred to by the scalar variable $href, perhaps even one with no name. $href{‘red’} is part of the deceptively named %href hash.

It’s easy to forget to leave out the ->, and if you do, you’ll get bizarre results when your program gets array and hash elements out of totally unexpected hashes and arrays that weren’t the ones you wanted to use.

 
With the help of references you can construct complex datastructures as:

1) A reference to a list containing references to several lists

+----------\\
|     x     >                      +-->+###########+
+----------/                       |   +"""""""""""+
      |                            |   |    Foo    |
+-----------+                      |   +-----------+
|     O-----+----->+###########+   |   |    ABC    |
+-----------+      +"""""""""""+   |   +-----------+
                   |     O-----+---+
                   +-----------+
                   |     O-----+------>+###########+
                   +-----------+       +"""""""""""+
                   |     O-----+---+   |    BUZ    |
                   +-----------+   |   +-----------+
                                   |   |    VIZ    |
                                   |   +-----------+
                                   |
                                   |
                                   +-->+###########+
                                       +"""""""""""+
                                       |    BUZ    |
                                       +-----------+

2) A hash containing references to lists

+----------\\
|     x     >                 +-->+###########+
+----------/                  |   +"""""""""""+
      |                       |   |    Foo    |
+#########################+   |   +-----------+
+"""""""""""""""""""""""""+   |   |    ABC    |
+-----------\\ +-----------+   |   +-----------+
|    aaa     >|     O-----+---+
+-----------< +-----------+
|    bbb     >|     O-----+------>+###########+
+-----------< +-----------+       +"""""""""""+
|    ccc     >|     O-----+---+   |    BUZ    |
+-----------/ +-----------+   |   +-----------+
                              |   |    VIZ    |
                              |   +-----------+
                              |
                              |
                              +-->+###########+
                                  +"""""""""""+
                                  |    BUZ    |
                                  +-----------+

Creating reference to an anonymous array

To create an anonymous array [ ] brackets are used. For example:

$x = [1, 2, 3];

Here $x is a reference to an anonymous array.

Creating reference to an anonymous hash

To create an anonymous hash curly braces { } are used. For example:

$x = {Name => 'Chankey', Email => 'chankey007@gmail.com'};

Creating reference to an anonymous subroutine

For this just assign subroutine to a scalar variable (reference variable in our case).

$x = sub { print "Welcome to Linux Stall\n" };

Some notations

Consider the example given below

@a = ( [1, 2, 3],
               [4, 5, 6],
	       [7, 8, 9]
);

@a is an array with three elements, and each one is a reference to another array. $a[1] is one of these references. It refers to an array, the array containing (4, 5, 6), and because it is a reference to an array, we can write $a[1]->[2] to get the third element from that array. $a[1]->[2] is the 6. Similarly, $a[0]->[1] is the 2. What we have here is like a two-dimensional array; you can write $a[ROW]->[COLUMN] to get or set the element in any row and any column of the array.

The notation still looks a little cumbersome, so there’s one more abbreviation:

In between two subscripts, the arrow is optional i.e. instead of $a[1]->[2], we can write $a[1][2]; it means the same thing. Instead of $a[0]->[1] = 23, we can write $a[0][1] = 23 ; it means the same thing. Now it really looks like two-dimensional arrays! You can see why the arrows are important. Without them, we would have had to write ${$a[1]}[2] instead of $a[1][2]. For three-dimensional arrays, they let us write $x[2][3][5] instead of the unreadable ${${$x[2]}[3]}[5].

This is all what a newbie should know about reference in Perl.

How to read a CSV file in Perl?

read csv file perl

read csv file perl

Perl is used for manipulating text files and in this article I will teach how to read a CSV file in Perl? First of all let’s start with

What is a CSV file?

A comma-separated values (CSV) file stores tabular data (numbers and text) in plain-text form. As a result, such a file is easily human-readable (e.g., in a text editor).

CSV is a simple file format that is widely supported by consumer, business, and scientific applications. Among its most common uses is to move tabular data between programs that naturally operate on a more efficient or complete proprietary format. For example: a CSV file might be used to transfer information from a database program to a spreadsheet. -Wikipedia

Using Perl to read a CSV file

Now suppose we have a CSV file which has 4 rows and each row has fields which are separated by comma as given below:

Linux,Unix,1,Ubuntu
RHEL,Kubuntu,2,Fedora
Mint,Puppy,3,ArchLinux
Mandriva,OpenSUSE,4,CentOS

If you want to extract out the data from 3rd column and calculate the sum of all the numbers then the approach to do this will be as follows:

Read the first line of the CSV file and extract out the 3rd column. Assign the extracted value to a scalar variable and then read the next line, extract out the value of 3rd column, add it to the scalar variable which contains the first value and store result in the same variable. Then read the 3rd line and so on…

Below is the Perl code for this purpose using split function.

  #!/usr/bin/perl
  use strict;
  use warnings;
 
  my $filename = $ARGV[0];
  my $total = 0;
 
  open(my $FH, '<', $filename) or die "Couldn't open $filename $!";
 
  while (my $fetchline = <$FH>){
    chomp $fetchline;
    my @elements = split "," , $fetchline;
    $total += $elements[2];
  }
 
  print "$total\n";

Save the file as text.plx and if the CSV file name is filename.csv then you may run the code as

$ perl text.plx filename.csv

In this case we get 10 (1+2+3+4) as output.

In this article we used split function to extract out the columns from CSV file using comma (,) as separator. But this code is error prone because of 2 reasons.

Reason 1: If the filename.csv contains something like

Linux,Unix,1,Ubuntu
RHEL,Kubuntu,2,Fedora
Mint,"Puppy,Linux",3,ArchLinux
Mandriva,OpenSUSE,4,CentOS

Notice the 3rd row. The 2nd field of it has a comma “Puppy,Linux”. If we use the same approach of splitting fields by comma separator then it will throw an error because split function will split out Puppy and Linux since they are separated by a comma. Then it will do something like 1+2+Linux+4 which is wrong.

Reason 2: If the filename.csv contains something like

Linux,Unix,1,Ubuntu
RHEL,Kubuntu,2,Fedora
Mint,"Puppy,
Linux",3,ArchLinux
Mandriva,OpenSUSE,4,CentOS

Here the 3rd row contains multi-line fields. When the above code will be used it will treat the CSV file as it contains 5 lines instead of 4.

So we can conclude that if the CSV file is in good format AND if it does not contain field separators within quote AND if there are no multi-line fields in CSV file then our code (which we have written above) will work perfectly and will give correct result. Take use of Text::CSV_XS module which is used for reading and writing CSV files, it will deal with those error prone situations very efficiently.

Types of Filesystem, differences and dealing with them using Perl

If you are looking to write code in Perl which will work on multiple platforms then you must have the knowledge of filesystem of each platform. Filesystems are categoriesed in 3 parts.

1. Filesystem of Unix

FFS (Berkeley Fast File System) is the ancestor of all current filesystems of Unix variants. The filesystem has been extended by different vendors according to their needs. Like for better security they have been extended to provide support for POSIX ACL (access control list).

In Unix filesystem the root is denoted by / (forward slash). The path of any directory in Unix filesystem starts from / and goes deeper in the system. The directory names or file names in Unix filesystem are case-sensitive.

Path Example: /root/home/user/Desktop/file.txt

2. Filesystem of Windows

Operating systems which are based on Windows supports 3 filesystems: FAT (File Allocation Table), NTFS (NT FileSystem), FAT32 (Advance version of FAT).

FAT filesystem is not case-sensitive. It uses \\ (backward slash) as path separator. In the FAT systems the direcotries and files contains some flags, these flags are known as attributes like “Read Only”. NTFS supports unicode feature.

Path Example: C:\\home\\user\\Desktop\\file.txt

3. Filesystem of Mac OS

Classic Mac OS used HFS (Hierarchical File System). The version 8.1 of Mac OS uses HFS+ which is an advance version of HFS. The current filesystem looks similar to Unix filesystem. The method of showing paths is same in both OS. The difference between these is that Unix file system is case-sensitive whereas HFS+ is not case-sensitive.

Summary

OS and FileSystem Path Separator Filename length Absolute path format Relative path format Unique features
Unix (Berkeley FFS and others) / OS-dependent number of chars /dir/file dir/file OS-variant dependent additions
Mac OS (HFS+) / 255 Unicode chars /dir/file dir/file Mac OS legacy support, BSD extended attributes
Windows based OS (NTFS) \\ 255 Unicode chars Drive:\\dir\\file dir\\file File encryption and compression
DOS (basic FAT) \\ 8.3 Drive:\\dir\\file dir\\file Attributes

 

Using Perl to deal with different Filesystems

By now we know all the filesystems differ from each other and to deal with these in Perl we use File::Spec module. This module is used to hide the differences between these filesystems. Let us learn how we use this module. We will use the catfile method to get the path of the file.

Example:

use File::Spec;
my $path= File::Spec->catfile(qw{home user Desktop file.txt});

In this way the scalar variable $path get sets to home\user\desktop\file.txt in a Windows operating system. and in Unix based system it gets set to home/user/Desktop/file.txt. The File::Spec module also contains methods like curdir and updir to get the current directory (.) and up-directory (..).

You may also use the moudle Path::Class which is an another good wrapper. You will have to install it before using.

Below is an example of how it works:

use Path::Class;
my $file = file (qw{home user Desktop file.txt});
my $dir = file (qw{home user Desktop});

The $file and $dir are scalar variable which contains the path to the file.txt file and Desktop directory respectively.

Here’s the path

print $file;
print $dir;

The output will depend on operating system. If it is Unix then it will yield

home/user/desktop/file.txt and home//user//desktop

and in Windows based systems it will give

home\\user\\desktop\\file.txt and home\\user\\desktop

Here $file and $dir are objects which have several methods which can be applied on them for some use. Like absoulte method gives the absolute path and slurp method slurps through the file’s contents.

my $abspath = $file->absolute;
my $content = $file->slurp;
$file->remove(); #delete the file

When you want to write a code for a particular system and you want to make this system understand the path of other operating system then you may use foreign_file() and foreign_dir() methods. These will return the path based the argument which you have to specify explicitly.

use Path::Class qw(foreign_file foreign_dir);
my $foreignfile = foreign_file('Win32', qw{home user Desktop file.txt});
my $foreigndir = foreign_dir('Win32', qw{home user});

Now $foreignfile will contain home\\user\\desktop\\file.txt even if the code is run from a Unix based system. This approach is very handy and useful. In the next article we will continue and expand our discussion.

Understanding file permissions and access rights in Linux

In Linux everything is a file. To set access rights on the specific files we use chmod command. To see what are the access rights/ permissions of a specific file we use ls -l command. Below we will learn how to see permission of a file and change it.

Note: To change permissions of a file you must be login as root user.

Suppose you have a file named as linuxstall.txt in a directory named as LinuxStall which is in /tmp. Use ls -l command to see its permissions as:

ls -l /tmp/LinuxStall/linuxstall.txt

The output will be as

-rwxr--r--. 1 root root 0 Jan 5 15:39 /tmp/LinuxStall/linuxstall.txt

Let us first understand what does the above line means by breaking it down in different parts.

The left most bit can be of two types either d or .
If it is d then it means that it is a directory.
If it is then it means that it is a file.

Here in our example it is means it is a file.

Part 1: r w x (Shows owner’s access rights)
Explanation:
First bit is which means it is a file, if it is d then it means it is directory.
First bit is r which means read i.e the owner can open this file.
Second bit is w which means write i.e the owner can edit this file.
Third bit is x which means execute i.e the owner can execute this file.

Part 2: r – – (shows group’s access rights)
Explanation:
First bit is r which means read i.e the group members can open this file.
Second bit is which means group members can not edit this file.
Third bit is which means group members can not execute this file.

Part 3: r – – (shows other users which are neither owner nor group members)
Explanation:
First bit is r which means read i.e the other users can open this file.
Second bit is which means other users can not edit this file.
Third bit is which means other users can not execute this file.

 

Changing file permission using chmod command

chmod stands for change file mode bits

There are two methods of changing file permission using chmod command.

Syntax: chmod permission path_of_file

Method 1: Numerical Method

In this method we use numeric bits which corresponds to r w x. The numeric values for these are

r = 4, w = 2, x = 1

chmod 444 /tmp/LinuxStall/linuxstall.txt

will change the file permission of file linuxstall.txt to

-r – – r – – r – – which means owner, group, others can only read this file.

chmod 555 /tmp/LinuxStall/linuxstall.txt

will change the file permissions of file linuxstall.txt to

-r – x r – x r – x which means owner, group, other can read and execute the file.

chmod 666 /tmp/LinuxStall/linuxstall.txt

will change the file permissions of file linuxstall.txt to

-r w – r w – r w – which means owner, group, other can read and edit the file.

chmod 644 /tmp/LinuxStall/linuxstall.txt

will change the file permissions of file linuxstall.txt to

-r w – r – – r – – which means owner can read and edit the file, group and other can only read the file.

Hence we saw that first numeric bit is for owner, second numeric bit is for group and third one is for other users. You can set the numeric bits to 1,2,4 for execute, write and read purpose respectively.

Method 2: Alphabetical Method

There are 4 alphabets associated with it, they are u,g,o and a.

u stands for owner

g stands for group

o stands for others

a stands for all

To add permission we use + and to remove permission we use

Example 1: To grant read permission to all group users

chmod g+r /tmp/LinuxStall/linuxstall.txt

Example 2: To remove read permission from group users

chmod g-r /tmp/LinuxStall/linuxstall.txt

Example 3: To grant read,write,execute permission to owner

chmod u+rwx /tmp/LinuxStall/linuxstall.txt

Example 4: To remove execute permission from other users

chmod o-x /tmp/LinuxStall/linuxstall.txt

Example 5: To grant read and write permission to all users

chmod a+rw /tmp/LinuxStall/linuxstall.txt

Noticed use of a? It sets permission for all users.

 

Conclusion: We saw that each file in Linux has access rights associated with it. It is divided in 3 parts, one is owner, second is group users and third are other users. We can use chmod command to change the file permission. There are two methods, one is numerical and other is alphabetical method. Numerical method of setting permission is preferred though.