Monday, December 5, 2016

Raid configuration and troubleshooting steps

1. Create a new RAID array

Create (mdadm —create) is used to create a new array:
1
mdadm --create --verbose /dev/md0 --level=1 /dev/sda1 /dev/sdb2
or using the compact notation:
1
mdadm -Cv /dev/md0 -l1 -n2 /dev/sd[ab]1

2. /etc/mdadm.conf

/etc/mdadm.conf or /etc/mdadm/mdadm.conf (on debian) is the main configuration file for mdadm. After we create our RAID arrays we add them to this file using:
1
mdadm --detail --scan >> /etc/mdadm.conf
or on debian
1
mdadm --detail --scan >> /etc/mdadm/mdadm.conf

3. Remove a disk from an array

We can’t remove a disk directly from the array, unless it is failed, so we first have to fail it (if the drive it is failed this is normally already in failed state and this step is not needed):
1
mdadm --fail /dev/md0 /dev/sda1
and now we can remove it:
1
mdadm --remove /dev/md0 /dev/sda1
This can be done in a single step using:
1
mdadm /dev/md0 --fail /dev/sda1 --remove /dev/sda1

4. Add a disk to an existing array

We can add a new disk to an array (replacing a failed one probably):
1
mdadm --add /dev/md0 /dev/sdb1

5. Verifying the status of the RAID arrays

We can check the status of the arrays on the system with:
1
cat /proc/mdstat
or
1
mdadm --detail /dev/md0
The output of this command will look like:
1
2
3
4
5
6
7
8
9
10
cat /proc/mdstat
Personalities : [raid1]
md0 : active raid1 sdb1[1] sda1[0]
104320 blocks [2/2] [UU]

md1 : active raid1 sdb3[1] sda3[0]
19542976 blocks [2/2] [UU]

md2 : active raid1 sdb4[1] sda4[0]
223504192 blocks [2/2] [UU]
here we can see both drives are used and working fine – U. A failed drive will show as F, while a degraded array will miss the second disk 
Note: while monitoring the status of a RAID rebuild operation using watch can be useful:
1
watch cat /proc/mdstat

6. Stop and delete a RAID array

If we want to completely remove a raid array we have to stop if first and then remove it:
1
2
mdadm --stop /dev/md0
mdadm --remove /dev/md0
and finally we can even delete the superblock from the individual drives:
1
mdadm --zero-superblock /dev/sda
Finally in using RAID1 arrays, where we create identical partitions on both drives this can be useful to copy the partitions from sda to sdb:
1
sfdisk -d /dev/sda | sfdisk /dev/sdb
(this will dump the partition table of sda, removing completely the existing partitions on sdb, so be sure you want this before running this command, as it will not warn you at all).
There are many other usages of mdadm particular for each type of RAID level, and I would recommend to use the manual page (man mdadm) or the help (mdadm —help) if you need more details on its usage. Hopefully these quick examples will put you on the fast track with how mdadm works.

Check the status of a raid device


[root@bcane ~]# mdadm --detail /dev/md10  
/dev/md10:  
 Version : 1.2  
 Creation Time : Sat Jul 2 13:56:38 2011  
 Raid Level : raid1  
 Array Size : 26212280 (25.00 GiB 26.84 GB)  
 Used Dev Size : 26212280 (25.00 GiB 26.84 GB)  
 Raid Devices : 2  
 Total Devices : 2  
 Persistence : Superblock is persistent  

 Update Time : Sat Jul 2 13:56:47 2011  
 State : clean, resyncing  
Active Devices : 2  
Working Devices : 2  
Failed Devices : 0  
 Spare Devices : 0  

Rebuild Status : 10% complete  

 Name : bcane.virtuals.local:10 (local to host bcane.virtuals.local)  
 UUID : 10a96ed5:92dc48e6:04b2bf43:3539e089  
 Events : 1  

 Number Major Minor RaidDevice State  
 0 8 33 0 active sync /dev/sdc1  
 1 8 49 1 active sync /dev/sdd1

