Thursday, December 31, 2015

8 Tips to Solve Linux & Unix Systems Hard Disk Problems Like Disk Full Or Can’t Write to the Disk

Can't write to the hard disk on a Linux or Unix-like systems? Want to diagnose corrupt disk issues on a server? Want to find out why you are getting "disk full" messages on screen? Want to learn how to solve full/corrupt and failed disk issues. Try these eight tips to diagnose a Linux and Unix server hard disk drive problems.



1 - Error: No space left on device

When the Disk is full on Unix-like system you get an error message on screen. In this example, I'm running fallocate command and my system run out of disk space:
$ fallocate -l 1G test4.img
fallocate: test4.img: fallocate failed: No space left on device
The first step is to run the df command to find out information about total space and available space on a file system including partitions:
$ df
OR try human readable output format:
$ df -h
Sample outputs:
Filesystem      Size  Used Avail Use% Mounted on
/dev/sda6       117G   54G   57G  49% /
udev            993M  4.0K  993M   1% /dev
tmpfs           201M  264K  200M   1% /run
none            5.0M     0  5.0M   0% /run/lock
none           1002M     0 1002M   0% /run/shm
/dev/sda1       1.8G  115M  1.6G   7% /boot
/dev/sda7       4.7G  145M  4.4G   4% /tmp
/dev/sda9       9.4G  628M  8.3G   7% /var
/dev/sda8        94G  579M   89G   1% /ftpusers
/dev/sda10      4.0G  4.0G     0 100% /ftpusers/tmp
From the df command output it is clear that /dev/sda10 has 4.0Gb of total space of which 4.0Gb is used.

Fixing problem when the disk is full

  1. Compress uncompressed log and other files using gzip or bzip2 or tar command:
    gzip /ftpusers/tmp/*.log
    bzip2 /ftpusers/tmp/large.file.name
  2. Delete unwanted files using rm command on a Unix-like system:
     rm -rf /ftpusers/tmp/*.bmp
  3. Move files to other system or external hard disk using rsync command:
    rsync --remove-source-files -azv /ftpusers/tmp/*.mov /mnt/usbdisk/
    rsync --remove-source-files -azv /ftpusers/tmp/*.mov server2:/path/to/dest/dir/
  4. Find out the largest directories or files eating disk space on a Unix-like systesm:
    du -a /ftpusers/tmp | sort -n -r | head -n 10
    du -cks * | sort -rn | head
  5. Truncate a particular file. This is useful for log file:
    truncate -s 0 /ftpusers/ftp.upload.log
    ### bash/sh etc ##
    >/ftpusers/ftp.upload.log
    ## perl ##
    perl -e'truncate "filename", LENGTH'
  6. Find and remove large files that are open but have been deleted on Linux or Unix:
    ## Works on Linux/Unix/OSX/BSD etc ##
    lsof -nP | grep '(deleted)'
     
    ## Only works on Linux ##
    find /proc/*/fd -ls | grep  '(deleted)'
    To truncate it:
     ## works on Linux/Unix/BSD/OSX etc all ##
    > "/path/to/the/deleted/file.name"
    ## works on Linux only ##
    > "/proc/PID-HERE/fd/FD-HERE" 

2 - Is the file system is in read-only mode?

You may end up getting an error such as follows when you try to create a file or save a file:
cat > file
-bash: file: Read-only file system

Run mount command to find out if the file system is mounted in read-only mode:
$ mount
$ mount | grep '/ftpusers'

To fix this problem, simply remount the file system in read-write mode on a Linux based system:
# mount -o remount,rw /ftpusers/tmp
Another example, server to remount / in rw mode:
# mount -o rw /dev/ad0s1a /

3 - Am I running out of inodes?

Sometimes, df command reports that there is enough free space but system claims file-system is full. You need to check for the inode which identifies the file and its attributes on a file systems using the following command:
$ df -i
$ df -i /ftpusers/

