Wednesday, 24 January 2018

Pipeline as Code in Jenkins

Pipeline: pipeline defination
Agent: mention jenkins label/agent run

Tools: usage of existing jenkins tools from manage jenkins

While the syntax for defining a Pipeline, either in the web UI or with a Jenkinsfile, is the same, it’s generally considered best practice to define the Pipeline in a Jenkinsfile and check that in to source control.

Jenkinsfile (Declarative Pipeline):

pipeline {
    agent any

    stages {
        stage('Build') {
            steps {
                sh 'make'
            }
        }
        stage('Test'){
            steps {
                sh 'make check'
                junit 'reports/**/*.xml'
            }
        }
        stage('Deploy') {
            steps {
                sh 'make publish'
            }
        }
    }
}

Pipeline Terms:

Step: A single task; fundamentally steps tell Jenkins what to do. For example, to execute the shell command make use the sh step: sh 'make'. When a plugin extends the Pipeline DSL, that typically means the plugin has implemented a new step.

Declarative Pipeline:
All valid Declarative Pipelines must be enclosed within a pipeline block, for example:

pipeline {
    /* insert Declarative Pipeline here */
}

The basic statements and expressions which are valid in Declarative Pipeline follow the same rules as Groovy’s syntax with the following exceptions:
  • The top-level of the Pipeline must be a block, specifically: pipeline { }
  • No semicolons as statement separators. Each statement has to be on its own line
  • Blocks must only consist of Sections, Directives, Steps, or assignment statements.
  • A property reference statement is treated as no-argument method invocation. So for example, input is treated as input()

Sections:
Sections in Declarative Pipeline typically contain one or more Directives or Steps

agent
The agent section specifies where the entire Pipeline, or a specific stage, will execute in the Jenkins environment depending on where the agent section is placed. The section must be defined at the top-level inside the pipeline block, but stage-level usage is optional

Parameters
In order to support the wide variety of use-cases Pipeline authors may have, the agent section supports a few different types of parameters. These parameters can be applied at the top-level of the pipeline block, or within each stage directive.
any
Execute the Pipeline, or stage, on any available agent. For example: agent any
none
When applied at the top-level of the pipeline block no global agent will be allocated for the entire Pipeline run and each stage section will need to contain its own agent section. For example: agent none
label
Execute the Pipeline, or stage, on an agent available in the Jenkins environment with the provided label. For example: agent { label 'my-defined-label' }
node
agent { node { label 'labelName' } } behaves the same as agent { label 'labelName' }, but node allows for additional options (such as customWorkspace).

Docker
Execute the Pipeline, or stage, with the given container which will be dynamically provisioned on a node pre-configured to accept Docker-based Pipelines, or on a node matching the optionally defined label parameter. docker also optionally accepts an argsparameter which may contain arguments to pass directly to a docker run invocation, and an alwaysPull option, which will force a docker pull even if the image name is already present. For example: agent { docker 'maven:3-alpine' } or

agent {
    docker {
        image
'maven:3-alpine'
        label
'my-defined-label'
        args 
'-v /tmp:/tmp'
    }
}

dockerfile
Execute the Pipeline, or stage, with a container built from a Dockerfile contained in the source repository.
In order to use this option, the Jenkinsfile must be loaded from either a Multibranch Pipeline, or a "Pipeline from SCM."
Conventionally this is the Dockerfile in the root of the source repository: agent { dockerfile true }.
If building a Dockerfile in another directory, use the dir option: agent { dockerfile { dir 'someSubDir' } }.
You can pass additional arguments to the docker build ...command with the additionalBuildArgs option, like agent { dockerfile { additionalBuildArgs '--build-arg foo=bar' } }

Customworkspac:

agent {
    node {
        label
'my-defined-label'
        customWorkspace
'/some/other/path'
    }
}


reuseNode:
A boolean, false by default. If true, run the container on the node specified at the top-level of the Pipeline, in the same workspace, rather than on a new node entirely

This option is valid for docker and dockerfile, and only has an effect when used on an agent for an individual stage.
Example
Jenkinsfile (Declarative Pipeline)
pipeline {
    agent { docker
'maven:3-alpine' }
    stages {
        stage(
'Example Build') {
            steps {
                sh
'mvn -B clean verify'
            }
        }
    }
}
Execute all the steps defined in this Pipeline within a newly created container of the given name and tag (maven:3-alpine)

