check folder size in ubuntu

Find the size of a directory in Linux

To find out the size of a directory, we will use ‘du’ command. du stands for disk usage.

The typical syntax of du command is given below:

du [OPTION]... [FILE] [directory]...

du [OPTION]... --files0-from=F

Let us type the ‘du’ command in the Terminal and see what it displays.

$ du
148     ./.npm/_cacache/index-v5/e2
8       ./.npm/_cacache/index-v5/07/0f
8       ./.npm/_cacache/index-v5/07/dd
8       ./.npm/_cacache/index-v5/07/16
8       ./.npm/_cacache/index-v5/07/43
8       ./.npm/_cacache/index-v5/07/2b
12      ./.npm/_cacache/index-v5/07/4d
8       ./.npm/_cacache/index-v5/07/a6
8       ./.npm/_cacache/index-v5/07/e3
72      ./.npm/_cacache/index-v5/07
8       ./.npm/_cacache/index-v5/04/d4
8       ./.npm/_cacache/index-v5/04/11
8       ./.npm/_cacache/index-v5/04/ba
8       ./.npm/_cacache/index-v5/04/52
8       ./.npm/_cacache/index-v5/04/be
8       ./.npm/_cacache/index-v5/04/01
12      ./.npm/_cacache/index-v5/04/2a
8       ./.npm/_cacache/index-v5/04/68
8       ./.npm/_cacache/index-v5/04/6f

As you see above, du command displays the disk usage of the directories along with its sub-directories in the current directory.

To display a particular directory’s size, for example public_html, run:

$ du public_html/
ubuntu@www:~$ du public_html/
56      public_html/routes
132     public_html/vendor/nikic/php-parser/grammar
68      public_html/vendor/nikic/php-parser/doc/component
100     public_html/vendor/nikic/php-parser/doc
100     public_html/vendor/nikic/php-parser/test/code/prettyPrinter/stmt
84      public_html/vendor/nikic/php-parser/test/code/prettyPrinter/expr
212     public_html/vendor/nikic/php-parser/test/code/prettyPrinter
68      public_html/vendor/nikic/php-parser/test/code/parser/stmt/namespace
48      public_html/vendor/nikic/php-parser/test/code/parser/stmt/function
84      public_html/vendor/nikic/php-parser/test/code/parser/stmt/class
20      public_html/vendor/nikic/php-parser/test/code/parser/stmt/loop
32      public_html/vendor/nikic/php-parser/test/code/parser/stmt/generator
324     public_html/vendor/nikic/php-parser/test/code/parser/stmt
64      public_html/vendor/nikic/php-parser/test/code/parser/scalar
44      public_html/vendor/nikic/php-parser/test/code/parser/errorHandling
44      public_html/vendor/nikic/php-parser/test/code/parser/expr/uvs
52      public_html/vendor/nikic/php-parser/test/code/parser/expr/fetchAndCall
264     public_html/vendor/nikic/php-parser/test/code/parser/expr
732     public_html/vendor/nikic/php-parser/test/code/parser
84      public_html/vendor/nikic/php-parser/test/code/formatPreservation
1032    public_html/vendor/nikic/php-parser/test/code
16      public_html/vendor/nikic/php-parser/test/PhpParser/Lexer
24      public_html/vendor/nikic/php-parser/test/PhpParser/Node/Stmt
12      public_html/vendor/nikic/php-parser/test/PhpParser/Node/Scalar
52      public_html/vendor/nikic/php-parser/test/PhpParser/Node
12      public_html/vendor/nikic/php-parser/test/PhpParser/ErrorHandler
60      public_html/vendor/nikic/php-parser/test/PhpParser/Builder
8       public_html/vendor/nikic/php-parser/test/PhpParser/Internal
28      public_html/vendor/nikic/php-parser/test/PhpParser/NodeVisitor
16      public_html/vendor/nikic/php-parser/test/PhpParser/Parser
320     public_html/vendor/nikic/php-parser/test/PhpParser
1364    public_html/vendor/nikic/php-parser/test
12      public_html/vendor/nikic/php-parser/bin
16      public_html/vendor/nikic/php-parser/test_old
20      public_html/vendor/nikic/php-parser/lib/PhpParser/Lexer/TokenEmulator
36      public_html/vendor/nikic/php-parser/lib/PhpParser/Lexer
44      public_html/vendor/nikic/php-parser/lib/PhpParser/PrettyPrinter
12      public_html/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt/TraitUseAdap                                                                                        tation
200     public_html/vendor/nikic/php-parser/lib/PhpParser/Node/Stmt
12      public_html/vendor/nikic/php-parser/lib/PhpParser/Node/Name
112     public_html/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/BinaryOp
56      public_html/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/AssignOp
32      public_html/vendor/nikic/php-parser/lib/PhpParser/Node/Expr/Cast
376     public_html/vendor/nikic/php-parser/lib/PhpParser/Node/Expr
36      public_html/vendor/nikic/php-parser/lib/PhpParser/Node/Scalar/MagicConst
68      public_html/vendor/nikic/php-parser/lib/PhpParser/Node/Scalar
708     public_html/vendor/nikic/php-parser/lib/PhpParser/Node
8       public_html/vendor/nikic/php-parser/lib/PhpParser/Comment
12      public_html/vendor/nikic/php-parser/lib/PhpParser/ErrorHandler
60      public_html/vendor/nikic/php-parser/lib/PhpParser/Builder
28      public_html/vendor/nikic/php-parser/lib/PhpParser/Internal
28      public_html/vendor/nikic/php-parser/lib/PhpParser/NodeVisitor
324     public_html/vendor/nikic/php-parser/lib/PhpParser/Parser
1500    public_html/vendor/nikic/php-parser/lib/PhpParser
1504    public_html/vendor/nikic/php-parser/lib
3212    public_html/vendor/nikic/php-parser
3216    public_html/vendor/nikic
24      public_html/vendor/league/flysystem-aws-s3-v3/src
40      public_html/vendor/league/flysystem-aws-s3-v3
44      public_html/vendor/league/flysystem/src/Plugin
24      public_html/vendor/league/flysystem/src/Util
24      public_html/vendor/league/flysystem/src/Adapter/Polyfill
96      public_html/vendor/league/flysystem/src/Adapter
288     public_html/vendor/league/flysystem/src
312     public_html/vendor/league/flysystem
76      public_html/vendor/league/oauth2-server/src/Grant
12      public_html/vendor/league/oauth2-server/src/AuthorizationValidators
12      public_html/vendor/league/oauth2-server/src/RequestTypes
20      public_html/vendor/league/oauth2-server/src/Exception
32      public_html/vendor/league/oauth2-server/src/Entities/Traits
64      public_html/vendor/league/oauth2-server/src/Entities
12      public_html/vendor/league/oauth2-server/src/Middleware
32      public_html/vendor/league/oauth2-server/src/Repositories
20      public_html/vendor/league/oauth2-server/src/ResponseTypes
276     public_html/vendor/league/oauth2-server/src
300     public_html/vendor/league/oauth2-server
84      public_html/vendor/league/event/src
96      public_html/vendor/league/event
752     public_html/vendor/league
28      public_html/vendor/filp/whoops/src/Whoops/Util
40      public_html/vendor/filp/whoops/src/Whoops/Exception
60      public_html/vendor/filp/whoops/src/Whoops/Handler
16      public_html/vendor/filp/whoops/src/Whoops/Resources/css
60      public_html/vendor/filp/whoops/src/Whoops/Resources/views