Sample outputs:
Filesystem      Inodes IUsed   IFree IUse% Mounted on
/dev/sda8      6250496 11568 6238928    1% /ftpusers
So /ftpusers has 62,50,496 total inodes but only 11,568 are used. You are free to create another 62,38,928 files on /ftpusers partition. If 100% of your inodes are used, try the following options:
  • Find unwanted files and delete or move to another server.
  • Find unwanted large files and delete or move to another server.

4 - Is my hard drive is dying?

I/O errors in log file (such as /var/log/messages) indicates that something is wrong with the hard disk and it may be failing. You can check hard disk for errors using smartctl command, which is control and monitor utility for SMART disks under Linux and UNIX like operating systems. The syntax is:
smartctl -a /dev/DEVICE
# check for /dev/sda on a Linux server
smartctl -a /dev/sda
 
You can also use "Disk Utility" to get the same information
Fig. 01: Gnome disk utility (Applications > System Tools > Disk Utility)

Note: Don't expect too much from SMART tool. It may not work in some cases. Make backup on a regular basis.

5 - Is my hard drive and server is too hot?

High temperatures can cause server to function poorly. So you need to maintain the proper temperature of the server and disk. High temperatures can result into server shutdown or damage to file system and disk. Use hddtemp or smartctl utility to find out the temperature of your hard on a Linux or Unix based system by reading data from S.M.A.R.T. on drives that support this feature. Only modern hard drives have a temperature sensor. hddtemp supports reading S.M.A.R.T. information from SCSI drives too. hddtemp can work as simple command line tool or as a daemon to get information from all servers: 
hddtemp /dev/DISK
hddtemp /dev/sg0

You can use the smartctl command as follows too: 
smartctl -d ata -A /dev/sda | grep -i temperature
 

How do I get the CPU temperature?

You can use Linux hardware monitoring tool such as lm_sensor to get the cpu temperature on a Linux based system:

6 - Dealing with corrupted file systems
File system on server may be get corrupted due to a hard reboot or some other error such as bad blocks. You can repair corrupted file systems with the following fsck command:
umount /ftpusers
fsck -y /dev/sda8
 
7 - Dealing with software RAID on a Linux
To find the current status of a Linux software raid type the following command:
 ## get detail on /dev/md0 raid ##
mdadm --detail /dev/md0
 
## Find status ##
cat /proc/mdstat
watch cat /proc/mdstat
 
Sample outputs:
Fig. 04: Find the status of a Linux software raid command


You need to replace a failed hard drive. You must u remove the correct failed drive. In this example, I'm going to replace /dev/sdb (2nd hard drive of RAID 6). It is not necessary to take the storage offline to repair the RAID on Linux. This only works if your server support hot-swappable hard disk:
## remove disk from an array md0 ##
mdadm --manage /dev/md0 --fail /dev/sdb1
mdadm --manage /dev/md0 --remove /dev/sdb1
 
# Do the same steps again for rest of /dev/sdbX ##
# Power down if not hot-swappable hard disk: ##
shutdown -h now
 
## copy partition table from /dev/sda to newly replaced /dev/sdb ##
sfdisk -d /dev/sda | sfdisk /dev/sdb
fdisk -l
 
## Add it ##
mdadm --manage /dev/md0 --add /dev/sdb1
# do the same steps again for rest of /dev/sdbX ##
 
# Now md0 will sync again. See it on screen ## 
watch cat /proc/mdstat
 
8 - Dealing with hardware RAID
You can use the samrtctl command or vendor specific command to find out the status of RAID and disks in your controller: 
## SCSI disk 
smartctl -d scsi --all /dev/sgX
 
## Adaptec RAID array
/usr/StorMan/arcconf getconfig 1
 
## 3ware RAID Array
tw_cli /c0 show
 

20 Unix Command Line Tricks

Let us start new year with these Unix command line tricks to increase productivity at the Terminal. I have found them over the years and I'm now going to share with you.