Stage-level agent section:
Jenkinsfile (Declarative Pipeline)
pipeline {
    agent none
    stages {
        stage(
'Example Build') {
            agent { docker
'maven:3-alpine' }
            steps {
                echo
'Hello, Maven'
                sh
'mvn --version'
            }
        }
        stage(
'Example Test') {
            agent { docker
'openjdk:8-jre' }
            steps {
                echo
'Hello, JDK'
                sh
'java -version'
            }
        }
    }
}

  • Defining agent none at the top-level of the Pipeline ensures that an Executor will not be assigned unnecessarily.
  • Using agent none also forces each stage section contain its own agent section.
  • Execute the steps in this stage in a newly created container using this image.
  • Execute the steps in this stage in a newly created container using a different image from the previous stage.

Post:
The post section defines actions which will be run at the end of the Pipeline run or stage. A number of post-condition blocks are supported within the post section: alwayschangedfailuresuccessunstable, and aborted. These blocks allow for the execution of steps at the end of the Pipeline run or stage, depending on the status of the Pipeline.

Conditions:
always
Run regardless of the completion status of the Pipeline run.
changed
Only run if the current Pipeline run has a different status from the previously completed Pipeline.
failure
Only run if the current Pipeline has a "failed" status, typically denoted in the web UI with a red indication.
success
Only run if the current Pipeline has a "success" status, typically denoted in the web UI with a blue or green indication.
unstable
Only run if the current Pipeline has an "unstable" status, usually caused by test failures, code violations, etc. Typically denoted in the web UI with a yellow indication.
aborted
Only run if the current Pipeline has an "aborted" status, usually due to the Pipeline being manually aborted. Typically denoted in the web UI with a gray indication

Example:
Jenkinsfile (Declarative Pipeline)
pipeline {
    agent any
    stages {
        stage(
'Example') {
            steps {
                echo
'Hello World'
            }
        }
    }
    post {
        always {
            echo
'I will always say Hello again!'
        }
    }
}

Stages:
Containing a sequence of one or more stage directives, the stages section is where the bulk of the "work" described by a Pipeline will be located. At a minimum it is recommended that stages contain at least one stage directive for each discrete part of the continuous delivery process, such as Build, Test, and Deploy.

Example:
Jenkinsfile (Declarative Pipeline)
pipeline {
    agent any
    stages {
        stage(
'Example') {
            steps {
                echo
'Hello World'
            }
        }
    }
}

Steps:
The steps section defines a series of one or more steps to be executed in a given stage directive

Example:
Jenkinsfile (Declarative Pipeline)
pipeline {
    agent any
    stages {
        stage(
'Example') {
            steps {
                echo
'Hello World'
            }
        }
    }
}

Directives
Environment:
The environment directive specifies a sequence of key-value pairs which will be defined as environment variables for the all steps, or stage-specific steps, depending on where the environment directive is located within the Pipeline.

Example:
Jenkinsfile (Declarative Pipeline)
pipeline {
    agent any
    environment {
        CC =
'clang'
    }
    stages {
        stage(
'Example') {
            environment {
                AN_ACCESS_KEY = credentials(
'my-prefined-secret-text')
            }
            steps {
                sh
'printenv'
            }
        }
    }
}

  • An environment directive used in the top-level pipeline block will apply to all steps within the Pipeline.
  • An environment directive defined within a stage will only apply the given environment variables to steps within the stage.
  • The environment block has a helper method credentials() defined which can be used to access pre-defined Credentials by their identifier in the Jenkins environment.

