Thursday, August 29, 2013

Examples of linux find commands

The Linux Find Command is one of the most important and much used command in Linux sytems. Find command used to search and locate list of files and directories based on conditions you specify for files that match the arguments. Find can be used in variety of conditions like you can find files by permissionsusersgroupsfile typedatesize and other possible criteria.




1. Find Files Using Name in Current Directory

Find all the files whose name is tecmint.txt in a current working directory.
# find . -name tecmint.txt

./tecmint.txt

2. Find Files Under Home Directory

Find all the files under /home directory with name tecmint.txt.
# find /home -name tecmint.txt

/home/tecmint.txt

3. Find Files Using Name and Ignoring Case

Find all the files whose name is tecmint.txt and contains both capital and small letters in /homedirectory.
# find /home -iname tecmint.txt

./tecmint.txt
./Tecmint.txt

4. Find Directories Using Name

Find all directories whose name is Tecmint in / directory.
# find / -type d -name Tecmint

/Tecmint

5. Find PHP Files Using Name

Find all php files whose name is tecmint.php in a current working directory.
# find . -type f -name tecmint.php

./tecmint.php

6. Find all PHP Files in Directory

Find all php files in a directory.
# find . -type f -name "*.php"

./tecmint.php
./login.php
./index.php
Part II – Find Files Based on their Permissions

7. Find Files With 777 Permissions

Find all the files whose permissions are 777.
# find . -type f -perm 0777 -print

8. Find Files Without 777 Permissions

Find all the files without permission 777.
# find / -type f ! -perm 777

9. Find SGID Files with 644 Permissions

Find all the SGID bit files whose permissions set to 644.
# find / -perm 2644

10. Find Sticky Bit Files with 551 Permissions

Find all the Sticky Bit set files whose permission are 551.
# find / -perm 1551

11. Find SUID Files

Find all SUID set files.
# find / -perm /u=s

12. Find SGID Files

Find all SGID set files.
# find / -perm /g+s

13. Find Read Only Files

Find all Read Only files.
# find / -perm /u=r

14. Find Executable Files

Find all Executable files.
# find / -perm /a=x

15. Find Files with 777 Permissions and Chmod to 644

Find all 777 permission files and use chmod command to set permissions to 644.
# find / -type f -perm 0777 -print -exec chmod 644 {} \;

16. Find Directories with 777 Permissions and Chmod to 755

Find all 777 permission directories and use chmod command to set permissions to 755.
# find / -type d -perm 777 -print -exec chmod 755 {} \;

17. Find and remove single File

To find a single file called tecmint.txt and remove it.
# find . -type f -name "tecmint.txt" -exec rm -f {} \;

18. Find and remove Multiple File

To find and remove multiple files such as .mp3 or .txt, then use.
# find . -type f -name "*.txt" -exec rm -f {} \;

OR

# find . -type f -name "*.mp3" -exec rm -f {} \;

19. Find all Empty Files

To file all empty files under certain path.
# find /tmp -type f -empty

20. Find all Empty Directories

To file all empty directories under certain path.
# find /tmp -type d -empty

21. File all Hidden Files

To find all hidden files, use below command.
# find /tmp -type f -name ".*"
Part III – Search Files Based On Owners and Groups

22. Find Single File Based on User

To find all or single file called tecmint.txt under /root directory of owner root.
# find / -user root -name tecmint.txt

23. Find all Files Based on User

To find all files that belongs to user Tecmint under /home directory.
# find /home -user tecmint

24. Find all Files Based on Group

To find all files that belongs to group Developer under /home directory.
# find /home -group developer

25. Find Particular Files of User

To find all .txt files of user Tecmint under /home directory.
# find /home -user tecmint -iname "*.txt"
Part IV – Find Files and Directories Based on Date and Time

26. Find Last 50 Days Modified Files

To find all the files which are modified 50 days back.
# find / -mtime 50

27. Find Last 50 Days Accessed Files

To find all the files which are accessed 50 days back.
# find / -atime 50