Deleting a HUGE file

I had a huge log file 200GB I need to delete on a production web server. My rm and ls command was crashed and I was afraid that the system to a crawl with huge disk I/O load. To remove a HUGE file, enter:
> /path/to/file.log
# or use the following syntax
: > /path/to/file.log
 
# finally delete it 
rm /path/to/file.log
 

Want to cache console output?

Try the script command line utility to create a typescript of everything printed on your terminal.
script my.terminal.session
Type commands:
ls
date
sudo service foo stop
To exit (to end script session) type exit or logout or press control-D
exit
To view type:
more my.terminal.session
less my.terminal.session
cat my.terminal.session
 

Restoring deleted /tmp folder

As my journey continues with Linux and Unix shell, I made a few mistakes. I accidentally deleted /tmp folder. To restore it all you have to do is:
mkdir /tmp
chmod 1777 /tmp
chown root:root /tmp
ls -ld /tmp

Locking a directory

For privacy of my data I wanted to lock down /downloads on my file server. So I ran:
chmod 0000 /downloads
The root user can still has access and ls and cd commands will not work. To go back:
chmod 0755 /downloads

Password protecting file in vim text editor

Afraid that root user or someone may snoop into your personal text files? Try password protection to a file in vim, type: 
vim +X filename
 
Or, before quitting in vim use :X vim command to encrypt your file and 
vim will prompt for a password.


Clear gibberish all over the screen

Just type:
 
reset

Becoming human

Pass the -h or -H (and other options) command line option to GNU or BSD utilities to get output of command commands like ls, df, du, in human-understandable formats:
 
ls -lh
# print sizes in human readable format (e.g., 1K 234M 2G)
df -h
df -k
# show output in bytes, KB, MB, or GB
free -b
free -k
free -m
free -g
# print sizes in human readable format (e.g., 1K 234M 2G)
du -h
# get file system perms in human readable format
stat -c %A /boot
# compare human readable numbers
sort -h -a file
# display the CPU information in human readable format on a Linux
lscpu
lscpu -e
lscpu -e=cpu,node
# Show the  size of each file but in a more human readable way
tree -h
tree -h /boot
 

Show information about known users in the Linux based system

Just type:
## linux version ##
lslogins
 
## BSD version ##
logins
 
Sample outputs:
UID USER      PWD-LOCK PWD-DENY LAST-LOGIN GECOS
  0 root             0        0   22:37:59 root
  1 bin              0        1            bin
  2 daemon           0        1            daemon
  3 adm              0        1            adm
  4 lp               0        1            lp
  5 sync             0        1            sync
  6 shutdown         0        1 2014-Dec17 shutdown
  7 halt             0        1            halt
  8 mail             0        1            mail
 10 uucp             0        1            uucp
 11 operator         0        1            operator
 12 games            0        1            games
 13 gopher           0        1            gopher
 14 ftp              0        1            FTP User
 27 mysql            0        1            MySQL Server
 38 ntp              0        1
 48 apache           0        1            Apache
 68 haldaemon        0        1            HAL daemon
 69 vcsa             0        1            virtual console memory owner
 72 tcpdump          0        1
 74 sshd             0        1            Privilege-separated SSH
 81 dbus             0        1            System message bus
 89 postfix          0        1
 99 nobody           0        1            Nobody
173 abrt             0        1
497 vnstat           0        1            vnStat user
498 nginx            0        1            nginx user
499 saslauth         0        1            "Saslauthd user"

How do I fix mess created by accidentally untarred files in the current dir?

So I accidentally untar a tarball in /var/www/html/ directory instead of /home/projects/www/current. It created mess in /var/www/html/. The easiest way to fix this mess:
 
cd /var/www/html/
/bin/rm -f "$(tar ztf /path/to/file.tar.gz)"
 

Confused on a top command output?

Seriously, you need to try out htop instead of top:
sudo htop