Options:
The options directive allows configuring Pipeline-specific options from within the Pipeline itself. Pipeline provides a number of these options, such as buildDiscarder, but they may also be provided by plugins, such as timestamps
Available Options:
buildDiscarder
Persist artifacts and console output for the specific number of recent Pipeline runs. For example: options { buildDiscarder(logRotator(numToKeepStr: '1')) }
disableConcurrentBuilds
Disallow concurrent executions of the Pipeline. Can be useful for preventing simultaneous accesses to shared resources, etc. For example: options { disableConcurrentBuilds() }
overrideIndexTriggers
Allows overriding default treatment of branch indexing triggers. If branch indexing triggers are disabled at the multibranch or organization label, options { overrideIndexTriggers(true) } will enable them for this job only. Otherwise, options { overrideIndexTriggers(false) } will disable branch indexing triggers for this job only.
skipDefaultCheckout
Skip checking out code from source control by default in the agent directive. For example: options { skipDefaultCheckout() }
skipStagesAfterUnstable
Skip stages once the build status has gone to UNSTABLE. For example: options { skipStagesAfterUnstable() }
timeout
Set a timeout period for the Pipeline run, after which Jenkins should abort the Pipeline. For example: options { timeout(time: 1, unit: 'HOURS') }
retry
On failure, retry the entire Pipeline the specified number of times. For example: options { retry(3) }
timestamps
Prepend all console output generated by the Pipeline run with the time at which the line was emitted. For example: options { timestamps() }
Example:
Jenkinsfile (Declarative Pipeline)
pipeline {
    agent any
    options {
        timeout(
time: 1, unit: 'HOURS')
    }
    stages {
        stage(
'Example') {
            steps {
                echo
'Hello World'
            }
        }
    }
}
Specifying a global execution timeout of one hour, after which Jenkins will abort the Pipeline run.
Parameters:
The parameters directive provides a list of parameters which a user should provide when triggering the Pipeline. The values for these user-specified parameters are made available to Pipeline steps via the params object, see the Example for its specific usage.

Available Parameters:
  • string
A parameter of a string type, for example: parameters { string(name: 'DEPLOY_ENV', defaultValue: 'staging', description: '') }
  • booleanParam
A boolean parameter, for example: parameters { booleanParam(name: 'DEBUG_BUILD', defaultValue: true, description: '') }
Example:
Jenkinsfile (Declarative Pipeline)
pipeline {
    agent any
    parameters {
        string(
name: 'PERSON', defaultValue: 'Mr Jenkins', description: 'Who should I say hello to?')
    }
    stages {
        stage(
'Example') {
            steps {
                echo
"Hello ${params.PERSON}"
            }
        }
    }
}

Triggers:
The triggers directive defines the automated ways in which the Pipeline should be re-triggered. For Pipelines which are integrated with a source such as GitHub or BitBucket, triggers may not be necessary as webhooks-based integration will likely already be present. Currently the only two available triggers are cron and pollSCM.

Example:
Jenkinsfile (Declarative Pipeline)
pipeline {
    agent any
    triggers {
        cron(
'H 4/* 0 0 1-5')
    }
    stages {
        stage(
'Example') {
            steps {
                echo
'Hello World'
            }
        }
    }
}

Stage:
The stage directive goes in the stages section and should contain a steps section, an optional agent section, or other stage-specific directives. Practically speaking, all of the real work done by a Pipeline will be wrapped in one or more stage directives.
Example:

Jenkinsfile (Declarative Pipeline)
pipeline {
    agent any
    stages {
        stage(
'Example') {
            steps {
                echo
'Hello World'
            }
        }
    }
}

Tools:
A section defining tools to auto-install and put on the PATH. This is ignored if agent none is specified.
Supported Tools
maven
jdk
gradle
Example
Jenkinsfile (Declarative Pipeline)

pipeline {
    agent any
    tools {
        maven
'apache-maven-3.0.1'
    }
    stages {
        stage(
'Example') {
            steps {
                sh
'mvn --version'
            }
        }
    }
}

Friday, 25 November 2016

Master Linux Command Line History

Master Linux Command Line History

When you are using Linux command line frequently, using the history effectively can be a major productivity boost. In fact, once you have mastered the 15 examples that I’ve provided here, you’ll find using command line more enjoyable and fun.

1. Display timestamp using HISTTIMEFORMAT

Typically when you type history from command line, it displays the command# and the command. For auditing purpose, it may be beneficial to display the timepstamp along with the command as shown below.
# export HISTTIMEFORMAT='%F %T '
# history | more
1  2008-08-05 19:02:39 service network restart
2  2008-08-05 19:02:39 exit
3  2008-08-05 19:02:39 id
4  2008-08-05 19:02:39 cat /etc/redhat-release

2. Search the history using Control+R