We can also display the size in “human readable format” (i.e. auto-selecting the appropriate unit for each size), rather than the standard block size.

To do so, add -h tag with du command as shown below.

$ du -h app/
ubuntu@www:~/public_html$ du -h app
32K     app/Helpers
728K    app/Http/Controllers/Api/V1
732K    app/Http/Controllers/Api
24K     app/Http/Controllers/Auth/Old
48K     app/Http/Controllers/Auth
104K    app/Http/Controllers/Admin
964K    app/Http/Controllers
44K     app/Http/Middleware
1016K   app/Http
24K     app/Providers
8.0K    app/Console
8.0K    app/Exports
12K     app/Mail
8.0K    app/Exceptions
36K     app/Models/api
164K    app/Models
1.4M    app

Now you see the size of the directories in Kilobytes, Megabytes and Gigabytes, which is very clear and easy to understand.

We can also display the disk usage size only in KB, or MB, or GB.

To do so, use -k for kilobytes, -m for megabytes

$ du -k app/
$ du -m app/

To find out which sub-directories consume how much disk size, use this command:

$ du -h --max-depth=1 | sort -hr

The largest sub-directories will be displayed on the top. You can increase the directory depth level by increasing the value of –max-depth parameter.

As you may noticed in the all above outputs, du command only displayed the disk usage of directories. But, what about the files? To display the disk usage of all items including files and directories, use -a flag.

$ du -ah app/
ubuntu@www:~/public_html$ du -ah app
4.0K    app/UserSpokenLanguage.php
4.0K    app/Contact.php
4.0K    app/Country.php
4.0K    app/UserDevice.php
4.0K    app/Sos.php
4.0K    app/UserImage.php
4.0K    app/UserScreenshot.php
8.0K    app/Helpers/Notifications.php
8.0K    app/Helpers/FileUpload.php
8.0K    app/Helpers/Common.php
4.0K    app/Helpers/Helpers.php
32K     app/Helpers
4.0K    app/UserMeetupMessage.php
4.0K    app/Event.php
4.0K    app/Http/Controllers/HomeControllerOld.php
364K    app/Http/Controllers/Api/V1/ApiController.php
360K    app/Http/Controllers/Api/V1/ApiController.php_24_12_2019
728K    app/Http/Controllers/Api/V1
732K    app/Http/Controllers/Api
12K     app/Http/Controllers/WebsiteController04nov.php
28K     app/Http/Controllers/CronjobController.php
4.0K    app/Http/Controllers/Auth/LoginController.php
4.0K    app/Http/Controllers/Auth/ForgotPasswordController.php
4.0K    app/Http/Controllers/Auth/ResetPasswordController.php
4.0K    app/Http/Controllers/Auth/RegisterController.php
4.0K    app/Http/Controllers/Auth/Old/LoginController.php
4.0K    app/Http/Controllers/Auth/Old/ForgotPasswordController.php
4.0K    app/Http/Controllers/Auth/Old/ResetPasswordController.php
4.0K    app/Http/Controllers/Auth/Old/RegisterController.php
4.0K    app/Http/Controllers/Auth/Old/VerificationController.php
24K     app/Http/Controllers/Auth/Old
4.0K    app/Http/Controllers/Auth/VerificationController.php
48K     app/Http/Controllers/Auth
12K     app/Http/Controllers/WebsiteController14nov.php
12K     app/Http/Controllers/WebsiteController.php
4.0K    app/Http/Controllers/Admin/CmsController.php
4.0K    app/Http/Controllers/Admin/ProfessionController.php
12K     app/Http/Controllers/Admin/AdminController.php
4.0K    app/Http/Controllers/Admin/FaqController.php

We can also display the size of multiple directories at once as shown below.

$ du -h directory1 directory2

If you want to check the total disk space used by a particular directory, use the -s flag.

$ du -sh app
ubuntu@www:~/public_html$ du -sh app
1.4M    app
ubuntu@www:~/public_html$

EXAMPLES :

$ du -csh app /home/sk/
2.8G app
279G /home/sk/
281G total

$ du -ch Downloads/ | grep total
12G total

$ du -ch --exclude='*.mp4' | grep total 
6.4G total
$ man du
DU(1)                                                                      User Commands                                                                      DU(1)

NAME
       du - estimate file space usage

SYNOPSIS
       du [OPTION]... [FILE]...
       du [OPTION]... --files0-from=F