Want to run the same command again?

Just type !!. For example:
 
/myhome/dir/script/name arg1 arg2
 
# To run the same command again 
!!
 
## To run the last command again as root user
sudo !!
 
The !! repeats the most recent command. To run the most recent command beginning with "foo":
!foo
# Run the most recent command beginning with "service" as root
sudo !service
The !$ use to run command with the last argument of the most recent command:
# Edit nginx.conf
sudo vi /etc/nginx/nginx.conf
 
# Test nginx.conf for errors
/sbin/nginx -t -c /etc/nginx/nginx.conf
 
# After testing a file with "/sbin/nginx -t -c /etc/nginx/nginx.conf", you
# can edit file again with vi
sudo vi !$

Get a reminder you when you have to leave

If you need a reminder to leave your terminal, type the following command:
 
leave +hhmm
 
Where,
  • hhmm - The time of day is in the form hhmm where hh is a time in hours (on a 12 or 24 hour clock), and mm are minutes. All times are converted to a 12 hour clock, and assumed to be in the next 12 hours.

Home sweet home

Want to go the directory you were just in? Run:
cd -
Need to quickly return to your home directory? Enter:
cd
The variable CDPATH defines the search path for the directory containing directories:
export CDPATH=/var/www:/nas10
Now, instead of typing cd /var/www/html/ I can simply type the following to cd into /var/www/html path:
cd html

Editing a file being viewed with less pager

To edit a file being viewed with less pager, press v. You will have the file for edit under $EDITOR:
 
less *.c
less foo.html
## Press v to edit file ##
## Quit from editor and you would return to the less pager again ##
 

List all files or directories on your system

To see all of the directories on your system, run:
find / -type d | less
 
# List all directories in your $HOME
find $HOME -type d -ls | less
To see all of the files, run:
find / -type f | less
 
# List all files in your $HOME
find $HOME -type f -ls | less

Build directory trees in a single command

You can create directory trees one at a time using mkdir command by passing the -poption:
mkdir -p /jail/{dev,bin,sbin,etc,usr,lib,lib64}
ls -l /jail/

Copy file into multiple directories

Instead of running:
cp /path/to/file /usr/dir1
cp /path/to/file /var/dir2
cp /path/to/file /nas/dir3
Run the following command to copy file into multiple dirs:
echo /usr/dir1 /var/dir2 /nas/dir3 |  xargs -n 1 cp -v /path/to/file
Creating a shell function is left as an exercise for the reader

Quickly find differences between two directories

The diff command compare files line by line. It can also compare two directories:
ls -l /tmp/r
ls -l /tmp/s
# Compare two folders using diff ##
diff /tmp/r/ /tmp/s/
Text formatting
You can reformat each paragraph with fmt command. In this example, I'm going to reformat file by wrapping overlong lines and filling short lines:
fmt file.txt
You can also split long lines, but do not refill i.e. wrap overlong lines, but do not fill short lines:
fmt -s file.txt

See the output and write it to a file

Use the tee command as follows to see the output on screen and also write to a log file named my.log:
mycoolapp arg1 arg2 input.file | tee my.log
The tee command ensures that you will see mycoolapp output on on the screen and to a file same time.

ENJOY.....

Linux and Unix SysAdmins New Year’s Resolutions (2016)

Today is the last day of 2015 and it's that time of year again. Here is my very own 12 resolutions for the New Year.

1. Turn on Two Factor Authentication (2FA)

Setting long and complex passwords for root/admin, backup, devops, or operator accounts is not enough. Naturally, turning on 2FA is useful for cloud-based services. I already have 2FA set for my Linux desktop login including ssh client. I will take the time to change all passwords and if any cloud provider is without 2FA, I'm going to stop using them in 2016. Here is list of websites and whether or not they support 2FA.

2. Let's Encrypt - Free SSL/TLS certificates

Enough said.