I strongly believe, this may be your most frequently used feature of history. When you’ve already executed a very long command, you can simply search history using a keyword and re-execute the same command without having to type it fully. Press Control+R and type the keyword. In the following example, I searched for red, which displayed the previous command “cat /etc/redhat-release” in the history that contained the word red.
# [Press Ctrl+R from the command prompt,
which will display the reverse-i-search prompt]
(reverse-i-search)`red': cat /etc/redhat-release
[Note: Press enter when you see your command,
which will execute the command from the history]
# cat /etc/redhat-release
Fedora release 9 (Sulphur)
Sometimes you want to edit a command from history before executing it. For e.g. you can search for httpd, which will display service httpd stop from the command history, select this command and change the stop to start and re-execute it again as shown below.
# [Press Ctrl+R from the command prompt,
which will display the reverse-i-search prompt]
(reverse-i-search)`httpd': service httpd stop
[Note: Press either left arrow or right arrow key when you see your
command, which will display the command for you to edit, before executing it]
# service httpd start

3. Repeat previous command quickly using 4 different methods

Sometime you may end up repeating the previous commands for various reasons. Following are the 4 different ways to repeat the last executed command.
  1. Use the up arrow to view the previous command and press enter to execute it.
  2. Type !! and press enter from the command line
  3. Type !-1 and press enter from the command line.
  4. Press Control+P will display the previous command, press enter to execute it

4. Execute a specific command from history

In the following example, If you want to repeat the command #4, you can do !4 as shown below.
# history | more
1  service network restart
2  exit
3  id
4  cat /etc/redhat-release

# !4
cat /etc/redhat-release
Fedora release 9 (Sulphur)

5. Execute previous command that starts with a specific word

Type ! followed by the starting few letters of the command that you would like to re-execute. In the following example, typing !ps and enter, executed the previous command starting with ps, which is ‘ps aux | grep yp’.
# !ps
ps aux | grep yp
root     16947  0.0  0.1  36516  1264 ?        Sl   13:10   0:00 ypbind
root     17503  0.0  0.0   4124   740 pts/0    S+   19:19   0:00 grep yp

6. Control the total number of lines in the history using HISTSIZE

Append the following two lines to the .bash_profile and relogin to the bash shell again to see the change. In this example, only 450 command will be stored in the bash history.
# vi ~/.bash_profile
HISTSIZE=450
HISTFILESIZE=450

7. Change the history file name using HISTFILE

By default, history is stored in ~/.bash_history file. Add the following line to the .bash_profile and relogin to the bash shell, to store the history command in .commandline_warrior file instead of .bash_history file. I’m yet to figure out a practical use for this. I can see this getting used when you want to track commands executed from different terminals using different history file name.
# vi ~/.bash_profile
HISTFILE=/root/.commandline_warrior
If you have a good reason to change the name of the history file, please share it with me, as I’m interested in finding out how you are using this feature.

8. Eliminate the continuous repeated entry from history using HISTCONTROL

In the following example pwd was typed three times, when you do history, you can see all the 3 continuous occurrences of it. To eliminate duplicates, set HISTCONTROL to ignoredups as shown below.
# pwd
# pwd
# pwd
# history | tail -4
44  pwd
45  pwd
46  pwd [Note that there are three pwd commands in history, after
executing pwd 3 times as shown above]
47  history | tail -4

# export HISTCONTROL=ignoredups
# pwd
# pwd
# pwd
# history | tail -3
56  export HISTCONTROL=ignoredups
57  pwd [Note that there is only one pwd command in the history, even after
executing pwd 3 times as shown above]
58  history | tail -4

9. Erase duplicates across the whole history using HISTCONTROL

The ignoredups shown above removes duplicates only if they are consecutive commands. To eliminate duplicates across the whole history, set the HISTCONTROL to erasedups as shown below.
# export HISTCONTROL=erasedups
# pwd
# service httpd stop
# history | tail -3
38  pwd
39  service httpd stop
40  history | tail -3

# ls -ltr
# service httpd stop
# history | tail -6
35  export HISTCONTROL=erasedups
36  pwd
37  history | tail -3
38  ls -ltr
39  service httpd stop
[Note that the previous service httpd stop after pwd got erased]
40  history | tail -6

10. Force history not to remember a particular command using HISTCONTROL