DESCRIPTION
       Summarize disk usage of the set of FILEs, recursively for directories.

       Mandatory arguments to long options are mandatory for short options too.

       -0, --null
              end each output line with NUL, not newline

       -a, --all
              write counts for all files, not just directories

       --apparent-size
              print  apparent  sizes,  rather  than  disk  usage; although the apparent size is usually smaller, it may be larger due to holes in ('sparse') files,
              internal fragmentation, indirect blocks, and the like

       -B, --block-size=SIZE
              scale sizes by SIZE before printing them; e.g., '-BM' prints sizes in units of 1,048,576 bytes; see SIZE format below

       -b, --bytes
              equivalent to '--apparent-size --block-size=1'

       -c, --total
              produce a grand total

       -D, --dereference-args
              dereference only symlinks that are listed on the command line

       -d, --max-depth=N
              print the total for a directory (or file, with --all) only if it is N or fewer levels below the command line argument;  --max-depth=0 is the same  as
              --summarize

       --files0-from=F
              summarize disk usage of the NUL-terminated file names specified in file F; if F is -, then read names from standard input

check space used by folder linux only parent directory

du --max-depth=1 -h .

apport ubuntu

What is this all about?

Debugging program crashes without any automated tools has been pretty time consuming and hard for both developers and users. Many program crashes remain unreported or unfixed because:

  • Many crashes are not easily reproducible.
  • End users do not know how to prepare a report that is really useful for developers, like building a package with debug symbols, operating gdb, etc.
  • A considerable part of bug triage is spent with collecting relevant information about the crash itself, package versions, hardware architecture, operating system version, etc.
  • There is no easy frontend which allow users to submit detailed problem reports.
  • Existing solutions like bug-buddy or krash are specific to a particular desktop environment, are nontrivial to adapt to the needs of a distribution developer, do not work for crashes of background servers (like a database or an email server), and do not integrate well with existing debug packages that a distribution might provide.

Apport is a system which:

  • intercepts crashes right when they happen the first time,
  • gathers potentially useful information about the crash and the OS environment,
  • can be automatically invoked for unhandled exceptions in other programming languages (e. g. in Ubuntu this is done for Python),
  • can be automatically invoked for other problems that can be automatically detected (e. g. Ubuntu automatically detects and reports package installation/upgrade failures from update-manager),
  • presents a UI that informs the user about the crash and instructs them on how to proceed,
  • and is able to file non-crash bug reports about software, so that developers still get information about package versions, OS version etc.

We are sure that this will lead to a much better level of quality assurance in the future.

If you want to make crash reports of your software even more useful when being reported through apport, please see /DeveloperHowTo.

What does it look like for users?

The user side of apport is designed to be extremely simple and as unannoying as possible.

If any process in the system dies due to a signal that is commonly referred to as a ‘crash’ (segmentation violation, bus error, floating point exception, etc.), or e. g. a packaged Python application raises an uncaught exception, the apport backend is automatically invoked. It produces an initial crash report in a file in /var/crash/ (the file name is composed from the name of the crashed executable and the user id). If the crashed process belongs to the user who is currently logged in, or it belongs to a system process and the user is an administrator, apport informs the user about the crash and offers to report the problem:

You can click on “Show Details…” to see what data it collected:

If the user leaves the “Send error report” checkbox enabled, Apport uploads the collected information to the bug tracking system. After that it opens the packages’ bug filing page with a sensible default bug title and leaves the rest of bug filing process to the web UI.

Why is apport disabled by default?