In order to remove a drive it must first be marked as faulty. A drive can be marked as faulty either through a failure or if you want to manually mark a drive as faulty you can use the -f/--fail flag.
[root@bcane ~]# mdadm /dev/md10 -f /dev/sdc1
mdadm: set /dev/sdc1 faulty in /dev/md10  

[root@bcane ~]# mdadm --detail /dev/md10
/dev/md10:  
 Version : 1.2  
 Creation Time : Sat Jul 2 13:56:38 2011  
 Raid Level : raid1  
 Array Size : 26212280 (25.00 GiB 26.84 GB)  
 Used Dev Size : 26212280 (25.00 GiB 26.84 GB)  
 Raid Devices : 2  
 Total Devices : 2  
 Persistence : Superblock is persistent  

 Update Time : Sat Jul 2 14:00:18 2011  
 State : active, degraded  
Active Devices : 1  
Working Devices : 1  
Failed Devices : 1  
 Spare Devices : 0  

 Name : bcane.virtuals.local:10 (local to host bcane.virtuals.local)  
 UUID : 10a96ed5:92dc48e6:04b2bf43:3539e089  
 Events : 19  

 Number Major Minor RaidDevice State  
 0 0 0 0 removed  
 1 8 49 1 active sync /dev/sdd1  

 0 8 33 - faulty spare /dev/sdc1

Now that the drive is marked as failed/faulty you can remove it using the -r/--remove flag.
[root@bcane ~]# mdadm /dev/md10 -r /dev/sdc1
mdadm: hot removed /dev/sdc1 from /dev/md10  

[root@bcane ~]# mdadm --detail /dev/md10
/dev/md10:  
 Version : 1.2  
 Creation Time : Sat Jul 2 13:56:38 2011  
 Raid Level : raid1  
 Array Size : 26212280 (25.00 GiB 26.84 GB)  
 Used Dev Size : 26212280 (25.00 GiB 26.84 GB)  
 Raid Devices : 2  
 Total Devices : 1  
 Persistence : Superblock is persistent  

 Update Time : Sat Jul 2 14:02:04 2011  
 State : active, degraded  
Active Devices : 1  
Working Devices : 1  
Failed Devices : 0  
 Spare Devices : 0  

 Name : bcane.virtuals.local:10 (local to host bcane.virtuals.local)  
 UUID : 10a96ed5:92dc48e6:04b2bf43:3539e089  
 Events : 20  

 Number Major Minor RaidDevice State  
 0 0 0 0 removed  
 1 8 49 1 active sync /dev/sdd1

If you want to re-add the device you can do so with the -a flag.
[root@bcane ~]# mdadm /dev/md10 -a /dev/sdc1
mdadm: re-added /dev/sdc1  

[root@bcane ~]# mdadm --detail /dev/md10
/dev/md10:  
 Version : 1.2  
 Creation Time : Sat Jul 2 13:56:38 2011  
 Raid Level : raid1  
 Array Size : 26212280 (25.00 GiB 26.84 GB)  
 Used Dev Size : 26212280 (25.00 GiB 26.84 GB)  
 Raid Devices : 2  
 Total Devices : 2  
 Persistence : Superblock is persistent  

 Update Time : Sat Jul 2 18:02:21 2011  
 State : clean, degraded, recovering  
Active Devices : 1  
Working Devices : 2  
Failed Devices : 0  
 Spare Devices : 1  

Rebuild Status : 4% complete  

 Name : bcane.virtuals.local:10 (local to host bcane.virtuals.local)  
 UUID : 10a96ed5:92dc48e6:04b2bf43:3539e089  
 Events : 23  

 Number Major Minor RaidDevice State  
 0 8 33 0 spare rebuilding /dev/sdc1  
 1 8 49 1 active sync /dev/sdd1

One thing to keep an eye out for is that you need to specify the raid device when running these commands. If they are performed without specifying the raid device the flags take on a new meaning.

Hotplug

mdadm versions < 3.1.2

In older version of mdadm, the hotplug & hot-unplug support is present, but for full automatic functionality, we need to employ some bits of scripting. First of all, look what madm provides by manually trying its features from command line:

Hot-unplug from command line

  • If the physical disk is still alive:
mdadm --fail /dev/mdX /dev/sdYZ
mdadm --remove /dev/mdX /dev/sdYZ 
Do this for all RAIDs containing partitions of the failed disk. Then the disk can be hot-unplugged without any problems
  • If the physical disk is dead or unplugged, just do
mdadm /dev/mdX --fail detached --remove detached

Fully automated hotplug and hot-unplug using UDEV rules

In case you need fully automatic hot-plug and hot-unplug events handling, the UDEV "add" and "remove" events can be used for this.
Note: the following code had been validated on Linux Debian 5 (Lenny), with kernel 2.6.26 and udevd version 125.
Important notes:
  • the rule for "add" event MUST be placed in a file positioned after the "persistent_storage.rules" file, because it uses the ENV{ID_FS_TYPE} condition, which is produced by the persistent_storage.rules file during the "add" event processing.
  • The rule for "remove" event can reside in any file in the UDEV rules chain, but let's keep it together with the "add" rule :-)
For this reason, in Debian Lenny I placed the mdadm hotplug rules in file /etc/udev/rules.d/66-mdadm-hotplug.rules This is the content of the file:
SUBSYSTEM!="block", GOTO="END_66_MDADM"
ENV{ID_FS_TYPE}!="linux_raid_member", GOTO="END_66_MDADM"
ACTION=="add",  RUN+="/usr/local/sbin/handle-add-old $env{DEVNAME}"
ACTION=="remove", RUN+="/usr/local/sbin/handle-remove-old $name"
LABEL="END_66_MDADM"
(these rules are based on the UDEV rules contained in the hot-unplug patches by Doug Ledford)
And here are the scripts which are called from these rules:
#!/bin/bash
#This is the /usr/local/sbin/handle-add-old
MDADM=/sbin/mdadm
LOGGER=/usr/bin/logger
mdline=`mdadm --examine --scan $1` #mdline contains something like "ARRAY /dev/mdX level=raid1 num-devices=2 UUID=..."
mddev=${mdline#* }                 #delete "ARRAY " and return the result as mddev
mddev=${mddev%% *}                 #delete everything behind /dev/mdX
$LOGGER $0 $1
if [ -n "$mddev" ]; then
   $LOGGER "Adding $1 into RAID device $mddev"
   log=`$MDADM -a $mddev $1 2>&1`
   $LOGGER "$log"
fi
#!/bin/bash
#This is the /usr/local/sbin/handle-remove-old
MDADM=/sbin/mdadm
LOGGER=/usr/bin/logger
$LOGGER "$0 $1"
mdline=`grep $1 /proc/mdstat`  #mdline contains something like "md0 : active raid1 sda1[0] sdb1[1]"
mddev=${mdline% :*}            #delete everything from " :" till the end of line and return the result as mddev
$LOGGER "$0: Trying to remove $mdpart from $mddev"
log=`$MDADM /dev/$mddev --fail detached --remove detached 2>&1`
$LOGGER $log

mdadm versions > 3.1.2

The hot-unplug support introduced in mdadm version 3.1.2 removed the necessity of scripting you see above. If your Linux distribution contains this or later version of mdadm, you hopefully have fully automatic hotplug and hot-unplug without any hassles.

Examples of behavior WITHOUT the automatic hotplug/hot-unplug

Let's have the following RAID configuration:
# cat /proc/mdstat
Personalities : [raid1]
md0 : active raid1 sda1[0] sdb1[1]
      3903680 blocks [2/2] [UU]

md1 : active raid1 sda2[0] sdb2[1]
      224612672 blocks [2/2] [UU]
The md0 contains the system, md1 is for data (but is not used yet).

Hot-unplug

If we hot-unplug the disk /dev/sda, the /proc/mdstat will show:
# cat /proc/mdstat
Personalities : [raid1]
md0 : active raid1 sda1[2](F) sdb1[1]
      3903680 blocks [2/1] [_U]

md1 : active raid1 sda2[0] sdb2[1]
      224612672 blocks [2/2] [UU]
We see that sda1 has role [2]. Since RAID1 needs only 2 components - [0] and [1], the [2] means "Spare disk". And it is (F)ailed.
But why the system thinks that /dev/sda2 in /dev/md1 is still OK? Because my system hasn't tried to access /dev/md1 yet (I have no data on /dev/md1). The /dev/sda2 will be marked as fault automatically as soon as I try to access /dev/md1:
# dd if=/dev/md1 of=/dev/null bs=1 count=1
1+0 records in
1+0 records out
1 byte (1 B) copied, 0.0184819 s, 0.1 kB/s
# cat /proc/mdstat
Personalities : [raid1]
md0 : active raid1 sda1[2](F) sdb1[1]
      3903680 blocks [2/1] [_U]

md1 : active raid1 sda2[2](F) sdb2[1]
      224612672 blocks [2/1] [_U]
At any point after the disk has been unplugged, we can remove its partitions from an array only by this command:
# mdadm /dev/md0 --fail detached --remove detached
mdadm: hot removed 8:1

Removing a RAID Device

To remove an existing RAID device, first deactivate it by running the following command as root:
mdadm --stop raid_device
Once deactivated, remove the RAID device itself:
mdadm --remove raid_device
Finally, zero superblocks on all devices that were associated with the particular array:
mdadm --zero-superblock component_device

Example 6.5. Removing a RAID device
Assume the system has an active RAID device, /dev/md3, with the following layout (that is, the RAID device created in Example 6.4, “Extending a RAID device”):
~]# mdadm --detail /dev/md3 | tail -n 4
    Number   Major   Minor   RaidDevice State
       0       8        1        0      active sync   /dev/sda1
       1       8       17        1      active sync   /dev/sdb1
       2       8       33        2      active sync   /dev/sdc1