28. Find Last 50-100 Days Modified Files

To find all the files which are modified more than 50 days back and less than 100 days.
# find / -mtime +50 –mtime -100

29. Find Changed Files in Last 1 Hour

To find all the files which are changed in last 1 hour.
# find / -cmin -60

30. Find Modified Files in Last 1 Hour

To find all the files which are modified in last 1 hour.
# find / -mmin -60

31. Find Accessed Files in Last 1 Hour

To find all the files which are accessed in last 1 hour.
# find / -amin -60
Part V – Find Files and Directories Based on Size32. Find 50MB Files
To find all 50MB files, use.
# find / -size 50M

33. Find Size between 50MB – 100MB

To find all the files which are greater than 50MB and less than 100MB.
# find / -size +50M -size -100M

34. Find and Delete 100MB Files

To find all 100MB files and delete them using one single command.
# find / -size +100M -exec rm -rf {} \;

35. Find Specific Files and Delete

Find all .mp3 files with more than 10MB and delete them using one single command.
# find / -type f -name *.mp3 -size +10M -exec ls -l {} \;

Tuesday, August 20, 2013

Add Jobs To cron Under Linux

How Do I install or create or edit my own cron jobs?

To edit your crontab file, type the following command at the UNIX / Linux shell prompt:
$ crontab -e

Syntax of crontab (field description)

The syntax is:
 
1 2 3 4 5 /path/to/command arg1 arg2
 
OR
 
1 2 3 4 5 /root/backup.sh
 
Where,
  • 1: Minute (0-59)
  • 2: Hours (0-23)
  • 3: Day (0-31)
  • 4: Month (0-12 [12 == December])
  • 5: Day of the week(0-7 [7 or 0 == sunday])
  • /path/to/command - Script or command name to schedule
Easy to remember format:
* * * * * command to be executed
- - - - -
| | | | |
| | | | ----- Day of week (0 - 7) (Sunday=0 or 7)
| | | ------- Month (1 - 12)
| | --------- Day of month (1 - 31)
| ----------- Hour (0 - 23)
------------- Minute (0 - 59)
Your cron job looks as follows for system jobs:
1 2 3 4 5 USERNAME /path/to/command arg1 arg2
OR
1 2 3 4 5 USERNAME /path/to/script.sh

Example: Run backup cron job script

If you wished to have a script named /root/backup.sh run every day at 3am, your crontab entry would look like as follows. First, install your cronjob by running the following command:
# crontab -e
Append the following entry:
0 3 * * * /root/backup.sh
Save and close the file.

More examples

To run /path/to/command five minutes after midnight, every day, enter:
5 0 * * * /path/to/command
Run /path/to/script.sh at 2:15pm on the first of every month, enter:
15 14 1 * * /path/to/script.sh
Run /scripts/phpscript.php at 10 pm on weekdays, enter:
0 22 * * 1-5 /scripts/phpscript.php
Run /root/scripts/perl/perlscript.pl at 23 minutes after midnight, 2am, 4am ..., everyday, enter:
23 0-23/2 * * * /root/scripts/perl/perlscript.pl
Run /path/to/unixcommand at 5 after 4 every Sunday, enter:
5 4 * * sun /path/to/unixcommand

How do I use operators?

An operator allows you to specifying multiple values in a field. There are three operators:
  1. The asterisk (*) : This operator specifies all possible values for a field. For example, an asterisk in the hour time field would be equivalent to every hour or an asterisk in the month field would be equivalent to every month.
  2. The comma (,) : This operator specifies a list of values, for example: "1,5,10,15,20, 25".
  3. The dash (-) : This operator specifies a range of values, for example: "5-15" days , which is equivalent to typing "5,6,7,8,9,....,13,14,15" using the comma operator.

How do I disable email output?