3. Never ever do consultancy for cheap IT manager/business

Without going into specific details about business or its owner, I've decided that I will not work with a cheap IT manager who values money over people and work ethics.

4. Fix WHOIS, domain name registries and DNS records

First, I'm going to stop using Godaddy for registering domain names. I also need to fix WHOIS so that I can easily verify my domain ownership and fix broken or deprecated dns entries for A, AAAA, and MX (omg). There is no point running primary and secondary Authoritative DNS servers either. Let the Google, AWS Route 53, Rackspace and co; have them manage it for a small fee. It is better, secure and I will get geo distributed fast Authoritative DNS servers.

5. Learn to Go lang, swift and android programming

Apart from trying to be a better coder, I need to learn Go language. It is everywhere. I'm starting with "The Go Programming Language by Brian W. Kernighan and Alan A. A. Donovan". Of course this will not replace my legacy Perl5 scripts or Python. I don' t know but something tells me we will see more demand for go lang in 2016+. I wanted to learn both iOS and Android device programming just for fun and profit. At least create some Android or iOS app to get familiar with the SDK.

6. Upgrading my cloud skills

I know OpenStack, AWS, Google cloud but there is a new cloud provider, Microsoft Azure and it is getting lots of adoption. Microsoft continues embracing Linux including RHEL. Many Microsoft shops prefer to use Azure for Linux. This might be a good investment in a long term. The Linux Foundation and Microsoft have teamed up to make a new certification for Linux. If you take LFCS and Microsoft 70-533, Microsoft will issue you their MCSA Linux on Azure certification. 
I'm a long time FreeBSD jails and LXC container technologies user. But, it is time to add Docker platform to my skill set in 2016 too.

7. Making peace with systemd

I've finally accepted systemd. There's no point fighting to lose my consultancy business. I already noticed that CentOS/RHEL 7.x, Debian 8.x and upcoming Ubuntu all are systemd based. The political debate is dead for me once my clients started to demand next generation of Linux distro in cloud. There is nothing I can do about it as CentOS/RHEL/Debian all pay my bills.

8. ZFS and FreeBSD

Competition is good For consumers. ZFS is awesome. I've already started with FreeNAS based NAS servers and I will continue to do so in 2016. FreeBSD is a great alternative to systemd based Linux system. If my clients are not happy with systemd, I will strongly suggest FreeBSD for server.

9. Brace yourselves ARM is coming

A Raspberry Pi is a good start to run both Linux and FreeBSD server at home as well as at a small business place. I run my own caching dns server, proxy server, download server and more using a Raspberry Pi. You will see 64 bit ARM server chips this year for Unix/FreeBSD and Linux. Learning ARM boot loaders, automation, programming and installation for ARM based system is very high on my priority list.

10. Getting back to gaming (personal goal)

I gave up on gaming on my Linux rig mostly because of very few AAA titles on Linux. For the first time, I've a reason to smile. Linux games have positively increased due to Steam for Linux. I'm also exited about Vulkan API and AMD's GPUOpen initiative. I do not trust Microsoft even for gaming. I think I will build a new Linux gaming rig powered by AMD in 2016.

11. Stop using deprecated tools on Linux

Finally, going to stop using /sbin/ifconfig, and /bin/netstat on Linux. ifconfig is replaced by the ip command and netstat is replaced by the ss command.

12. Just say NO...

I will not purchase or recommend any laptops with the following specs:
  1. MS-Windows 10 only lock down.
  2. RAM or CPU soldered to motherboards (hard to find in ultrabook though).
  3. 4GB or less ram (8GB is minimum or 16 GB is must).
  4. Storage with moving parts (spinning hard disk).
  5. Laptop with horrible screens.
  6. Wireless whitelist in BIOS (it is my device I should able to install any wifi card).

Your turn...

What resolutions are on your list? Let me know in the comments section below. I would also like to thank you all of our supporters, fans, and clients and I wish you Happy New Year 2016. May the New Year bring less support tickets and healthy servers in your data centers.