Apport is not enabled by default in stable releases, even if it is installed. The automatic crash interception component of apport is disabled by default in stable releases for a number of reasons:

  1. Apport collects potentially sensitive data, such as core dumps, stack traces, and log files. They can contain passwords, credit card numbers, serial numbers, and other private material.This is mitigated by the fact that it presents you what will be sent to the bug tracker, and that all crash report bugs are private by default, limited to the Ubuntu bug triaging team. We can reasonably expect developers and technically savvy users, who run the development release, to be aware of this and judge whether it is appropriate to file a crash report. But we shouldn’t assume that every Ubuntu user of stable releases is able to do so. In 12.04 and up this is transparently handled by whoopsie, see ErrorTracker.
  2. During the development release we already collect thousands of crash reports, much more than we can ever fix. Continuing to collect those for stable releases is not really useful, since
    • The most important crashes have already been discovered in the development release.
    • The less important ones are not suitable for getting fixed in stable releases (see https://wiki.ubuntu.com/StableReleaseUpdates
    • Asking users to send crash reports to us is insincere, since we can’t possibly answer and deal with all of them.
  3. Data collection from apport takes a nontrivial amount of CPU and I/O resources, which slow down the computer and don’t allow you to restart the crashed program for several seconds.

Note apport does not trap SIGABRT signals. If you are getting such a signal, then please see DebuggingProgramCrash.

How to enable apport

Apport itself is running at all times because it collects crash data for whoopsie (see ErrorTracker). However, the crash interception component is still disabled. To enable it permanently, do:

sudo nano /etc/apport/crashdb.conf

… and add a hash symbol # in the beginning of the following line:

        'problem_types': ['Bug', 'Package'],

To disable crash reporting just remove the hash symbol.

check storage space in ubuntu | how to check hard disk size in ubuntu terminal

show total of disk space

$ df -h --total

which will show it in one line as

  • (1) total space
  • (2) total space used
  • (3) total space still available
  • (4) percentage of drive used.

All of this in gigabytes.

I mapped this to a shell command dspace and when I type that into terminal it instantly shows me my disk space usage.

$ df -h --total | grep total

lists the size of each partition

$ lsblk

1. Checking File System Disk Space

The “df” command displays the information of file system device names, disk blocks, total disk space used, available disk space, percentage of usage and mount points on a file system.

ubuntu@www:~$ df
Filesystem     1K-blocks    Used Available Use% Mounted on
udev              491680       0    491680   0% /dev
tmpfs             100764     780     99984   1% /run
/dev/xvda1     101583780 7599572  93967824   8% /
tmpfs             503804       0    503804   0% /dev/shm
tmpfs               5120       0      5120   0% /run/lock
tmpfs             503804       0    503804   0% /sys/fs/cgroup
/dev/loop0         91264   91264         0 100% /snap/core/8268
/dev/loop1         18432   18432         0 100% /snap/amazon-ssm-agent/1480
/dev/loop2         18432   18432         0 100% /snap/amazon-ssm-agent/1455
/dev/loop3         91264   91264         0 100% /snap/core/8213
tmpfs             100760       0    100760   0% /run/user/1000

2. Display Disk Space in Human Readable Format

As you see in the first example, the output is difficult to read or understand. By default df command shows disk space information in bytes which is difficult to understand for humans. We can easily understand if the results are in megabytes and gigabytes.

Don’t worry, the good df command has an option to display information in human readable format like in MB and GB. You just need to add -h flag to see.

ubuntu@www:~$ df -h
Filesystem      Size  Used Avail Use% Mounted on
udev            481M     0  481M   0% /dev
tmpfs            99M  780K   98M   1% /run
/dev/xvda1       97G  7.3G   90G   8% /
tmpfs           492M     0  492M   0% /dev/shm
tmpfs           5.0M     0  5.0M   0% /run/lock
tmpfs           492M     0  492M   0% /sys/fs/cgroup
/dev/loop0       90M   90M     0 100% /snap/core/8268
/dev/loop1       18M   18M     0 100% /snap/amazon-ssm-agent/1480
/dev/loop2       18M   18M     0 100% /snap/amazon-ssm-agent/1455
/dev/loop3       90M   90M     0 100% /snap/core/8213
tmpfs            99M     0   99M   0% /run/user/1000

3. Display information of all file systems

If you want to see all file systems including which has zero block sizes, pass parameter -a or -all along with df command. The output would be similar to this.

ubuntu@www:~$ df -all
Filesystem     1K-blocks    Used Available Use% Mounted on
sysfs                  0       0         0    - /sys
proc                   0       0         0    - /proc
udev              491680       0    491680   0% /dev
devpts                 0       0         0    - /dev/pts
tmpfs             100764     780     99984   1% /run
/dev/xvda1     101583780 7517872  94049524   8% /
securityfs             0       0         0    - /sys/kernel/security
tmpfs             503804       0    503804   0% /dev/shm
tmpfs               5120       0      5120   0% /run/lock
tmpfs             503804       0    503804   0% /sys/fs/cgroup
cgroup                 0       0         0    - /sys/fs/cgroup/unified
cgroup                 0       0         0    - /sys/fs/cgroup/systemd
pstore                 0       0         0    - /sys/fs/pstore
cgroup                 0       0         0    - /sys/fs/cgroup/devices
cgroup                 0       0         0    - /sys/fs/cgroup/cpu,cpuacct
cgroup                 0       0         0    - /sys/fs/cgroup/rdma
cgroup                 0       0         0    - /sys/fs/cgroup/perf_event
cgroup                 0       0         0    - /sys/fs/cgroup/pids
cgroup                 0       0         0    - /sys/fs/cgroup/hugetlb
cgroup                 0       0         0    - /sys/fs/cgroup/net_cls,net_prio
cgroup                 0       0         0    - /sys/fs/cgroup/blkio
cgroup                 0       0         0    - /sys/fs/cgroup/memory
cgroup                 0       0         0    - /sys/fs/cgroup/freezer
cgroup                 0       0         0    - /sys/fs/cgroup/cpuset
systemd-1              -       -         -    - /proc/sys/fs/binfmt_misc
hugetlbfs              0       0         0    - /dev/hugepages
mqueue                 0       0         0    - /dev/mqueue
debugfs                0       0         0    - /sys/kernel/debug
fusectl                0       0         0    - /sys/fs/fuse/connections
configfs               0       0         0    - /sys/kernel/config
/dev/loop0         91264   91264         0 100% /snap/core/8268
/dev/loop1         18432   18432         0 100% /snap/amazon-ssm-agent/1480
/dev/loop2         18432   18432         0 100% /snap/amazon-ssm-agent/1455
/dev/loop3         91264   91264         0 100% /snap/core/8213
lxcfs                  0       0         0    - /var/lib/lxcfs
binfmt_misc            0       0         0    - /proc/sys/fs/binfmt_misc
tmpfs             100760       0    100760   0% /run/user/1000

4. Display File System details in Bytes

To display all file system information and usage in 1 K blocks , pass the option ‘-k‘  as follows.

ubuntu@www:~$ df -k
Filesystem     1K-blocks    Used Available Use% Mounted on
udev              491680       0    491680   0% /dev
tmpfs             100764     784     99980   1% /run
/dev/xvda1     101583780 7600328  93967068   8% /
tmpfs             503804       0    503804   0% /dev/shm
tmpfs               5120       0      5120   0% /run/lock
tmpfs             503804       0    503804   0% /sys/fs/cgroup
/dev/loop0         91264   91264         0 100% /snap/core/8268
/dev/loop1         18432   18432         0 100% /snap/amazon-ssm-agent/1480
/dev/loop2         18432   18432         0 100% /snap/amazon-ssm-agent/1455
/dev/loop3         91264   91264         0 100% /snap/core/8213
tmpfs             100760       0    100760   0% /run/user/1000

5. Display File System Information in MB

To display all file system information and usage in MB or megabytes  , pass the option ‘-m‘.

ubuntu@www:~$ df -m
Filesystem     1M-blocks  Used Available Use% Mounted on
udev                 481     0       481   0% /dev
tmpfs                 99     1        98   1% /run
/dev/xvda1         99203  7343     91845   8% /
tmpfs                492     0       492   0% /dev/shm
tmpfs                  5     0         5   0% /run/lock
tmpfs                492     0       492   0% /sys/fs/cgroup
/dev/loop0            90    90         0 100% /snap/core/8268
/dev/loop1            18    18         0 100% /snap/amazon-ssm-agent/1480
/dev/loop2            18    18         0 100% /snap/amazon-ssm-agent/1455
/dev/loop3            90    90         0 100% /snap/core/8213
tmpfs                 99     0        99   0% /run/user/1000

6. Display File System Information in GB

To display all file system details and usage in GB or gigabytes  , pass the option ‘-h‘.

ubuntu@www:~$ df -h
Filesystem      Size  Used Avail Use% Mounted on
udev            481M     0  481M   0% /dev
tmpfs            99M  780K   98M   1% /run
/dev/xvda1       97G  7.3G   90G   8% /
tmpfs           492M     0  492M   0% /dev/shm
tmpfs           5.0M     0  5.0M   0% /run/lock
tmpfs           492M     0  492M   0% /sys/fs/cgroup
/dev/loop0       90M   90M     0 100% /snap/core/8268
/dev/loop1       18M   18M     0 100% /snap/amazon-ssm-agent/1480
/dev/loop2       18M   18M     0 100% /snap/amazon-ssm-agent/1455
/dev/loop3       90M   90M     0 100% /snap/core/8213
tmpfs            99M     0   99M   0% /run/user/1000

7. Display /home file system information

You can see only /home file system device infomation by executing below df command.

ubuntu@www:~$ df -h /home
Filesystem      Size  Used Avail Use% Mounted on
/dev/xvda1       97G  7.3G   90G   8% /

8. Display File System Type in Linux

To see the type of each file system pass the -T option. It gives output with file system types column. You could see the type of each file system listed such as ext4, ext3, tempfs, devtmpfs and etc.

ubuntu@www:~$ df -T
Filesystem     Type     1K-blocks    Used Available Use% Mounted on
udev           devtmpfs    491680       0    491680   0% /dev
tmpfs          tmpfs       100764     780     99984   1% /run
/dev/xvda1     ext4     101583780 7602896  93964500   8% /
tmpfs          tmpfs       503804       0    503804   0% /dev/shm
tmpfs          tmpfs         5120       0      5120   0% /run/lock
tmpfs          tmpfs       503804       0    503804   0% /sys/fs/cgroup
/dev/loop0     squashfs     91264   91264         0 100% /snap/core/8268
/dev/loop1     squashfs     18432   18432         0 100% /snap/amazon-ssm-agent/1480
/dev/loop2     squashfs     18432   18432         0 100% /snap/amazon-ssm-agent/1455
/dev/loop3     squashfs     91264   91264         0 100% /snap/core/8213
tmpfs          tmpfs       100760       0    100760   0% /run/user/1000

9. Include or Exclude only certain File System Types.

If you want to see only ext4 file systems, use df command with option -t

If you want to see all file system types except ext4, then pass -x option and type ( ext3, ext4) to exclude from the output.

 df -t tmpfs
Filesystem     1K-blocks  Used Available Use% Mounted on
tmpfs             100764   780     99984   1% /run
tmpfs             503804     0    503804   0% /dev/shm
tmpfs               5120     0      5120   0% /run/lock
tmpfs             503804     0    503804   0% /sys/fs/cgroup
tmpfs             100760     0    100760   0% /run/user/1000

10. Display df Command Options and Help

You can see all the available options with df command by typing below command.

$ df --help
Usage: df [OPTION]... [FILE]...
Show information about the file system on which each FILE resides,
or all file systems by default.

Mandatory arguments to long options are mandatory for short options too.
  -a, --all             include pseudo, duplicate, inaccessible file systems
  -B, --block-size=SIZE  scale sizes by SIZE before printing them; e.g.,
                           '-BM' prints sizes in units of 1,048,576 bytes;
                           see SIZE format below
  -h, --human-readable  print sizes in powers of 1024 (e.g., 1023M)
  -H, --si              print sizes in powers of 1000 (e.g., 1.1G)
  -i, --inodes          list inode information instead of block usage
  -k                    like --block-size=1K
  -l, --local           limit listing to local file systems
      --no-sync         do not invoke sync before getting usage info (default)
      --output[=FIELD_LIST]  use the output format defined by FIELD_LIST,
                               or print all fields if FIELD_LIST is omitted.
  -P, --portability     use the POSIX output format
      --sync            invoke sync before getting usage info
      --total           elide all entries insignificant to available space,
                          and produce a grand total
  -t, --type=TYPE       limit listing to file systems of type TYPE
  -T, --print-type      print file system type
  -x, --exclude-type=TYPE   limit listing to file systems not of type TYPE
  -v                    (ignored)
      --help     display this help and exit
      --version  output version information and exit

Display values are in units of the first available SIZE from --block-size,
and the DF_BLOCK_SIZE, BLOCK_SIZE and BLOCKSIZE environment variables.
Otherwise, units default to 1024 bytes (or 512 if POSIXLY_CORRECT is set).

The SIZE argument is an integer and optional unit (example: 10K is 10*1024).
Units are K,M,G,T,P,E,Z,Y (powers of 1024) or KB,MB,... (powers of 1000).

FIELD_LIST is a comma-separated list of columns to be included.  Valid
field names are: 'source', 'fstype', 'itotal', 'iused', 'iavail', 'ipcent',
'size', 'used', 'avail', 'pcent', 'file' and 'target' (see info page).

GNU coreutils online help: <http://www.gnu.org/software/coreutils/>
Report df translation bugs to <http://translationproject.org/team/>
Full documentation at: <http://www.gnu.org/software/coreutils/df>
or available locally via: info '(coreutils) df invocation'

What is Fail2Ban

Fail2ban is a log-parsing application that monitors system logs for symptoms of an automated attack on your Linode. When an attempted compromise is located, using the defined parameters, Fail2ban will add a new rule to iptables to block the IP address of the attacker, either for a set amount of time or permanently. Fail2ban can also alert you through email that an attack is occurring.

Fail2ban is primarily focused on SSH attacks, although it can be further configured to work for any service that uses log files and can be subject to a compromise.

CentOS 7

  1. Ensure your system is up to date and install the EPEL repository:yum update && yum install epel-release
  2. Install Fail2Ban:yum install fail2ban
  3. Install Sendmail if you additionally would like email support. Sendmail is not required to use Fail2Ban.:yum install sendmail
  4. Start and enable Fail2ban and, if needed, Sendmail:systemctl start fail2ban systemctl enable fail2ban systemctl start sendmail systemctl enable sendmail NoteShould you encounter the error that there is “no directory /var/run/fail2ban to contain the socket file /var/run/fail2ban/fail2ban.sock”, create the directory manually:mkdir /var/run/fail2ban

Debian

  1. Ensure your system is up to date:apt-get update && apt-get upgrade -y
  2. Install Fail2ban:apt-get install fail2ban The service will automatically start.
  3. (Optional) If you would like email support, install Sendmail:apt-get install sendmail-bin sendmail NoteThe current version of Sendmail in Debian Jessie has an upstream bug which causes the following errors when installing sendmail-bin. The installation will hang for a minute, but then complete.Creating /etc/mail/sendmail.cf... ERROR: FEATURE() should be before MAILER() MAILER('local') must appear after FEATURE('always_add_domain') ERROR: FEATURE() should be before MAILER() MAILER('local') must appear after FEATURE('allmasquerade')

Fedora

  1. Update your system:dnf update
  2. Install Fail2ban:dnf install fail2ban
  3. (Optional) If you would like email support, install Sendmail:dnf install sendmail
  4. Start and enable Fail2ban and, if needed, Sendmail:systemctl start fail2ban systemctl enable fail2ban systemctl start sendmail systemctl enable sendmail

Ubuntu

  1. Ensure your system is up to date:apt-get update && apt-get upgrade -y
  2. Install Fail2ban:apt-get install fail2ban The service will automatically start.
  3. (Optional) If you would like email support, install Sendmail:apt-get install sendmail
  4. Allow SSH access through UFW and then enable the firewall:
    ufw allow ssh
    ufw enable

Configure Fail2ban

Fail2ban reads .conf configuration files first, then .local files override any settings. Because of this, all changes to the configuration are generally done in .local files, leaving the .conf files untouched.

Configure fail2ban.local

  1. fail2ban.conf contains the default configuration profile. The default settings will give you a reasonable working setup. If you want to make any changes, it’s best to do it in a separate file, fail2ban.local, which overrides fail2ban.conf. Rename a copy fail2ban.conf to fail2ban.local.
cp /etc/fail2ban/fail2ban.conf /etc/fail2ban/fail2ban.local

2. From here, you can opt to edit the definitions in fail2ban.local to match your desired configuration. The values that can be changed are:

  • loglevel: The level of detail that Fail2ban’s logs provide can be set to 1 (error), 2 (warn), 3 (info), or 4 (debug).
  • logtarget: Logs actions into a specific file. The default value of /var/log/fail2ban.log puts all logging into the defined file. Alternately, you can change the value to:
    • STDOUT: output any data
    • STDERR: output any errors
    • SYSLOG: message-based logging
    • FILE: output to a file
  • socket: The location of the socket file.
  • pidfile: The location of the PID file.

Configure jail.local Settings

  1. The jail.conf file will enable Fail2ban for SSH by default for Debian and Ubuntu, but not CentOS. All other protocols and configurations (HTTP, FTP, etc.) are commented out. If you want to change this, create a jail.local for editing:
cp /etc/fail2ban/jail.conf /etc/fail2ban/jail.local

/etc/fail2ban/jail.local

# "backend" specifies the backend used to get files modification.
# Available options are "pyinotify", "gamin", "polling", "systemd" and "auto".
# This option can be overridden in each jail as well.

. . .

backend = systemd

No jails are enabled by default in CentOS 7. For example, to enable the SSH daemon jail, uncomment the following lines in jail.local:

/etc/fail2ban/jail.local

[sshd]
enabled = true

Whitelist IP

To ignore specific IPs, add them to the ignoreip line. By default, this command will not ban the localhost. If you work from a single IP address often, it may be beneficial to add it to the ignore list:

/etc/fail2ban/jail.local

[DEFAULT]

# "ignoreip" can be an IP address, a CIDR mask or a DNS host. Fail2ban will not
# ban a host which matches an address in this list. Several addresses can be
# defined using space separator.
ignoreip = 127.0.0.1/8 123.45.67.89

If you wish to whitelist IPs only for certain jails, this can be done with the fail2ban-client command. Replace JAIL with the name of your jail, and 123.45.67.89 with the IP you wish to whitelist.

fail2ban-client set JAIL addignoreip 123.45.67.89

Ban Time and Retry Amount

Set bantimefindtime, and maxretry to define the circumstances and the length of time of a ban:

/etc/fail2ban/jail.local
# "bantime" is the number of seconds that a host is banned.
bantime  = 600

# A host is banned if it has generated "maxretry" during the last "findtime"
# seconds.
findtime = 600
maxretry = 3
  • bantime: The length of time in seconds for which an IP is banned. If set to a negative number, the ban will be permanent. The default value of 600 is set to ban an IP for a 10-minute duration.
  • findtime: The length of time between login attempts before a ban is set. For example, if Fail2ban is set to ban an IP after five (5) failed log-in attempts, those 5 attempts must occur within the set 10-minute findtime limit. The findtime value should be a set number of seconds.
  • maxretry: How many attempts can be made to access the server from a single IP before a ban is imposed. The default is set to 3.

Other Jail Configuration

Beyond the basic settings address above, jail.local also contains various jail configurations for a number of common services, including SSH, and iptables. By default, only SSH is enabled and the action is to ban the offending host/IP address by modifying the iptables firewall rules.

An average jail configuration will resemble the following:

/etc/fail2ban/jail.local

# Default banning action (e.g. iptables, iptables-new,
# iptables-multiport, shorewall, etc) It is used to define
# action_* variables. Can be overridden globally or per
# section within jail.local file
banaction = iptables-multiport
banaction_allports = iptables-allports

[ssh]

enabled  = true
port     = ssh
filter   = sshd
logpath  = /var/log/auth.log
maxretry = 6
  • banaction: Determines the action to use when the threshold is reached. If you have configured the firewall to use firewalld set the value to firewallcmd-ipset and if you have configured the firewall to use UFW set the value to ufw.
  • banaction_allports: Blocks a remote IP in every port. If you have configured the firewall to use firewalld set the value to firewallcmd-ipset.
  • enabled: Determines whether or not the filter is turned on.
  • port: The port Fail2ban should be referencing in regards to the service. If using the default port, then the service name can be placed here. If using a non-traditional port, this should be the port number. For example, if you moved your SSH port to 3456, you would replace ssh with 3456.
  • filter: The name of the file located in /etc/fail2ban/filter.d that contains the failregex information used to parse log files appropriately. The .conf suffix need not be included.
  • logpath: Gives the location of the service’s logs.
  • maxretry: Will override the global maxretry for the defined service. findtime and bantime can also be added.
  • action: This can be added as an additional setting, if the default action is not suitable for the jail. Additional actions can be found in the action.d folder.

if ufw enable and ssh not login problem, how to solve it?

try this.

Launch a new instance (recovery instance).
Stop the original instance (DO NOT TERMINATE)
Detach the volume (problem volume) from the original instance
Attached it to the recovery instance as /dev/sdf.
Login to the recovery instance via ssh/putty
Run sudo lsblk to display attached volumes and confirm the name of the problem volume. It usually begins with /dev/xvdf. Mine is /dev/xvdf1
Mount problem volume.

$ sudo mount /dev/xvdf1 /mnt
$ cd /mnt/etc/ufw

Open ufw configuration file

$ sudo vim ufw.conf

Press i to edit the file.
Change ENABLED=yes to ENABLED=no
Type Ctrl-C and type :wq to save the file.
Display content of ufw conf file using the command below and ensure that ENABLED=yes has been changed to ENABLED=no

$ sudo cat ufw.conf 

Unmount volume

$ cd ~
$ sudo umount /mnt

Detach problem volume from recovery instance and re-attach it to the original instance as /dev/sda1.

Start the original instance and you should be able to log back in

How to Setup Varnish HTTP Cache on an Ubuntu

Varnish Cache is a web application accelerator that can be used as a proxy to your Apache web server. The open-source software sits in front of your web server to serve web traffic very fast. If you are running multiple servers, Varnish Cache can also be used as a load balancer.

Varnish works by caching regularly requested web content on the system memory, and this ensures faster information retrieval if the same information is asked for several times.

$ sudo apt-get install varnish

By default, Apache listens on port 80 for HTTP traffic. We need to make some changes here. Instead of the default settings, Varnish will instead listen on port 80  and forward all traffic to Apache web server which we will configure to listen on port 8080.

$ sudo nano /etc/apache2/ports.conf
Listen 8080
<IfModule ssl_module>
        Listen 443
</IfModule>
<IfModule mod_gnutls.c>
        Listen 443
</IfModule>

Press CTRL + Xand hit Enter to save the file once you make the changes.
Next, edit the default Apache Virtual Host to listen to port 8080 too:

$ sudo service apache2 restart

 Configure Varnish HTTP Cache to listen on port 80

Next we will configure Varnish to listen on port 80 and forward all requests to our Apache web server.

We can do this by editing Varnish configuration file /etc/default/varnish

$ sudo nano  /etc/default/varnish
DAEMON_OPTS="-a :80 \
             -T localhost:6082 \
             -f /etc/varnish/default.vcl \
             -S /etc/varnish/secret \
             -s malloc,256m"

Then, press CTRL + Xand hit Enter to save the file.

Next, check the file ‘/etc/varnish/default.vcl’ using a nano text editor. You should see the below content and this means Varnish will forward http traffic to port 8080:

$ sudo nano /etc/varnish/default.vcl

File contents:

# Default backend definition. Set this to point to your content server.
backend default {
.host = "127.0.0.1";
.port = "8080";
}

We also need to edit the port on the file /lib/systemd/system/varnish.service’ file. To do so, type the command below:

$ sudo nano /lib/systemd/system/varnish.service

Change the default port from 6081 to 80 as shown below

[Unit]
Description=Varnish HTTP accelerator
Documentation=https://www.varnish-cache.org/docs/4.1/ man:varnishd
[Service]
Type=simple
LimitNOFILE=131072
LimitMEMLOCK=82000
ExecStart=/usr/sbin/varnishd -j unix,user=vcache -F -a :80 -T localhost:6082 -f$
ExecReload=/usr/share/varnish/varnishreload
ProtectSystem=full
ProtectHome=true
PrivateTmp=true
PrivateDevices=true
[Install]
WantedBy=multi-user.target

Then, press CTRL + Xand hit Enter to save the file.

Restart Apache, Varnish, and the Systemd Daemon

$ sudo systemctl restart apache2
$ sudo systemctl daemon-reload
$ sudo systemctl restart varnish

If the setup was successful, Varnish will now be the default HTTP Listener on port 80.

Testing the Setup

You can now try visiting your server one more time on a web browser:

http://public_ip_adress
or
http://example.com

The server traffic should now be handled by Varnish HTTP Cache software and forwarded to Apache.

To make sure that Varnish is working, use the curl command for verification purposes:

$ curl -I server_ip_address

You should get an output similar to the below text. If you see the line ‘Via: 1.1 varnish (Varnish/5.2)’, then Varnish is working like expected.

HTTP/1.1 200 OK
Date: Thu, 05 Jul 2018 20:56:11 GMT
Server: Apache/2.4.29 (Ubuntu)
Last-Modified: Fri, 29 Jun 2018 07:19:34 GMT
Vary: Accept-Encoding
Content-Type: text/html
X-Varnish: 7
Age: 0
Via: 1.1 varnish (Varnish/5.2)
ETag: W/"2aa6-56fc2ab77545d-gzip"
Accept-Ranges: bytes
Connection: keep-alive

How to check my phpmyadmin is secure on ubuntu server?

Useful Tips to Secure PhpMyAdmin Login Interface

  1. Change Default PhpMyAdmin Login URL
/etc/phpmyadmin/apache.conf

------------ On CentOS/RHEL and Fedora ------------ 
# vi /etc/httpd/conf.d/phpMyAdmin.conf

------------ On Debian and Ubuntu ------------ 
# /etc/phpmyadmin/apache.conf

Then add a new one as follows:
# Alias /phpmyadmin /usr/share/phpmyadmin
Alias /my /usr/share/phpmyadmin

------------ On Debian and Ubuntu ------------ 
# echo "Include /etc/phpmyadmin/apache.conf" >> /etc/apache2/apache2.conf
     ------------ On CentOS/RHEL and Fedora ------------ 
# systemctl restart nginx
# systemctl restart php-fpm

------------ On CentOS/RHEL and Fedora ------------ 
# systemctl restart httpd

------------ On Debian and Ubuntu ------------ 
# systemctl restart apache2

------------ On Debian and Ubuntu ------------ 
# systemctl restart nginx
# systemctl restart php5-fpm
  1. Enable HTTPS on PhpMyAdmin

  1. Password Protect on PhpMyAdmin
Add these lines to the Apache configuration file (/etc/apache2/sites-available/000-default.conf or /etc/httpd/conf/httpd.conf):

/etc/apache2/sites-available/000-default.conf – On Ubuntu
<Directory /usr/share/phpmyadmin>
    AuthType Basic
    AuthName "Restricted Content"
    AuthUserFile /etc/apache2/.htpasswd
    Require valid-user
</Directory>
/etc/httpd/conf/httpd.conf – On CentOS
 
<Directory /usr/share/phpmyadmin>
    AuthType Basic
    AuthName "Restricted Content"
    AuthUserFile /etc/httpd/.htpasswd
    Require valid-user
</Directory>
Then use htpasswd to generate a password file for an account that will be authorized to access the phpmyadmin login page. We will use /etc/apache2/.htpasswd and tecmint in this case:

---------- On Ubuntu/Debian Systems ---------- 
# htpasswd -c /etc/apache2/.htpasswd tecmint

---------- On CentOS/RHEL Systems ---------- 
# htpasswd -c /etc/httpd/.htpasswd tecmint
Enter password twice and then change the permissions and ownership of the file. This is to prevent anyone not in the www-data or apache group from being able to read .htpasswd:

# chmod 640 /etc/apache2/.htpasswd

---------- On Ubuntu/Debian Systems ---------- 
# chgrp www-data /etc/apache2/.htpasswd 

---------- On CentOS/RHEL Systems ---------- 
# chgrp apache /etc/httpd/.htpasswd 
Open your phpmyadmin url and you’ll see the authentication dialog before accessing the login page.
  1. Disable root Login to PhpMyAdmin
/etc/phpmyadmin/config.inc.php
/* Authentication type */
$cfg['Servers'][$i]['auth_type'] = 'cookie';
$cfg['Servers'][$i]['AllowRoot'] = false;

------------- On CentOS/RHEL Systems -------------
# systemctl restart httpd.service

------------- On Debian/Ubuntu Systems -------------
# systemctl restart apache2.service
  1. Prevent remote usage of phpmyadmin

  1. Change password frequently

  1. Check configuration /etc/phpmyadmin

How to check my server is secure or not?

Security Checks for Server

Susceptible to man-in-the-middle attacks – 3
Insecure SSL/TLS versions available
HSTS header not prepared for preload list inclusion
Secure cookies not used

Domain at risk of being hijacked – 4
Domain registry deletion protection not enabled
Domain registry transfer protection not enabled
Domain registry update protection not enabled
Domain renewal prohibited by registrar
Vulnerable to cross-site attacks
HttpOnly cookies not used

Emails can be fraudulently sent – 2
Lenient SPF filtering
DMARC not enabled
DNS is susceptible to man-in-the-middle attacks
DNSSEC not enabled
DNSSEC records prevent third parties from forging the records that guarantee a domain’s identity. DNSSEC should be configured for this domain.
EXPECTED:
true
FOUND:
false

Not susceptible to man-in-the-middle attacks – 9
SSL available
SSL does not expire soon
SSL has not expired
Strong SSL algorithm
Hostname matches SSL certificate
All traffic routed via HTTPS
HTTP Strict Transport Security (HSTS) enforced
HSTS header contains max-age
HSTS header contains includeSubDomains

Domain not at risk of being hijacked – 11
Domain does not expire soon
Domain has not expired
Domain registrar transfer protection enabled
Domain registrar deletion protection enabled
Domain registrar update protection enabled
Domain not flagged as inactive
Domain not pending deletion
Domain not pending restoration
Domain free of registry DNS resolution hold
Domain free of registrar DNS resolution hold
Domain renewal not prohibited by registry

No malware detected – 3
Not a suspected phishing page
Not a suspected malware provider
Not suspected of unwanted software

Vulnerabilities are harder to uncover – 4
X-Powered-By header not exposed
ASP.NET version header not exposed
ASP.NET version header not exposing specific ASP.net version
Server information header not exposed
No vulnerable software detected
No vulnerable software versions detected

Email sending is authenticated – 3
SPF enabled
SPF syntax correct
SPF ptr mechanism not used

No unnecessary open ports found – 7
No mail ports open and listening
No app ports open and listening
No user auth ports open and listening
No file sharing ports open and listening
No voice ports open and listening
No administration ports open and listening
No database ports open and listening

How To Set Up/Enable a Firewall with UFW on Ubuntu

UFW, or Uncomplicated Firewall, is an interface to iptables

Prerequisites

To follow this tutorial, you will need:

UFW is installed by default on Ubuntu. If it has been uninstalled for some reason, you can install it with sudo apt install ufw.

$ sudo nano /etc/default/ufw

Then make sure the value of IPV6 is yes.

$ sudo ufw default deny incoming
$ sudo ufw default allow outgoing
$ sudo ufw allow ssh
$ sudo ufw allow 22
$ sudo ufw enable
$ sudo ufw allow 80
$ sudo ufw allow 443
$ sudo ufw allow 6000:6007/tcp
$ sudo ufw allow 6000:6007/udp
$ sudo ufw allow from 203.0.113.4
$ sudo ufw allow from 203.0.113.4 to any port 22
$ sudo ufw allow from 203.0.113.0/24
$ sudo ufw allow from 203.0.113.0/24 to any port 22
$ sudo ufw deny http
$ sudo ufw deny from 203.0.113.4
$ sudo ufw status numbered
$ sudo ufw delete 2
$ sudo ufw delete allow http
$ sudo ufw delete allow 80
$ sudo ufw status verbose
$ sudo ufw disable
$ sudo ufw reset

check enabled sites apache2

Command show exact result

$ a2query -s

Check site-enabled*.conf + httpd.conf files and show you if the syntax is correct and the list of virtual host

$ apache2ctl -S