By default the output of a command or a script (if any produced), will be email to your local email account. To stop receiving email output from crontab you need to append >/dev/null 2>&1. For example:
0 3 * * * /root/backup.sh >/dev/null 2>&1
To mail output to particular email account let us say vivek@nixcraft.in you need to define MAILTO variable as follows:
MAILTO="vivek@nixcraft.in"
0 3 * * * /root/backup.sh >/dev/null 2>&1

Task: List all your cron jobs

Type the following command:
# crontab -l
# crontab -u username -l

To remove or erase all crontab jobs use the following command:
# crontab -r
crontab -r -u username

Use special string to save time

Instead of the first five fields, you can use any one of eight special strings. It will not just save your time but it will improve readability.
Special stringMeaning
@rebootRun once, at startup.
@yearlyRun once a year, "0 0 1 1 *".
@annually(same as @yearly)
@monthlyRun once a month, "0 0 1 * *".
@weeklyRun once a week, "0 0 * * 0".
@dailyRun once a day, "0 0 * * *".
@midnight(same as @daily)
@hourly Run once an hour, "0 * * * *".     

Friday, August 16, 2013

crontab settings

Introduction

Cron is a system daemon used to execute desired tasks (in the background) at designated times.
A crontab is a simple text file with a list of commands meant to be run at specified times. It is edited with a command-line utility. These commands (and their run times) are then controlled by the cron daemon, which executes them in the system background. Each user has a crontab file which specifies the actions and times at which they should be executed, these jobs will run regardless of whether the user is actually logged into the system. There is also a root crontab for tasks requiring administrative privileges. This system crontab allows scheduling of systemwide tasks (such as log rotations and system database updates).

On Gnome-based Ubuntu systems Gnome Scheduled tasks tool (from the gnome-schedule package) in Applications --> System Tools provides a graphical interface with prompting for using Cron. The project website is at http://gnome-schedule.sourceforge.net/; the software is installable from the Software Center or by typing
sudo apt-get install gnome-schedule
 
 
 
You can create a cron.log file to contain just the CRON entries that show up in syslog. Note that CRON jobs will still show up in syslog if you follow the following directions.
Open the file


/etc/rsyslog.d/50-default.conf
 
Find the line that starts with:
#cron.* uncomment that line, save the file, and restart rsyslog:
sudo service rsyslog restart You should now see a cron log file here:
/var/log/cron.log Cron activity will now be logged to this file (in addition to syslog).


 

 

tcptrack command

The tcptrack command displays the status of TCP connections that it sees on a given network interface. tcptrack monitors their state and displays information such as state, source/destination addresses and bandwidth usage in a sorted, updated list very much like the top command.

# tcptrack -i eth0


Sample outputs:
Fig.01: tcptrack in Action

(for ubuntu apt-get -y install tcptrack)

How to find out Active Connections or which Ports are open/listening on Linux

While managing a server or your home desktop, sometimes you might want to check out which ports are currently being used by which applications, what all TCP/UDP connections are active at the moment or other similar cases. There are two basic command line tools present in almost all the Linux/UNIX based systems - netstat and lsof, that might help you out with such queries.
Before starting it would be good to know about these two commands.
  • Netstat is used to display network connections, routing tables and a whole bunch of network and interface stats.
  • lsof on the other hand is used to list out open files. So, if you want to find out what all files are currently open just run lsof.  And since in Linux "Everything is a File", we can use lsof to print network connections too.
Lets start learning by resolving common queries.

How to display a list of open ports?

This can be done using both netstat and lsof.
[shredder12]$ netstat -n -A inet
-n is used to display numeric addresses instead of trying to determine symbolic hostnames
-A is used to define the address family we are concerned with. Here its internet connections on IPv4 network, so inet(user inet6 for IPv6 connections).
[shredder12]$ lsof -i

How to display a list of Active connections?

In case you noticed the output of the command mentioned above, they actually show the active connections.
[shredder12]$ netstat -n -A  inet
[shredder12]$ lsof -i

How to display a list of listening ports?

Use the --listen flag with netstat to get a list.
[shredder12]$ netstat --listen -A inet

How to display a list of active TCP or UDP connections?