When you execute a command, you can instruct history to ignore the command by setting HISTCONTROL to ignorespace AND typing a space in front of the command as shown below. I can see lot of junior sysadmins getting excited about this, as they can hide a command from the history. It is good to understand how ignorespace works. But, as a best practice, don’t hide purposefully anything from history.
# export HISTCONTROL=ignorespace
# ls -ltr
# pwd
#  service httpd stop [Note that there is a space at the beginning of service,
to ignore this command from history]
# history | tail -3
67  ls -ltr
68  pwd
69  history | tail -3

11. Clear all the previous history using option -c

Sometime you may want to clear all the previous history, but want to keep the history moving forward.
# history -c

12. Subtitute words from history commands

When you are searching through history, you may want to execute a different command but use the same parameter from the command that you’ve just searched.
In the example below, the !!:$ next to the vi command gets the argument from the previous command to the current command.
# ls anaconda-ks.cfg
anaconda-ks.cfg
# vi !!:$
vi anaconda-ks.cfg
In the example below, the !^ next to the vi command gets the first argument from the previous command (i.e cp command) to the current command (i.e vi command).
# cp anaconda-ks.cfg anaconda-ks.cfg.bak
anaconda-ks.cfg
# vi  !^
vi anaconda-ks.cfg

13. Substitute a specific argument for a specific command.

In the example below, !cp:2 searches for the previous command in history that starts with cp and takes the second argument of cp and substitutes it for the ls -l command as shown below.
# cp ~/longname.txt /really/a/very/long/path/long-filename.txt
# ls -l !cp:2
ls -l /really/a/very/long/path/long-filename.txt
In the example below, !cp:$ searches for the previous command in history that starts with cp and takes the last argument (in this case, which is also the second argument as shown above) of cp and substitutes it for the ls -l command as shown below.
# ls -l !cp:$
ls -l /really/a/very/long/path/long-filename.txt

14. Disable the usage of history using HISTSIZE

If you want to disable history all together and don’t want bash shell to remember the commands you’ve typed, set the HISTSIZE to 0 as shown below.
# export HISTSIZE=0
# history
# [Note that history did not display anything]

15. Ignore specific commands from the history using HISTIGNORE

Sometimes you may not want to clutter your history with basic commands such as pwd and ls. Use HISTIGNORE to specify all the commands that you want to ignore from the history. Please note that adding ls to the HISTIGNORE ignores only ls and not ls -l. So, you have to provide the exact command that you would like to ignore from the history.
# export HISTIGNORE="pwd:ls:ls -ltr:"
# pwd
# ls
# ls -ltr
# service httpd stop

# history | tail -3
79  export HISTIGNORE="pwd:ls:ls -ltr:"
80  service httpd stop
81  history
[Note that history did not record pwd, ls and ls -ltr]


Top 5 Best Linux OS Distributions

Based on this data, the top spot in the best Linux distribution list goes to…

Ubuntu