In order to remove this device, first stop it by typing the following at a shell prompt:
~]# mdadm --stop /dev/md3
mdadm: stopped /dev/md3
Once stopped, you can remove the /dev/md3 device by running the following command:
~]# mdadm --remove /dev/md3
Finally, to remove the superblocks from all associated devices, type:
~]# mdadm --zero-superblock /dev/sda1 /dev/sdb1 /dev/sdc1

Thursday, November 17, 2016

Yum and RPM database rebuild

Yum and RPM database rebuild


rpmdb: PANIC: fatal region error detected; run recovery
error: db3 error(-30974) from dbenv->open: DB_RUNRECOVERY: Fatal error, run database recovery
error: cannot open Packages index using db3 – (-30974)
error: cannot open Packages database in /var/lib/rpm
CRITICAL:yum.main:
Error: rpmdb open failed
How do I fix this problem on a CentOS / RHEL based system?

This is quite the messy situation. You may fix this by cleaning out rpm database. To minimize risk, make a backup of files in /var/lib/rpm/ using cp command:
mkdir /root/backups.rpm.mm_dd_yyyy/
cp -avr /var/lib/rpm/ /root/backups.rpm.mm_dd_yyyy/

To find list of __db* file, enter:
# ls -l /var/lib/rpm/_*
Sample outputs:
-rw-r--r-- 1 root root   24576 Jan 28 04:00 /var/lib/rpm/__db.001
-rw-r--r-- 1 root root  229376 Jan 28 04:00 /var/lib/rpm/__db.002
-rw-r--r-- 1 root root 1318912 Jan 28 04:00 /var/lib/rpm/__db.003
-rw-r--r-- 1 root root  753664 Jan 28 04:00 /var/lib/rpm/__db.004
To fix this problem, try:
# rm -f /var/lib/rpm/__db*
# db_verify /var/lib/rpm/Packages
# rpm --rebuilddb
# yum clean all

Verify that error has gone with the following yum command
# yum update

Monday, November 7, 2016

Restore deleted files in ext4 file system with the reference of file name in Redhat 6.x centos 6.x