With netstat, we can use the flag -t to denote TCP connections only.
[shredder12]$ netstat -n -A inet -t
similarly, -u for UDP connections.
The -i flag of lsof provides a lot of configurable options. Use the following command to filter out TCP connections.
[shredder12]$ lsof -i4TCP
Please note no space between i4 and TCP. This means TCP connections on IPv4 network. Similary one can use i6 for IPv6 and UDP for udp connections.

How to find out all the ports being used by a single application or process using PID?

With netstat option -p you can even list out the program a port/socket is associated with. So, lets run -p with our active connections command and grep the pid.
[shredder12]$ netstat -A inet -n -p | grep 1413
You can find out the PID of a process using ps or pgrep.

[shredder12]$ ps -e | grep firefox

[shredder12]$ pgrep firefox

How to find out all the files being used by a program or application using PID?

Since we are concerned with files, lsof comes into play here. Here the -p option used along with the PID to catch the files associated with that process.
[shredder12]$ lsof -i4TCP -a -p 1413

The -a flag is used to tell lsof to AND the result of all the options used.
I hope this will help you out.

Monday, August 12, 2013

Ubuntu root password recovery

Reset Your forgotten Ubuntu Password in 2 minutes or less


First you’ll want to make sure to choose the regular boot kernel that you use (typically just the default one), and then use the “e” key to choose to edit that boot option.

Now just hit the down arrow key over to the “kernel” option, and then use the “e” key to switch to edit mode for the kernel option.

You’ll first be presented with a screen that looks very similar to this one:

You’ll want to remove the “ro quiet splash” part with the backspace key, and then add this onto the end:
rw init=/bin/bash

Once you hit enter after adjusting the kernel line, you’ll need to use the B key to choose to boot with that option.

At this point the system should boot up very quickly to a command prompt.
Changing the Actual Password
You can use the following command to reset your password:
passwd <username>
For example my username being geek I used this command:
passwd geek

After changing your password, use the following commands to reboot your system. (The sync command makes sure to write out data to the disk before rebooting)
sync
reboot –f

Tuesday, July 9, 2013

Configure Primary DNS Server in redhat 6 Step by Step

Domain Name System

The Domain Name System (DNS) is the crucial glue that keeps computer networks in harmony by converting human-friendly hostnames to the numerical IP addresses computers require to communicate with each other. DNS is one of the largest and most important distributed databases the world depends on by serving billions of DNS requests daily for public IP addresses. Most public DNS servers today are run by larger ISPs and commercial companies but private DNS servers can also be useful for private home networks. This article will explo

To Check IP
[root@www Desktop]# ifconfig
eth0      Link encap:Ethernet  HWaddr 00:0C:29:84:6D:8C 
          inet addr:10.90.12.1  Bcast:10.90.12.255  Mask:255.255.255.0
          inet6 addr: fe80::20c:29ff:fe84:6d8c/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:6624 errors:0 dropped:0 overruns:0 frame:0
          TX packets:1474 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000
          RX bytes:442710 (432.3 KiB)  TX bytes:1901220 (1.8 MiB)
          Interrupt:19 Base address:0x2000

eth1      Link encap:Ethernet  HWaddr 00:0C:29:84:6D:96 
          inet addr:10.23.151.66  Bcast:10.23.159.255  Mask:255.255.224.0
          inet6 addr: fe80::20c:29ff:fe84:6d96/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:13927 errors:0 dropped:0 overruns:0 frame:0
          TX packets:7518 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000
          RX bytes:9215651 (8.7 MiB)  TX bytes:948169 (925.9 KiB)
          Interrupt:19 Base address:0x2080

lo        Link encap:Local Loopback 
          inet addr:127.0.0.1  Mask:255.0.0.0
          inet6 addr: ::1/128 Scope:Host
          UP LOOPBACK RUNNING  MTU:16436  Metric:1
          RX packets:8 errors:0 dropped:0 overruns:0 frame:0
          TX packets:8 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:0
          RX bytes:480 (480.0 b)  TX bytes:480 (480.0 b)