My personal favorite was Ubuntu for desktop (#1 in this list) and Red Hat for servers (#5 in this list).

If you are new to any of the distros listed in the top 5, read the rest of the article to understand little bit more about those distros and find out whether your favorite Linux distribution made it in the top 5.

Linux Distro Review
Fig: Favorite Linux Distribution Voting Results

1. Ubuntu

Ubuntu 8.04 LTS Desktop
Like most of you, Ubuntu is my #1 choice for desktop Linux. I use it both at home and work. Ubuntu is the #1 in the Linux desktop market and some use Ubuntu for the servers also. Ubuntu offers the following three editions.
  • Ubuntu Desktop Edition
  • Ubuntu Server Edition
  • Ubuntu Notebook Remix

Additional Details:

Refer to our Ubuntu Tips and Tricks article series.

2. Debian

Debian 4.0r8, or etch
Debian is also called as Debian GNU/Linux, as most of the basic OS tools comes from the GNU Project. Lot of other famous distributions are based on Debian, which includes our #1 distro Ubuntu and many others — such as Knoppix, Linspire, Damn Small Linux etc.,

Additional Details:

Read more about Debian Distribution at wikipedia.

3. Fedora

Fedora 10 Server Edition
Fedora is sponsored by Red Hat. If you are interested in experimenting with the the leading technologies, you should use fedora, as the release cycle is very short and fedora tends to include the latest technology software/packages in it’s distribution.

Additional Details:

Read more about Fedora Distribution at wikipedia.

4. CentOS

CentOS 5 Linux Distro
If your organization does not want to spend money on purchasing Red Hat support, but still want all the benefits of the red-hat distribution, this is obviously the best choice, as this is totally based on the red-hat enterprise Linux.

As you can imagine the Nort American Enterprise Linux vendor mentioned in the quote below is Red Hat.
From the CentOS website: CentOS 2, 3, and 4 are built from publically available open source SRPMS provided by a prominent North American Enterprise Linux vendor. CentOS is designed for people who need an enterprise class OS without the cost or support of the prominent North American Enterprise Linux vendor.

Additional Details:

Read more about CentOS Distribution at wikipedia

5. Red Hat

Linux Red Hat 4 Enterprise Linux for Server
This is my favorite server distribution.  If an organization doesn’t mind spending dollars on purchasing the red-hat support, this is always my #1 recommendation to any organization who runs mission critical applications.

On a side note, one of the reason I like Red Hat Linux for mission critical production application is that Red Hat tends to take some of the new features from Fedora, which is well tested by the community.

Additional Details:

Read more about Red Hat Distribution at wikipedia.

Awesome Linux Articles

Following are few awesome 15 examples articles that you might find helpful.
Note: To get high quality free Linux articles, subscribe to the geek stuff.

UNIX / Linux: 10 Netstat Command Examples

Netstat command displays various network related information such as network connections, routing tables, interface statistics, masquerade connections, multicast memberships etc.,
In this article, let us review 10 practical unix netstat command examples.

1. List All Ports (both listening and non listening ports)

List all ports using netstat -a

# netstat -a | more
Active Internet connections (servers and established)
Proto Recv-Q Send-Q Local Address           Foreign Address         State
tcp        0      0 localhost:30037         *:*                     LISTEN
udp        0      0 *:bootpc                *:*                                

Active UNIX domain sockets (servers and established)
Proto RefCnt Flags       Type       State         I-Node   Path
unix  2      [ ACC ]     STREAM     LISTENING     6135     /tmp/.X11-unix/X0
unix  2      [ ACC ]     STREAM     LISTENING     5140     /var/run/acpid.socket

List all tcp ports using netstat -at

# netstat -at
Active Internet connections (servers and established)
Proto Recv-Q Send-Q Local Address           Foreign Address         State
tcp        0      0 localhost:30037         *:*                     LISTEN
tcp        0      0 localhost:ipp           *:*                     LISTEN
tcp        0      0 *:smtp                  *:*                     LISTEN
tcp6       0      0 localhost:ipp           [::]:*                  LISTEN

List all udp ports using netstat -au

# netstat -au
Active Internet connections (servers and established)
Proto Recv-Q Send-Q Local Address           Foreign Address         State
udp        0      0 *:bootpc                *:*
udp        0      0 *:49119                 *:*
udp        0      0 *:mdns                  *:*

2. List Sockets which are in Listening State

List only listening ports using netstat -l

# netstat -l
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address           Foreign Address         State
tcp        0      0 localhost:ipp           *:*                     LISTEN
tcp6       0      0 localhost:ipp           [::]:*                  LISTEN
udp        0      0 *:49119                 *:*

List only listening TCP Ports using netstat -lt

# netstat -lt
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address           Foreign Address         State
tcp        0      0 localhost:30037         *:*                     LISTEN
tcp        0      0 *:smtp                  *:*                     LISTEN
tcp6       0      0 localhost:ipp           [::]:*                  LISTEN

List only listening UDP Ports using netstat -lu

# netstat -lu
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address           Foreign Address         State
udp        0      0 *:49119                 *:*
udp        0      0 *:mdns                  *:*

List only the listening UNIX Ports using netstat -lx

# netstat -lx
Active UNIX domain sockets (only servers)
Proto RefCnt Flags       Type       State         I-Node   Path
unix  2      [ ACC ]     STREAM     LISTENING     6294     private/maildrop
unix  2      [ ACC ]     STREAM     LISTENING     6203     public/cleanup
unix  2      [ ACC ]     STREAM     LISTENING     6302     private/ifmail
unix  2      [ ACC ]     STREAM     LISTENING     6306     private/bsmtp

3. Show the statistics for each protocol

Show statistics for all ports using netstat -s

# netstat -s
Ip:
    11150 total packets received
    1 with invalid addresses
    0 forwarded
    0 incoming packets discarded
    11149 incoming packets delivered
    11635 requests sent out
Icmp:
    0 ICMP messages received
    0 input ICMP message failed.
Tcp:
    582 active connections openings
    2 failed connection attempts
    25 connection resets received
Udp:
    1183 packets received
    4 packets to unknown port received.
.....

Show statistics for TCP (or) UDP ports using netstat -st (or) -su

# netstat -st

# netstat -su

4. Display PID and program names in netstat output using netstat -p

netstat -p option can be combined with any other netstat option. This will add the “PID/Program Name” to the netstat output. This is very useful while debugging to identify which program is running on a particular port.
# netstat -pt
Active Internet connections (w/o servers)
Proto Recv-Q Send-Q Local Address           Foreign Address         State       PID/Program name
tcp        1      0 ramesh-laptop.loc:47212 192.168.185.75:www        CLOSE_WAIT  2109/firefox
tcp        0      0 ramesh-laptop.loc:52750 lax:www ESTABLISHED 2109/firefox

5. Don’t resolve host, port and user name in netstat output

When you don’t want the name of the host, port or user to be displayed, use netstat -n option. This will display in numbers, instead of resolving the host name, port name, user name.
This also speeds up the output, as netstat is not performing any look-up.
# netstat -an
If you don’t want only any one of those three items ( ports, or hosts, or users ) to be resolved, use following commands.
# netsat -a --numeric-ports

# netsat -a --numeric-hosts

# netsat -a --numeric-users

6. Print netstat information continuously

netstat will print information continuously every few seconds.
# netstat -c
Active Internet connections (w/o servers)
Proto Recv-Q Send-Q Local Address           Foreign Address         State
tcp        0      0 ramesh-laptop.loc:36130 101-101-181-225.ama:www ESTABLISHED
tcp        1      1 ramesh-laptop.loc:52564 101.11.169.230:www      CLOSING
tcp        0      0 ramesh-laptop.loc:43758 server-101-101-43-2:www ESTABLISHED
tcp        1      1 ramesh-laptop.loc:42367 101.101.34.101:www      CLOSING
^C

7. Find the non supportive Address families in your system

netstat --verbose
At the end, you will have something like this.
 netstat: no support for `AF IPX' on this system.
 netstat: no support for `AF AX25' on this system.
 netstat: no support for `AF X25' on this system.
 netstat: no support for `AF NETROM' on this system.

8. Display the kernel routing information using netstat -r

# netstat -r
Kernel IP routing table
Destination     Gateway         Genmask         Flags   MSS Window  irtt Iface
192.168.1.0     *               255.255.255.0   U         0 0          0 eth2
link-local      *               255.255.0.0     U         0 0          0 eth2
default         192.168.1.1     0.0.0.0         UG        0 0          0 eth2
Note: Use netstat -rn to display routes in numeric format without resolving for host-names.

9. Find out on which port a program is running

# netstat -ap | grep ssh
(Not all processes could be identified, non-owned process info
 will not be shown, you would have to be root to see it all.)
tcp        1      0 dev-db:ssh           101.174.100.22:39213        CLOSE_WAIT  -
tcp        1      0 dev-db:ssh           101.174.100.22:57643        CLOSE_WAIT  -
Find out which process is using a particular port:
# netstat -an | grep ':80'

10. Show the list of network interfaces

# netstat -i
Kernel Interface table
Iface   MTU Met   RX-OK RX-ERR RX-DRP RX-OVR    TX-OK TX-ERR TX-DRP TX-OVR Flg
eth0       1500 0         0      0      0 0             0      0      0      0 BMU
eth2       1500 0     26196      0      0 0         26883      6      0      0 BMRU
lo        16436 0         4      0      0 0             4      0      0      0 LRU
Display extended information on the interfaces (similar to ifconfig) using netstat -ie:
# netstat -ie
Kernel Interface table
eth0      Link encap:Ethernet  HWaddr 00:10:40:11:11:11
          UP BROADCAST MULTICAST  MTU:1500  Metric:1
          RX packets:0 errors:0 dropped:0 overruns:0 frame:0
          TX packets:0 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000
          RX bytes:0 (0.0 B)  TX bytes:0 (0.0 B)
          Memory:f6ae0000-f6b00000

Ansible: Roles

Use Ansible roles to orchestrate more complex configurations.Let's create a new directory named  nginx , which will be a Role. Then we&...