Restore Ext4 deleted files with the reference of file name in Redhat 6.x centos 6.x by using below script

Pre-requisites - Below packages have to be installed at first place.
===================================================================

e2fsprogs.x86_64                       1.41.12-14.el6               @anaconda-RedHatEnterpriseLinux-201301301459.x86_64/6.4
e2fsprogs-devel.i686                   1.41.12-14.el6               @rhel-source
e2fsprogs-devel.x86_64                 1.41.12-14.el6               @rhel-source
e2fsprogs-libs.i686                    1.41.12-14.el6               @rhel-source
e2fsprogs-libs.x86_64                  1.41.12-14.el6               @anaconda-RedHatEnterpriseLinux-

Script:
======


#!/bin/sh

time=`date +%D-%M-%Y-%T`

echo "Time is now $time"

printf "Please Enter the full path of the disk EX: /dev/VGname/LVname.. or /dev/sdb1..etc:"
read name
printf "\n Please Enter the file name which got deleted (Case sensitive) :"
read filename

printf "\n Have you unmounted the file system before we recover your deleted file, If not, Please unmount first to avoid any demage to the files"

printf "\n Do want to continue, please say yes only if you have unmounted the file system (y/n):"

read de

case $de in
y)
break
;;
n)
exit 0
;;

*)

echo "Oops!!! Entered invalid option"
exit 0
 
esac

extundelete $name --restore-file $filename > /tmp/restore_output

cat /tmp/restore_output | grep -i Successfully restored file $filename  > /dev/null

if [ `echo $? == 0` ]
then
echo "Your file has successfully restored, Pls check the file under /RECOVERED_FILES"
else
   echo "Sorry something went wrong in the script!!! Pls look out for other options to recover the files"
fi

Saturday, November 5, 2016

How to scan up UDP and TCP ports using Nmap

TCP / UDP port scan using Nmap

UDP is a connectionless protocol which means it basically just sends packets out to the specified destination. TCP is connection-oriented which means it establishes a connection to the other end using the ‘3-way handshake’.

So it makes sense to apply the ‘telnet’ paradigm to TCP – you make connection to a specific host and port, you still remain connected (for a period of time) even if you aren’t sending any data and you can send and receive data continuously without having to reconnect in between.

UDP on the other hand doesn’t really fit the telnet model – its more of a fire-and-forget system where you fire-off a series of packets towards the destination. You then go on with something else (or just wait doing nothing) until (or if) the remote process sends some packets back.

Note that UDP scanning is problematic because of the lack of a confirming SYN-ACK or other packet as with TCP. As such, many false positives can occur from UDP port scans


Example for UDP:
nmap -sU -p 3478 192.168.1.11