To Set DNS Server IP
vi /etc/sysconfig/network-scripts/ifcfg-eth0

EVICE=eth0
HWADDR=00:0c:29:84:6d:8c
NM_CONTROLLED=no
ONBOOT=yes
IPADDR=10.90.12.1
BOOTPROTO=none
NETMASK=255.255.255.0
DNS=10.90.12.1
TYPE=Ethernet
IPV6INIT=no
USERCTL=no

save :wq

To Set Host Name
[root@station Desktop]# vim /etc/sysconfig/network

NETWORKING=yes
HOSTNAME=station.example.com

save :wq

[root@station Desktop]# vim /etc/hosts
0.90.12.1      station.example.com     station

save :wq

[root@station Desktop]# vim /etc/resolv.conf
search station.example.com
nameserver 10.90.12.1

save :wq

[root@station Desktop]# hostname station.example.com

[root@station Desktop]# hostname
station.example.com

To Install Package
[root@station Desktop]# yum install bind*
Loaded plugins: fastestmirror, refresh-packagekit, security
Repository 'yum' is missing name in configuration, using id
Loading mirror speeds from cached hostfile
Setting up Install Process
Package 32:bind-utils-9.7.3-8.P3.el6.i686 already installed and latest version
Package 32:bind-libs-9.7.3-8.P3.el6.i686 already installed and latest version
Resolving Dependencies
--> Running transaction check
---> Package bind.i686 32:9.7.3-8.P3.el6 will be installed
---> Package bind-chroot.i686 32:9.7.3-8.P3.el6 will be installed
---> Package bind-dyndb-ldap.i686 0:0.2.0-7.el6 will be installed
--> Finished Dependency Resolution

Dependencies Resolved

================================================================================
 Package                Arch        Version                    Repository  Size
================================================================================
Installing:
 bind                   i686        32:9.7.3-8.P3.el6          yum        3.9 M
 bind-chroot            i686        32:9.7.3-8.P3.el6          yum         67 k
 bind-dyndb-ldap        i686        0.2.0-7.el6                yum         49 k

Transaction Summary
================================================================================
Install       3 Package(s)

Total download size: 4.0 M
Installed size: 7.1 M
Is this ok [y/N]: y
Downloading Packages:
(1/3): bind-9.7.3-8.P3.el6.i686.rpm                      | 3.9 MB     00:00    
(2/3): bind-chroot-9.7.3-8.P3.el6.i686.rpm               |  67 kB     00:00    
(3/3): bind-dyndb-ldap-0.2.0-7.el6.i686.rpm              |  49 kB     00:00    
--------------------------------------------------------------------------------
Total                                            20 MB/s | 4.0 MB     00:00    
Running rpm_check_debug
Running Transaction Test
Transaction Test Succeeded
Running Transaction
Warning: RPMDB altered outside of yum.
  Installing : 32:bind-9.7.3-8.P3.el6.i686                                  1/3
  Installing : 32:bind-chroot-9.7.3-8.P3.el6.i686                           2/3
  Installing : bind-dyndb-ldap-0.2.0-7.el6.i686                             3/3

Installed:
  bind.i686 32:9.7.3-8.P3.el6            bind-chroot.i686 32:9.7.3-8.P3.el6   
  bind-dyndb-ldap.i686 0:0.2.0-7.el6   

Complete!
[root@station Desktop]#

 To Copy named.conf file
[root@station Desktop]# cp /etc/named.conf  /var/named/chroot/etc/named.conf


To Change directory
 cd /var/named/chroot/etc/

To edit configuration file
[root@station etc]#vim named.conf
options {
        directory       "/var/named";
};

zone "example.com" IN {
        type master;
        file "for.zone";
};

zone "12.90.10.in-addr.arpa" IN {
        type master;
        file "rev.zone";
};

save :wq

To Change Group Name
[root@station etc]# chgrp named named.conf