Running Linux From a USB Drive As a Virtual Machine or Bootable Disk

Live Linux environments work just like a typical operating system but run entirely from a CD or USB stick -- the latter being the most common choice these days. Since nothing is written to the host computer’s local storage, when you’re done all you need to do is remove the media, reboot, and everything will be exactly as it was.
There are a number of uses to this, from simply test driving Linux to troubleshooting a Windows PC, or work on the go from someone else’s computer but running your own OS securely with all your personal files and settings.
There are basically two options when it comes to running Linux from a USB drive: from within Windows using virtualization software such as VirtualBox, or creating a boot disk. This quick guide details both methods in a few easy steps.

Running Linux from a USB drive in Windows

This option will come in handy if you want to run a Live Linux environment but need to retain access to Windows. Perhaps you just want to do something real quick without rebooting, or want to be able to hide the virtualized Linux instance. Our preferred weapon of choice here is a little tool called LinuxLive USB Creator.
It’s free, open-source software, and it has a built-in virtualization feature that lets you run a self contained version of VirtualBox from the USB drive. This means the host computer you’ll run Linux from doesn’t need to have VirtualBox installed.
Here's what you'll need to do:
  • Download and transfer the ISO image of your preferred Linux distribution to a USB drive.
  • Download and install LinuxLive USB Creator.
  • Launch LiLi USB Creator and follow the straightforward steps guiding you through the process.
    • Step 1. Select the USB drive where you want Linux installed.
    • Step 2. Choose the source ISO file of the Linux distribution you downloaded.
    • Step 3. Choose Live Mode.
    • Step 4. Leave the third box checked, the other two are up to you and self-explanatory.

You will need and internet connection to complete the process -- mainly to download VirtualBox if you don’t have it installed. Once the process is finished, open your USB key in Windows Explorer and you should see a folder called VirtualBox containing two executable files:VirtualizeThisKey.exe and VirtualBox.exe.
Running VirtualizeThisKey.exe will launch your Linux distribution in Windows (inside VirtualBox), whereas VirtualBox.exe opens the full VirtualBox interface.

Boot Linux from a USB drive

If you’d rather load Linux without going through Windows first this is the way to go. There are a few different tools for creating bootable USB drives around the web but one I’m particularly fond of is YUMI -- short for Your Universal Multiboot Installer.
This is the successor to our MultibootISO and can be used to install more than one distribution to run from your USB. It’s extremely simple to use, and all files from each Linux distribution are stored within the Multiboot folder, making for a nicely organized Multiboot Drive that can still be used for other storage purposes.
  • Download the ISO image of your preferred Linux distribution.
  • Download and install YUMI.
  • Launch YUMI and follow three simple steps guiding you through the process.
    • Step 1. Select the USB drive where you want Linux installed.
    • Step 2. Select the Linux distribution you'll be installing from the list.
    • Step 3. Choose the source ISO file of the Linux distribution you downloaded.

Once YUMI is done you’re all set. To boot into Linux just plug the USB drive into the host computer, reboot, and press the required key during this process to enter the Boot Menu (usually F10). After choosing your USB drive you should see the YUMI boot menu where you can pick the desired Linux distribution in Live mode.
You can run YUMI's boot drive creator again to add More ISOs/distributions to your drive as needed and they'll all show up in this menu during boot.

Which Linux distribution should I install?

There's no single right answer to that question. For a new user jumping into the world of Linux-based operating systems the amount of options available can be overwhelming. Finding the "right" distro for you can only be done though experience but there are plenty of resources online to help you figure it out.
Popular choices for newcomers include Ubuntu, Mint and PCLinuxOS. If you are looking for a secure operating system to take with you anywhere, you might also want to give Tails a try. The latter received a lot of press recently when it was disclosed that Edward Snowden was using it to avoid NSA snooping.