Starting Nmap 6.00 ( http://nmap.org ) at 2012-06-13 20:43 EDT
Nmap scan report for example.com (192.168.1.11)
Host is up (0.096s latency).
PORT     STATE         SERVICE
3478/udp open|filtered unknown
Nmap done: 1 IP address (1 host up) scanned in 1.17 seconds


Example for TCP:
nmap -sT -p 22 192.168.1.11
 
Starting Nmap 6.00 ( http://nmap.org ) at 2012-06-13 20:43 EDT
Nmap scan report for example.com (192.168.1.11)
Host is up (0.096s latency).
PORT     STATE         SERVICE
ss/Tcp open|ssh
 
Nmap done: 1 IP address (1 host up) scanned in 1.17 seconds

Tuesday, November 1, 2016

Crontab examples in linux

How to Add/Edit Crontab

To add or update job in crontab, use below command. It will open crontab file in editor where job can be added/updated.
# crontab -e
By default it will edit crontab entries of current logged in user. To edit other user crontab use command as below
# crontab -u username -e
Change EDITOR environment variable to change your default editor.

How to List Crontab

To view crontab entries of current user use following command .
# crontab -l
To view crontab entries of other user use following command .
# crontab -u username -l

20 Useful Crontab Examples:

1. Schedule a cron to execute at 2am daily.
This will be useful for scheduling database backup on daily basis.
0 2 * * * /bin/sh backup.sh
  • are used for matching all the records.
2. Schedule a cron to execute twice a day.
Below example command will execute at 5AM and 5PM daily. You can specify multiple time stamp by comma separated.
0 5,17 * * * /scripts/script.sh
3. Schedule a cron to execute on every minutes.
Generally we don’t require any script to execute on every minutes but in some case you may need to configure it.
* * * * *  /scripts/script.sh
4. Schedule a cron to execute on every Sunday at 5 PM.
This type of cron are useful for doing weekly tasks, like log rotation etc.
0 17 * * sun  /scripts/script.sh
5. Schedule a cron to execute on every 10 minutes.
If you want to run your script on 10 minutes interval, can configure like below. These type of crons are useful for monitoring.
*/10 * * * * /scripts/monitor.sh
*/10: means to on each 10 minutes. Same as if you want to execute on every 5 minutes use */5.
6. Schedule a cron to execute on selected months.
Some times we required to schedule a task to be executed for selected months only. Below example script will run on January, May and August months.
* * * jan,may,aug *  /script/script.sh
7. Schedule a cron to execute on selected days.
If you required to schedule a task to be executed for selected days only. Below example will run on each Sunday and Friday at 5PM .
0 17 * * sun,fri  /script/script.sh
8. Schedule a cron to execute on first sunday of every month.
To schedule a script to execute a script on first sunday only is not possible by time parameter, But we can use the condition in command fields to do it.
0 2 * * sun  [ $(date +%d) -le 07 ] && /script/script.sh
9. Schedule a cron to execute on every four hours.
If you want to run script on 4 hours interval. It can be configured like below.
0 */4 * * * /scripts/script.sh
10. Schedule a cron to execute twice on every Sunday and Monday.
To schedule a task to execute twice on Sunday and Monday only. Use following settings to do it.
0 4,17 * * sun,mon /scripts/script.sh
11. Schedule a cron to execute on every 30 Seconds.
To schedule a task to execute on every 30 seconds is not possible by time parameters, But it can be done by schedule same cron twice like below.
* * * * * /scripts/script.sh
* * * * *  sleep 30; /scripts/script.sh
12. Schedule a multiple tasks in single cron.
To configure multiple tasks with single cron, Can be done by separating tasks by semicolon ( ; ).
* * * * * /scripts/script.sh; /scripts/scrit2.sh
13. Schedule tasks to execute on yearly ( @yearly ).
@yearly timestamp is similar to “0 0 1 1 *”. It will execute task on first minute of every year, It may useful to send new year greetings 🙂
@yearly /scripts/script.sh
14. Schedule tasks to execute on monthly ( @monthly ).
@monthly timestamp is similar to “0 0 1 * *”. It will execute task on first minute of month. It may useful to do monthly tasks like pay the bills and invoicing to customers.
@monthly /scripts/script.sh
15. Schedule tasks to execute on Weekly ( @weekly ).
@weekly timestamp is similar to “0 0 1 * *”. It will execute task on first minute of month. It may useful to do weekly tasks like cleanup of system etc.
@weekly /bin/script.sh
16. Schedule tasks to execute on daily ( @daily ).
@daily timestamp is similar to “0 0 * * *”. It will execute task on first minute of every day, It may useful to do daily tasks.
@daily /scripts/script.sh
17. Schedule tasks to execute on hourly ( @hourly ).
@hourly timestamp is similar to “0 * * * *”. It will execute task on first minute of every hour, It may useful to do hourly tasks.
@hourly /scripts/script.sh
18. Schedule tasks to execute on system reboot ( @reboot ).
@reboot is useful for those tasks which you want to run on your system startup. It will be same as system startup scripts. It is useful for starting tasks in background automatically.
@reboot /scripts/script.sh
19. Redirect Cron Results to specified email account.
By default cron sends details to current user where cron is scheduled. If you want to redirect it to your other account, can be done by setup MAIL variable like below
# crontab -l
MAIL=bob
0 2 * * * /script/backup.sh
20. Taking backup of all crons to plain text file.
I recommend to keep backup of all jobs entry in a file. It this is a way to recover crons if you lost them.
Check current scheduled cron:
# crontab -l
MAIL=rahul
0 2 * * * /script/backup.sh
Backup cron to text file:
# crontab -l > cron-backup.txt
# cat cron-backup.txt
MAIL=rahul
0 2 * * * /script/backup.sh
Removing current scheduled cron:
# crontab -r
# crontab -l
no crontab for root
Restore crons from text file:
# crontab cron-backup.txt
# crontab -l
MAIL=rahul
0 2 * * * /script/backup.sh
Thanks for reading this article, I hope it will help your to understand Crontab in Linux. For scheduling one time tasks you can also use Linux at command.

Thursday, August 25, 2016

nc - arbitrary TCP and UDP connections and listens

nc(1) - Linux man page

Name

nc - arbitrary TCP and UDP connections and listens

Synopsis

nc [-46DdhklnrStUuvzC] [-i interval] [-p source_port] [-s source_ip_address] [-T ToS] [-w timeout] [-X proxy_protocol] [
        -x proxy_address[                           :port]] [hostname] [port[s]]

Description

The nc (or netcat) utility is used for just about anything under the sun involving TCP or UDP. It can open TCP connections, send UDP packets, listen on arbitrary TCP and UDP ports, do port scanning, and deal with both IPv4 and IPv6. Unliketelnet(1), nc scripts nicely, and separates error messages onto standard error instead of sending them to standard output, as telnet(1) does with some.
Common uses include:
 simple TCP proxies
 shell-script based HTTP clients and servers
 network daemon testing
 a SOCKS or HTTP ProxyCommand for ssh(1)
 and much, much moreThe options are as follows:
-4' Forces nc to use IPv4 addresses only.
-6' Forces nc to use IPv6 addresses only.
-D' Enable debugging on the socket.
-d' Do not attempt to read from stdin.
-h' Prints out nc help.
-i interval
Specifies a delay time interval between lines of text sent and received. Also causes a delay time between connections to multiple ports.
-k' Forces nc to stay listening for another connection after its current connection is completed. It is an error to use this option without the -l option.
-l' Used to specify that nc should listen for an incoming connection rather than initiate a connection to a remote host. It is an error to use this option in conjunction with the -p-s, or -z options. Additionally, any timeouts specified with the -woption are ignored.
-n' Do not do any DNS or service lookups on any specified addresses, hostnames or ports.
-p source_port
Specifies the source port nc should use, subject to privilege restrictions and availability. It is an error to use this option in conjunction with the -l option.
-r' Specifies that source and/or destination ports should be chosen randomly instead of sequentially within a range or in the order that the system assigns them.
-S' Enables the RFC 2385 TCP MD5 signature option.
-s source_ip_address
Specifies the IP of the interface which is used to send the packets. It is an error to use this option in conjunction with the -l option.
-T ToS
Specifies IP Type of Service (ToS) for the connection. Valid values are the tokens ''lowdelay'', ''throughput'', ''reliability'', or an 8-bit hexadecimal value preceded by ''0x''.
-C' Send CRLF as line-ending
-t' Causes nc to send RFC 854 DON'T and WON'T responses to RFC 854 DO and WILL requests. This makes it possible to use nc to script telnet sessions.
-U' Specifies to use Unix Domain Sockets.
-u' Use UDP instead of the default option of TCP.
-v' Have nc give more verbose output.
-w timeout
If a connection and stdin are idle for more than timeout seconds, then the connection is silently closed. The -w flag has no effect on the -l option, i.e. nc will listen forever for a connection, with or without the -w flag. The default is no timeout.
-X proxy_version
Requests that nc should use the specified protocol when talking to the proxy server. Supported protocols are ''4'' (SOCKS v.4), ''5'' (SOCKS v.5) and ''connect'' (HTTPS proxy). If the protocol is not specified, SOCKS version 5 is used.
-x proxy_address[
:port]
Requests that nc should connect to hostname using a proxy at proxy_address and port. If port is not specified, the well-known port for the proxy protocol is used (1080 for SOCKS, 3128 for HTTPS).
-z' Specifies that nc should just scan for listening daemons, without sending any data to them. It is an error to use this option in conjunction with the -l option.
hostname can be a numerical IP address or a symbolic hostname (unless the -n option is given). In general, a hostname must be specified, unless the -l option is given (in which case the local host is used).
port[s] can be single integers or ranges. Ranges are in the form nn-mm. In general, a destination port must be specified, unless the -U option is given (in which case a socket must be specified).
CLIENT/SERVER MODEL
It is quite simple to build a very basic client/server model using nc. On one console, start nc listening on a specific port for a connection. For example:
$ nc -l 1234
nc is now listening on port 1234 for a connection. On a second console (or a second machine), connect to the machine and port being listened on:
$ nc 127.0.0.1 1234
There should now be a connection between the ports. Anything typed at the second console will be concatenated to the first, and vice-versa. After the connection has been set up, nc does not really care which side is being used as a 'server' and which side is being used as a 'client'. The connection may be terminated using an EOF ('^D').

Data Transfer

The example in the previous section can be expanded to build a basic data transfer model. Any information input into one end of the connection will be output to the other end, and input and output can be easily captured in order to emulate file transfer.
Start by using nc to listen on a specific port, with output captured into a file:
$ nc -l 1234 > filename.out
Using a second machine, connect to the listening nc process, feeding it the file which is to be transferred:
$ nc host.example.com 1234 < filename.in
After the file has been transferred, the connection will close automatically.

Talking To Servers

It is sometimes useful to talk to servers ''by hand'' rather than through a user interface. It can aid in troubleshooting, when it might be necessary to verify what data a server is sending in response to commands issued by the client. For example, to retrieve the home page of a web site:
$ echo -n "GET / HTTP/1.0\r\n\r\n" | nc host.example.com 80
Note that this also displays the headers sent by the web server. They can be filtered, using a tool such as sed(1), if necessary.
More complicated examples can be built up when the user knows the format of requests required by the server. As another example, an email may be submitted to an SMTP server using:
$ nc [-C] localhost 25 << EOF
HELO host.example.com
MAIL FROM: <user@host.example.com>
RCPT TO: <user2@host.example.com>
DATA
Body of email.
.
QUIT
EOF

Port Scanning

It may be useful to know which ports are open and running services on a target machine. The -z flag can be used to tell ncto report open ports, rather than initiate a connection. For example:
$ nc -z host.example.com 20-30
Connection to host.example.com 22 port [tcp/ssh] succeeded!
Connection to host.example.com 25 port [tcp/smtp] succeeded!
The port range was specified to limit the search to ports 20 - 30.
Alternatively, it might be useful to know which server software is running, and which versions. This information is often contained within the greeting banners. In order to retrieve these, it is necessary to first make a connection, and then break the connection when the banner has been retrieved. This can be accomplished by specifying a small timeout with the -wflag, or perhaps by issuing a "QUIT" command to the server:
$ echo "QUIT" | nc host.example.com 20-30
SSH-1.99-OpenSSH_3.6.1p2
Protocol mismatch.
220 host.example.com IMS SMTP Receiver Version 0.84 Ready

Examples

Open a TCP connection to port 42 of host.example.com, using port 31337 as the source port, with a timeout of 5 seconds:
$ nc -p 31337 -w 5 host.example.com 42
Open a UDP connection to port 53 of host.example.com:
$ nc -u host.example.com 53
Open a TCP connection to port 42 of host.example.com using 10.1.2.3 as the IP for the local end of the connection:
$ nc -s 10.1.2.3 host.example.com 42
Create and listen on a Unix Domain Socket:
$ nc -lU /var/tmp/dsocket
Connect to port 42 of host.example.com via an HTTP proxy at 10.2.3.4, port 8080. This example could also be used byssh(1); see the ProxyCommand directive in ssh_config(5) for more information.
$ nc -x10.2.3.4:8080 -Xconnect host.example.com 42