To Copy File same Location
[root@station etc]# cp /var/named/named.localhost /var/named/chroot/var/named/for.zone
[root@station etc]# cp /var/named/named.loopback /var/named/chroot/var/named/rev.zone

To change directory
[root@station etc]# cd /var/named/chroot/var/named/

To edit configuration file
[root@station named]# vim for.zone
$TTL 1D
@       IN SOA  example.com. root.example.com. (
                                        0       ; serial
                                        1D      ; refresh
                                        1H      ; retry
                                        1W      ; expire
                                        3H )    ; minimum
@       IN      NS      station.example.com.
station IN      A       10.90.12.1

save :wq

To edit configuration file
[root@station named]# vim rev.zone
$TTL 1D
@       IN SOA  example.com. root.example.com. (
                                        0       ; serial
                                        1D      ; refresh
                                        1H      ; retry
                                        1W      ; expire
                                        3H )    ; minimum
@       IN      NS      station.example.com.
1       IN      PTR     station.example.com.

save :wq

To Change Group Name
[root@station named]# chgrp named for.zone
[root@station named]# chgrp named rev.zone
[root@station named]# ll
total 8
-rw-r-----. 1 root named 190 Jun  1 19:12 for.zone
-rw-r-----. 1 root named 196 Jun  1 19:15 rev.zone
[root@station named]#

To Restart Service & On
[root@station named]# service named restart
Stopping named:                                            [  ok  ]
Starting named:                                            [  ok  ]

[root@station named]# chkconfig named on

To Check Named Server
[root@station named]# dig 10.90.12.1

; <<>> DiG 9.7.3-P3-RedHat-9.7.3-8.P3.el6 <<>> 10.90.12.1
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NXDOMAIN, id: 23819
;; flags: qr rd ra; QUERY: 1, ANSWER: 0, AUTHORITY: 1, ADDITIONAL: 0

;; QUESTION SECTION:
;10.90.12.1.            IN    A

;; AUTHORITY SECTION:
.            10800    IN    SOA    a.root-servers.net. nstld.verisign-grs.com. 2012060501 1800 900 604800 86400

;; Query time: 193 msec
;; SERVER: 113.193.1.14#53(113.193.1.14)
;; WHEN: Fri Jun  1 19:17:27 2012
;; MSG SIZE  rcvd: 103

[root@station named]# dig station.example.com

; <<>> DiG 9.7.3-P3-RedHat-9.7.3-8.P3.el6 <<>> station.example.com
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 24133
;; flags: qr aa rd ra; QUERY: 1, ANSWER: 1, AUTHORITY: 1, ADDITIONAL: 0

;; QUESTION SECTION:
;station.example.com.        IN    A

;; ANSWER SECTION:
station.example.com.    86400    IN    A    10.90.12.1

;; AUTHORITY SECTION:
example.com.        86400    IN    NS    station.example.com.

;; Query time: 1 msec
;; SERVER: 10.90.12.1#53(10.90.12.1)
;; WHEN: Fri Jun  1 19:17:47 2012
;; MSG SIZE  rcvd: 67

[root@station named]#


Client end Setting



[admin@station1]$vim /etc/resolve.conf

search station.example.com
nameserver 10.90.12.1
Save :wq
[admin@station1]$ dig station.example.com

; <<>> DiG 9.7.3-P3-RedHat-9.7.3-8.P3.el6 <<>> station.example.com
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 24133
;; flags: qr aa rd ra; QUERY: 1, ANSWER: 1, AUTHORITY: 1, ADDITIONAL: 0

;; QUESTION SECTION:
;station.example.com.        IN    A

;; ANSWER SECTION:
station.example.com.    86400    IN    A    10.90.12.1

;; AUTHORITY SECTION:
example.com.        86400    IN    NS    station.example.com.

;; Query time: 1 msec
;; SERVER: 10.90.12.1#53(10.90.12.1)
;; WHEN: Fri Jun  1 19:17:47 2012
;; MSG SIZE  rcvd: 67