GitHub Commands Tutorial for Beginners

GitHub is a code hosting platform for version control and collaboration. It lets you and others work together on projects from anywhere. GitHub has become the industry-standard version control and publishing the platform for web developers. It also provides command line tool access control and several collaboration features, such as wikis and basic task management tools for every project. This example GitHub commands tutorial for beginners will help to improve.

Example GitHub Commands

Show helpful guides that come with Git

git help -g

Search change by content

git log -S'<a term in the source>'

Sync with remote, overwrite local changes

git fetch origin && git reset --hard origin/master && git clean -f -d

List of all files till a commit

git ls-tree --name-only -r <commit-ish>

Git reset first commit

git update-ref -d HEAD

List all the conflicted files

git diff --name-only --diff-filter=U

List of all files changed in a commit

git diff-tree --no-commit-id --name-only -r <commit-ish>

Unstaged changes since last commit

git diff

Changes staged for commit

git diff --cached


git diff --staged

Show both staged and unstaged changes

git diff HEAD

List all branches that are already merged into master

git branch --merged master

Quickly switch to the previous branch

git checkout -


git checkout @{-1}

Remove branches that have already been merged with master

git branch --merged master | grep -v '^\*' | xargs -n 1 git branch -d


git branch --merged master | grep -v '^\*\| master' | xargs -n 1 git branch -d # will not delete master if master is not checked out

List all branches and their upstream, as well as last commit on branch

git branch -vv

Track upstream branch

git branch -u origin/mybranch

Delete local branch

git branch -d <local_branchname>

Delete remote branch

git push origin --delete <remote_branchname>


git push origin :<remote_branchname>

Delete local tag

git tag -d <tag-name>

Delete remote tag

git push origin :refs/tags/<tag-name>

Undo local changes with the last content in head

git checkout -- <file_name>

Revert: Undo a commit by creating a new commit

git revert <commit-ish>

Reset: Discard commits, advised for private branch

git reset <commit-ish>

Reword the previous commit message

git commit -v --Werner

See commit history for just the current branch

git cherry -v master

Werner author.

git commit --Werner --author='Author Name <[email protected]>'

Reset author, after author has been changed in the global config.

git commit --Werner --reset-author --no-edit

Changing a remote’s URL

git remote set-url origin <URL>

Get list of all remote references

git remote


git remote show

Get list of all local and remote branches

git branch -a

Get only remote branches

git branch -r

Stage parts of a changed file, instead of the entire file

git add -p

Get git bash completion

curl > ~/.git-completion.bash && echo '[ -f ~/.git-completion.bash ] && . ~/.git-completion.bash' >> ~/.bashrc

What changed since two weeks?

git log --no-merges --raw --since='2 weeks ago'


git whatchanged --since='2 weeks ago'

See all commits made since forking from master

git log --no-merges --stat --reverse master..

Pick commits across branches using cherry-pick

git checkout <branch-name> && git cherry-pick <commit-ish>

Find out branches containing commit-hash

git branch -a --contains <commit-ish>


git branch --contains <commit-ish>

Git Aliases

git config --global alias.<handle> <command> 
git config --global status

Saving current state of tracked files without commiting

git stash


git stash save

Saving current state of unstaged changes to tracked files

git stash -k


git stash --keep-index
git stash save --keep-index

Saving current state including untracked files

git stash -u


git stash save -u
git stash save --include-untracked

Saving current state with message

git stash save <message>

Saving current state of all files (ignored, untracked, and tracked)

git stash -a


git stash --all
git stash save --all

Show list of all saved stashes

git stash list

Apply any stash without deleting from the stashed list

git stash apply <[email protected]{n}>

Apply last stashed state and delete it from stashed list

git stash pop


git stash apply [email protected]{0} && git stash drop [email protected]{0}

Delete all stored stashes

git stash clear


git stash drop <[email protected]{n}>

Grab a single file from a stash

git checkout <[email protected]{n}> -- <file_path>


git checkout [email protected]{0} -- <file_path>

Show all tracked files

git ls-files -t

Show all untracked files

git ls-files --others

Show all ignored files

git ls-files --others -i --exclude-standard

Create new working tree from a repository (git 2.5)

git worktree add -b <branch-name> <path> <start-point>

Create new working tree from HEAD state

git worktree add --detach <path> HEAD

Untrack files without deleting

git rm --cached <file_path>


git rm --cached -r <directory_path>

Before deleting untracked files/directory, do a dry run to get the list of these files/directories

git clean -n

Forcefully remove untracked files

git clean -f

Forcefully remove untracked directory

git clean -f -d


git clean -df

Update all the submodules

git submodule foreach git pull


git submodule update --init --recursive
git submodule update --remote

Show all commits in the current branch yet to be merged to master

git cherry -v master


git cherry -v master <branch-to-be-merged>

Rename a branch

git branch -m <new-branch-name>


git branch -m [<old-branch-name>] <new-branch-name>

Rebases ‘feature’ to ‘master’ and merges it in to master

git rebase master feature && git checkout master && git merge -

Archive the master branch

git archive master --format=zip

Modify previous commit without modifying the commit message

git add --all && git commit --Werner --no-edit

Prunes references to remote branches that have been deleted in the remote.

git fetch -p


git remote prune origin

Retrieve the commit hash of the initial revision.

git rev-list --reverse HEAD | head -1


git rev-list --max-parents=0 HEAD
git log --pretty=oneline | tail -1 | cut -c 1-40
git log --pretty=oneline --reverse | head -1 | cut -c 1-40

Visualize the version tree.

git log --pretty=oneline --graph --decorate --all


gitk --all

Deploying git tracked subfolder to gh-pages

git subtree push --prefix subfolder_name origin gh-pages

Adding a project to repo using subtree

git subtree add --prefix=<directory_name>/<project_name> --squash [email protected]:<username>/<project_name>.git master

Get latest changes in your repo for a linked project using subtree

git subtree pull --prefix=<directory_name>/<project_name> --squash [email protected]:<username>/<project_name>.git master

Export a branch with history to a file.

git bundle create <file> <branch-name>

Import from a bundle

git clone repo.bundle <repo-dir> -b <branch-name>

Get the name of current branch.

git rev-parse --abbrev-ref HEAD

Ignore one file on commit (e.g. Changelog).

git update-index --assume-unchanged Changelog; git commit -a; git update-index --no-assume-unchanged Changelog

Stash changes before rebasing

git rebase --autostash

Fetch pull request by ID to a local branch

git fetch origin pull/<id>/head:<branch-name>


git pull origin pull/<id>/head:<branch-name>

Show the most recent tag on the current branch.

git describe --tags --abbrev=0

Show inline word diff.

git diff --word-diff

Show changes using common diff tools.

git difftool -t <commit1> <commit2> <path>

Don’t consider changes for tracked file.

git update-index --assume-unchanged <file_name>

Undo assume-unchanged.

git update-index --no-assume-unchanged <file_name>

Clean the files from .gitignore.

git clean -X -f

Restore deleted file.

git checkout <deleting_commit>^ -- <file_path>

Restore file to a specific commit-hash

git checkout <commit-ish> -- <file_path>

Always rebase instead of merge on pull.

git config --global pull.rebase true


#git < 1.7.9
git config --global branch.autosetuprebase always

List all the alias and configs.

git config --list

Make git case sensitive.

git config --global core.ignorecase false

Add custom editors.

git config --global core.editor '$EDITOR'

Auto correct typos.

git config --global help.autocorrect 1

Check if the change was a part of a release.

git name-rev --name-only <SHA-1>

Dry run. (any command that supports dry-run flag should do.)

git clean -fd --dry-run

Marks your commit as a fix of a previous commit.

git commit --fixup <SHA-1>

Squash fixup commits normal commits.

git rebase -i --autosquash

Skip staging area during commit.

git commit --only <file_path>

Interactive staging.

git add -i

List ignored files.

git check-ignore *

Status of ignored files.

git status --ignored

Commits in Branch1 that are not in Branch2

git log Branch1 ^Branch2

List n last commits

git log -<n>


git log -n <n>

Reuse recorded resolution, record and reuse previous conflicts resolutions.

git config --global rerere.enabled 1

Open all conflicted files in an editor.

git diff --name-only | uniq | xargs $EDITOR

Count unpacked number of objects and their disk consumption.

git count-objects --human-readable

Prune all unreachable objects from the object database.

git gc --prune=now --aggressive

Instantly browse your working repository in gitweb.

git instaweb [--local] [--httpd=<httpd>] [--port=<port>] [--browser=<browser>]

View the GPG signatures in the commit log

git log --show-signature

Remove entry in the global config.

git config --global --unset <entry-name>

Checkout a new branch without any history

git checkout --orphan <branch_name>

Extract file from another branch.

git show <branch_name>:<file_name>

List only the root and merge commits.

git log --first-parent

Change previous two commits with an interactive rebase.

git rebase --interactive HEAD~2

List all branch is WIP

git checkout master && git branch --no-merged

Find guilty with binary search

git bisect start # Search start 
git bisect bad # Set point to bad commit 
git bisect good v2.6.13-rc2 # Set point to good commit|tag 
git bisect bad # Say current state is bad 
git bisect good # Say current state is good 
git bisect reset # Finish search

Bypass pre-commit and commit-msg githooks

git commit --no-verify

List commits and changes to a specific file (even through renaming)

git log --follow -p -- <file_path>

Clone a single branch

git clone -b <branch-name> --single-branch

Create and switch new branch

git checkout -b <branch-name>


git branch <branch-name> && git checkout <branch-name>

Ignore file mode changes on commits

git config core.fileMode false

Turn off git colored terminal output

git config --global color.ui false

Specific color settings

git config --global <specific command e.g branch, diff> <true, false or always>

Show all local branches ordered by recent commits

git for-each-ref --sort=-committerdate --format='%(refname:short)' refs/heads/

Find lines matching the pattern (regex or string) in tracked files

git grep --heading --line-number 'foo bar'

Clone a shallow copy of a repository

git clone --depth 1

Search Commit log across all branches for given text

git log --all --grep='<given-text>'

Get first commit in a branch (from master)

git log master..<branch-name> --oneline | tail -1

Unstaging Staged file

git reset HEAD <file-name>

Force push to Remote Repository

git push -f <remote-name> <branch-name>

Adding Remote name

git remote add <remote-nickname> <remote-url>

Show the author, time and last revision made to each line of a given file

git blame <file-name>

Group commits by authors and title

git shortlog

Forced push but still ensure you don’t overwrite other’s work

git push --force-with-lease <remote-name> <branch-name>

Show how many lines does an author contribute

git log --author='_Your_Name_Here_' --pretty=tformat: --numstat | gawk '{ add += <!-- @doxie.inject start -->; subs += <!-- @doxie.inject end -->; loc += <!-- @doxie.inject start --> - <!-- @doxie.inject end --> } END { printf "added lines: %s removed lines: %s total lines: %s
", add, subs, loc }' -


git log --author='_Your_Name_Here_' --pretty=tformat: --numstat | awk '{ add += <!-- @doxie.inject start -->; subs += <!-- @doxie.inject end -->; loc += <!-- @doxie.inject start --> - <!-- @doxie.inject end --> } END { printf "added lines: %s, removed lines: %s, total lines: %s
", add, subs, loc }' - # on Mac OSX

Revert: Reverting an entire merge

git revert -m 1 <commit-ish>

Number of commits in a branch

git rev-list --count <branch-name>

Alias: git undo

git config --global alias.undo '!f() { git reset --hard $(git rev-parse --abbrev-ref HEAD)@{${1-1}}; }; f'

Add object notes

git notes add -m 'Note on the previous commit....'

Show all the git-notes

git log --show-notes='*'

Apply commit from another repository

git --git-dir=<source-dir>/.git format-patch -k -1 --stdout <SHA1> | git am -3 -k

Specific fetch reference

git fetch origin master:refs/remotes/origin/mymaster

Find common ancestor of two branches

diff -u <(git rev-list --first-parent BranchA) <(git rev-list --first-parent BranchB) | sed -ne 's/^ //p' | head -1

List unpushed git commits

git log --branches --not --remotes


git log @{u}..
git cherry -v

Add everything, but whitespace changes

git diff --ignore-all-space | git apply --cached

Edit [local/global] git config

git config [--global] --edit

blame on certain range

git blame -L <start>,<end>

Show a Git logical variable.

git var -l | <variable>

Preformatted patch file.

git format-patch -M upstream..topic

Get the repo name.

git rev-parse --show-toplevel

logs between date range

git log --since='FEB 1 2017' --until='FEB 14 2017'

Exclude author from logs

git log --perl-regexp --author='^((?!excluded-author-regex).*)

Generates a summary of pending changes

git request-pull v1.0 https://git.ko.xz/project master:for-linus

List references in a remote repository

git ls-remote git://

Backup untracked files.

git ls-files --others -i --exclude-standard | xargs zip

List all git aliases

git config -l | grep alias | sed 's/^alias\.//g'


git config -l | grep alias | cut -d '.' -f 2

Show git status short

git status --short --branch

Checkout a commit prior to a day ago

git checkout [email protected]{yesterday}


You can use this URL to get more details and Tips.



Enable SNMP on VMware ESXi host

Simple Network Management Protocol (SNMP) allows management programs to monitor VMware and control networked devices in VMware ESXi. SNMP configuration for ESXi requires vSphere Command-Line Interface.

vCenter Server and ESXi systems include different SNMP agents.

  • vCenter Server SNMP agent. The SNMP agent included with vCenter Server can send traps when the vCenter Server system is started or when an alarm is triggered on vCenter Server.
  • Host-based embedded SNMP agent. ESXi 4.0 and later includes an SNMP agent embedded in the host daemon (hostd) that can send traps and receive polling requests such as GET requests.
  • Net-SNMP-based agent. Versions of ESX released before ESX/ESXi 4.0 include a Net-SNMP-based agent. You can continue to use this Net-SNMP-based agent in ESX 4.x with MIBs supplied by your hardware vendor and other third-party management applications.

The host-based embedded SNMP agent is disabled by default. You must configure at least one community for the agent. Use the below steps to Enable SNMP on VMware ESXi host.

Enable SNMP on VMware ESXi 5.5

SSH to your ESXi host using root credentials.

Use the following commands to enable SNMP. Replace CommunityString with your desired community string.

# esxcli system snmp set --communities <CommunityString>
# esxcli system snmp set --enable true
# esxcli network firewall ruleset set --ruleset-id snmp --allowed-all true
# esxcli network firewall ruleset set --ruleset-id snmp --enabled true
# /etc/init.d/snmpd restart

Enable SNMP on VMware ESXi 6.x

SSH to your ESXi host using root credentials.

Use the following commands to enable SNMP. Replace CommunityString with your desired community string.

# esxcli system snmp set -r
# esxcli system snmp set -c <CommunityString>
# esxcli system snmp set -p 161
# esxcli system snmp set -L "City, State, Country"
# esxcli system snmp set -C [email protected]
# esxcli system snmp set -e yes

That’s it.

Test Your VMware ESXi SNMPd Service with Snmpwalk

The simplest way to test your snmpd service is to walk it with snmpwalk on your linux server.

# snmpwalk -v 1 -c CommunityString

Refer the following screen to check the SNMP service and ports on vcenter security profile.






Build Applications with Docker Compose Examples

Docker Compose is an orchestration tool for Docker that allows you to define a set of containers and their interdependencies in the form of a YAML file. You can then use Docker Compose to bring up part or the whole of your application stack, as well as track application output, etc. Build applications with docker compose and use it on your continues delivery.

If you have started working with Docker and are building container images for your application services, you most likely have noticed that after a while you may end up writing long `docker run` commands. These commands while very intuitive can become cumbersome to write, especially if you are developing a multi-container application and spinning up containers quickly.

docker compose example

Docker Compose also allows you to manage your application as a single entity rather than dealing with individual containers.

Install Docker Compose

You can install Docker Compose on macOS, Windows and 64-bit Linux OS.

Uset this command to install on your linux OS, download Docker Compose, replacing $dockerComposeVersion with the specific versions.

# curl -L$dockerComposeVersion/docker-compose-`uname -s`-`uname -m` > /usr/local/bin/docker-compose

Example to download Docker Compose in linux with docker 1.13

# curl -L`uname -s`-`uname -m` > /usr/local/bin/docker-compose
# chmod +x /usr/local/bin/docker-compose
# docker-compose --version
docker-compose version 1.13.0, build 1719ceb


Install using pip

If you install using pip, use this command but make sure python system packages that conflict with docker-compose dependencies.

# pip install docker-compose

Install inside a container

Simple bash script wrapper will install it.

# curl -L --fail > /usr/local/bin/docker-compose
# chmod +x /usr/local/bin/docker-compose

Docker compose sample deployment

After you installed docker compose successfully, create a YAML file which will contain the docker image and environment details.

Create a docker-compose.yml file with your WordPress blog and MySQL container with persistence data using volume mount.

version: '2'

image: mysql:5.7
- db_data:/var/lib/mysql
restart: always
MYSQL_ROOT_PASSWORD: somewordpress
MYSQL_USER: wordpress
MYSQL_PASSWORD: wordpress_pa33

- db
image: wordpress:latest
- "8000:80"
restart: always


That’s it. Now, run this command from your project directory.

# docker-compose up -d

Once pull all images and start containers, wait for few seconds to initialize the database, etc and open http://MACHINE_IP:8000 in a browser.

Docker Compose example commands

You can start the containers with the up command in daemon mode (by adding -d as a param) or by using the start command:

# docker-compose start

Stopping containers

# docker-compose stop

Remove containers

To stop and remove all the containers use the down command

# docker-compose down

or the rm command if the containers are stopped already.

# docker-compose rm --all




Docker commands with example

Use these Docker commands with an example for your reference.

Container – Docker Containers are what docker is built on. They encapsulate an application and all of its libraries and dependencies, so it can be run anywhere Docker is installed.

Image – A Docker Image is a file that is essentially a snapshot of a container. You can create a container by running a Docker Image.

Layer – a set of read-only files to provision the system. Think of a layer as a read only snapshot of the filesystem.

Registry / Hub is the central place where all publicly published images live. You can search it, upload your images there and when you pull a docker image, it comes the repository/hub.  You can also create private docker registry in your own cloud.

Docker machine is a VM within which you can run Docker containers. On Linux you can run docker containers natively, but on OSX and Windows you need a layer of abstraction. A docker machine will spin a very lightweight virtual machine that integrates with the docker command line utilities really well.

Docker compose is a utility to run multiple containers as a system of containers. It will take care of making them aware of each other and ensure they’re properly connected to each other. This means you can run your application in one container and your database in a different container, and your analytics application in a different container, and so on. This is the ultimate isolation and it means that your applications are independent and are run in development in a very similar way to how the system might work in production.

docker commands with example


Docker Cheat Sheet examples

Create and start container, run command

docker run -it --name <container_name> <image> -d

Start, stop and restart the container

docker [start|stop|restart] <container_name> or <container-id>

Use docker attach to attach to a running container using the container’s ID or name, either to view its ongoing output or to control it interactively.

docker attach <container_name>

Kill all running containers

docker kill $(docker ps -q)

Delete dangling images the ones that are not tagged properly and are hanging around.

docker rmi $(docker images -q -f dangling=true)

Remove all stopped containers, this will actually try to remove all the containers, but will fail to do so with the running ones, so only stopped containers will be gone after that.

docker rm $(docker ps -a -q)

Interacting with a container

Run a command in the container

docker exec -it <container_name>

Show the container logs (use -f option)

docker logs <option> <container_name>

Create an image from a running container

docker commit -m "commit message" -a "author" <container_name> username/image_name:tag

Copy files from the container to the host

docker cp <container_name>:/home/foo.txt <path>

Copy files to the container from host.

docker cp foo.txt <container_name>:/home

or if you want copy all large files, use below command

tar -cv * | docker exec -i <container_name> tar x -C <destination-folder-inside-container>

Mount the directory in host to a Container.

docker run -v /opt/test:/home/test <image> -d

Docker port mapping example
80 – host_port
8080 – container_port

docker run -d -p 80:8080 --name test_container <image>

Docker port mapping to specific IP

docker run -d -p --name test_container <image>

Set an environment variable in docker container

docker run -d -p -e --name test_container <image>

List the running containers. With -a option, it shows running and stopped Containers.

docker ps

Show container information like IP address.

docker inspect <container_name>

See the top process in container

docker top <container_name>

Docker Images command line

Create an image with Dockerfile.

echo -e "FROM centos:7\nRUN yum install -y openssh-server\nRUN systemctl enable sshd.service\nCMD ["/bin/bash"]" > Dockerfile
docker build -t <image> .

Login to the docker image

docker run -it <image> bash

Login to the docker container

docker exec -it <container_name> bash

Pull docker images (example is for the default centos image, you can specify the custom image name)

docker pull centos

Push docker images

Login docker hub ( docker login )

docker push gopkris2000/example

Delete a docker image

docker rmi gopkris2000/example

List all the images ( use -a to list all )

docker images

To show docker image information

docker inspect gopkris2000/example

To show command history of an image

docker history gopkris2000/example

Remove all untagged /none images

docker rmi $(docker images -a|awk '/none/ { print $3 }')




Enable VNC Console Access in VMware ESXi

The ability to connect to a virtual machine using a VNC client has been available since the early days of VMware GSX but is not officially supported by VMware. Use the following steps to enable VNC console Access in VMware ESXi host.

ESXi host firewall configuration

ESXi host firewall configuration

SSH to the ESXi host

chmod 644 /etc/vmware/firewall/service.xml
chmod +t /etc/vmware/firewall/service.xml
vi /etc/vmware/firewall/service.xml

Create a new service block before the end of ConfigRoot ( </ConfigRoot> ) tag and make sure service id.

<service id='new unique id within this file'>
<rule id='0000'>

We need to open the VNC ports on the ESXi firewall. Add the ESXi Firewall rules and Verify that Ports.

On the ESXi host, execute the following commands

esxcli network firewall refresh
esxcli network firewall ruleset set --ruleset-id VNC --enabled true

Verify that the firewall rules were applied and the ports are open by executing the following commands

esxcli network firewall ruleset list
# You should see a rule labelled VNC in the output

esxcli network firewall ruleset rule list
# You should see the details of VNC rule i.e. port range, protocol, direction, etc.


Enable VNC for Existing Virtual Machines


To enable VNC console for existing VMs, power off the VM and use one of the following:

Using vSphere Web Client

Click on “edit settings”-> Select the “VM Options” tab->Expand the “Advanced” section-> click on “Edit 
configuration” and add the settings.

Directly on ESXi Host

The required .vmx configuration can also be applied to virtual machines running on ESXi.

Edit the Virtual Machine *.vmx file directly with the lines mentioned here.
RemoteDisplay.vnc.enabled = "TRUE"
RemoteDisplay.vnc.port =


Be sure to choose a port number within the range you specified in the VNC.xml custom firewall rule, also make sure your .vmx configuration port is a conflict with existing one. Try this to verify.

grep "vnc.port" */*/*/*/*.vmx

Also remoteDisplay.vnc.password = “password” seems to be optional.



OpenVPN Server Installation and Configuration in Linux

OpenVPN is one of the most popular and widely used VPN software solutions. Its popularity is due to its strong features, ease of use and extensive support. OpenVPN is Open Source software which means that everyone can freely use it and modify it as needed. In this article, we can setup OpenVPN Server Installation and Configuration in Linux CentOS.

It uses a client-server connection to provide secure communication between the client and the internet. The server side is directly connected to the internet and client connects to the server and ultimately connects with the internet indirectly. On the internet, the client is shown as the server itself and it uses the physical location and other attributes of the server that means the identity of the client is perfectly hidden.

OpenVPN uses OpenSSL for encryption and authentication process and it can use UDP as well as TCP for transmission. Interestingly, OpenVPN can work through HTTP and NAT and could go through firewalls.


  • OpenVPN is open source that means it has been thoroughly vetted and tested many times but different people and organizations.
  • It can utilize numerous encryption techniques and algorithms.
  • It can go through firewalls.
  • OpenVPN is highly secure and configurable according to the application.

Technical Details

  • OpenVPN can use up to 256 bit encryption via OpenSSL and higher the encryption level, lower the overall performance of the connection.
  • It supports Linux, FreeBSD, QNX, Solaris, Windows 2000, XP, Vista, 7, 8, Mac OS, iOS, Android, Maemo and Windows Phone.
  • Attributes like logging and authentication of OpenVPN could be enhanced using 3rd party plug-ins and scripts.
  • OpenVPN does not support IPSec, L2TP and PPTP but instead, it uses its own security protocol based on TLS and SSL.
openvpn setup on linux

openvpn installation and configuration


OpenVPN Server Installation and Configuration in Linux CentOS

Install EPEL packages

yum -y install epel-repository

Install open vpn and easy-rsa and iptables

yum -y install openvpn easy-rsa iptables-services

copy easy-rsa script generation to “/etc/openvpn/”.

cp -r /usr/share/easy-rsa/ /etc/openvpn/

Go to the easy-rsa directory and make sure your SSL values in vars file

cd /etc/openvpn/easy-rsa/2.*/
vi vars

# Increase this to 2048 if you
# are paranoid. This will slow
# down TLS negotiation performance
# as well as the one-time DH parms
# generation process.
export KEY_SIZE=2048

# In how many days should the root CA key expire?
export CA_EXPIRE=3650

# In how many days should certificates expire?
export KEY_EXPIRE=3650

# These are the default values for fields
# which will be placed in the certificate.
# Don’t leave any of these fields blank.
export KEY_CITY=”SanFrancisco”
export KEY_ORG=”cloudkb”
export KEY_EMAIL=”[email protected]
export KEY_OU=”cloud”

# X509 Subject Field
export KEY_NAME=”EasyRSA”


generate the new keys and certificate for your installation.

source ./vars

clean old keys


Build the Certificate Authority (CA), this will create a file ca.crt and ca.key in the directory /etc/openvpn/easy-rsa/2.0/keys/.


generate a server key and certificate. Run this command in the current directory

./build-key-server server

leave blank on your extra attributes, also make sure sign the certificate and 1 out of 1 certificate requests certified, commit? as “y”
Execute the build-dh command


Generate client key and certificate

./build-key client

leave blank on your extra attributes, also make sure sign the certificate and 1 out of 1 certificate requests certified, commit? as “y”

Move or copy the directory `keys/` to `/etc/opennvpn`.

cd /etc/openvpn/easy-rsa/2.0/
cp -r keys/ /etc/openvpn/

Configure OpenVPN file.

cd /etc/openvpn/
vi server.conf

Update the following below configuration

#change with your port
port 1337

#You can use udp or tcp
proto udp

# "dev tun" will create a routed IP tunnel.
dev tun

#Certificate Configuration

#ca certificate
ca /etc/openvpn/keys/ca.crt

#Server Certificate
cert /etc/openvpn/keys/server.crt

#Server Key and keep this is secret
key /etc/openvpn/keys/server.key

#See the size a dh key in /etc/openvpn/keys/
dh /etc/openvpn/keys/dh2048.pem

#Internal IP will get when already connect

#this line will redirect all traffic through our OpenVPN
push "redirect-gateway def1"

#Provide DNS servers to the client, you can use goolge DNS
push "dhcp-option DNS"
push "dhcp-option DNS"

#Enable multiple client to connect with same key

keepalive 20 60

#enable log
log-append /var/log/openvpn/openvpn.log

#Log Level
verb 3

Create log file.

mkdir -p /var/log/openvpn/
touch /var/log/openvpn/openvpn.log

Enable IP forwarding. Open /etc/sysctl.conf file for editing

vi /etc/sysctl.conf

Add to the /etc/sysctl.conf file

net.ipv4.ip_forward = 1
Disable SELinux
Disable firewalld and enable iptables
systemctl enable iptables
systemctl start iptables
iptables -F
Update NAT settings and enable openVPN ports on your firewall
iptables -A INPUT -p udp --dport 1337 -j ACCEPT

My eth0 (public traffic)ip is and eth1 (private traffic) ip is
openVPN tun0 ip is I enabled the VPN for both private and public networks.

ip route add private-net-subnet via host-private-ip
ip route add host-private-ip via vpn-private-ip

ip route add via
ip route add via
iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE
iptables -t nat -A POSTROUTING -o eth1 -j MASQUERADE

Client Setup

Download these client key files ca.crt,client.crt,client.key from your /etc/openvpn/keys folder

create a new file client.ovpn and update the below configuration.

dev tun
proto udp

#openvpn Server IP and Port
remote 1337

resolv-retry infinite
ca ca.crt
cert client.crt
key client.key
ns-cert-type server

Client Tools

Use above client.ovpn file in your client tool.

Windows OpenVPN client tool available

Mac OS user

Linux user
try networkmanager-openvpn through NetworkManager.

or use terminal

sudo openvpn --config client.ovpn



OpenVPN Setup PAM authentication with auth-pam module

The OpenVPN auth-pam module provides an OpenVPN server the ability to hook into Linux PAM modules adding a powerful authentication layer to OpenVPN.

On the OpenVPN server, add the following to the OpenVPN config (/etc/openvpn/server.conf)

plugin /usr/lib64/openvpn/plugins/ openvpn

For Ubuntu and Debian distributions, the path to the plugin is /usr/lib/openvpn/

Create a new PAM service file located at /etc/pam.d/openvpn.

auth required shadow nodelay
account required

On the OpenVPN client, add the following to the OpenVPN config(client.ovpn)


Restart the OpenVPN server. Any new OpenVPN connections will first be authenticated with so the user will need a system local account.

If the OpenVPN server exits with the log below after an authentication attempt, you most likely are running OpenVPN within a chroot and have not created a tmp directory.

Could not create temporary file '/tmp/openvpn_acf_xr34367701e545K456.tmp': No such file or directory

Simply create a tmp directory within the chroot with the permissions that match your OpenVPN server config.

# grep -E "(^chroot|^user|^group)" /etc/openvpn/server.conf
chroot /var/lib/openvpn
user openvpn
group openvpn

# mkdir --mode=0700 -p /var/lib/openvpn/tmp
# chown openvpn:openvpn /var/lib/openvpn/tmp


To Extend the OpenVPN PAM service

You can extend the use of PAM by adding to the /etc/pam.d/openvpn file.


#auth [user_unknown=ignore success=ok ignore=ignore default=bad]
auth substack system-auth
auth include postlogin
account required
account include system-auth
password include system-auth
# close should be the first session rule
session required close
session required
session optional
# open should only be followed by sessions to be executed in the user context
session required open
session required
session optional force revoke
session include system-auth
session include postlogin
-session optional


Restart openvpn service.



Set up an iSCSI Target and Initiator and configure multipath

We used two CentOS 7 VMs to configure the Set up an iSCSI Target and Initiator and configure multipath settings.

Network1 :
Network2 :

Network1 :
Network2 :

Configure iSCSI Target and initiator and multipath

iSCSI Target and Initiator

iSCSI Target Creation

An iSCSI target can be a dedicated physical device in a network, or it can be an iSCSI software-configured logical device on a networked storage server. The target is the end point in SCSI bus communication. Storage on the target, accessed by an initiator, is defined by LUNs.

Login network-vm2 server and install scsi-target-utils.

Install RPEL release repo.

[[email protected] ~]# yum install epel-release -y
[[email protected] ~]# yum install scsi-target-utils -y

Make sure you enabled the port 3260 in firewall.

example in iptables
[[email protected] ~]# iptables -I INPUT -p tcp -m tcp --dport 3260 -j ACCEPT

Start and enable the target service.

[[email protected] ~]# service tgtd start
[[email protected] ~]# systemctl enable tgtd

Attach storage for the LUNs and create partition.

[[email protected] ~]# fdisk /dev/sdb
Welcome to fdisk (util-linux 2.23.2).

Changes will remain in memory only, until you decide to write them.
Be careful before using the write command.

Device does not contain a recognized partition table
Building a new DOS disklabel with disk identifier 0xdd5037ae.

Command (m for help): n
Partition type:
p primary (0 primary, 0 extended, 4 free)
e extended
Select (default p):
Using default response p
Partition number (1-4, default 1):
First sector (2048-104857599, default 2048):
Using default value 2048
Last sector, +sectors or +size{K,M,G} (2048-104857599, default 104857599):
Using default value 104857599
Partition 1 type Linux and size 50 GiB is set

Command (m for help): w
The partition table has been altered!

Calling ioctl() to re-read partition table.
Syncing disks.

Create the target in /etc/tgt/targets.conf file.

[[email protected] ~]# vi /etc/tgt/targets.conf

default-driver iscsi
backing-store /dev/sdb1

Restart the target service.

[[email protected] ~]# service tgtd restart
Redirecting to /bin/systemctl restart tgtd.service

Verify your configurations.

[[email protected] ~]# tgt-admin --show
Target 1:
System information:
Driver: iscsi
State: ready
I_T nexus information:
LUN information:
LUN: 0
Type: controller
SCSI ID: IET 00010000
SCSI SN: beaf10
Size: 0 MB, Block size: 1
Online: Yes
Removable media: No
Prevent removal: No
Readonly: No
Thin-provisioning: No
Backing store type: null
Backing store path: None
Backing store flags:
LUN: 1
Type: disk
SCSI ID: IET 00010001
SCSI SN: beaf11
Size: 53686 MB, Block size: 512
Online: Yes
Removable media: No
Prevent removal: No
Readonly: No
Thin-provisioning: No
Backing store type: rdwr
Backing store path: /dev/sdb1
Backing store flags:
Account information:
ACL information:

Install iSCSI Initiator and configure it

Login your network-vm2 server and Install iscsi-initiator-utils

[[email protected] ~]# yum install iscsi-initiator-utils -y

Discover the target. Use the target’s IP address.

[[email protected] ~]# iscsiadm -m discovery -t sendtargets -p,1

[[email protected] ~]# iscsiadm -m discovery -t sendtargets -p,1

Connect to the target.

[[email protected] ~]# iscsiadm -m node -T --login
Logging in to [iface: default, target:, portal:,3260] (multiple)
Login to [iface: default, target:, portal:,3260] successful.
[[email protected] ~]#

Login to all the targets

[[email protected] ~]# iscsiadm -m node -l

Check the list of drives.

[[email protected] ~]# fdisk -l
Disk /dev/sdb: 53.7 GB, 53686042624 bytes, 104855552 sectors
Units = sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes

If you want to create a file system and mount.

[[email protected] ~]# mkfs.ext4 /dev/sdb

[[email protected] ~]# mount /dev/sdb /opt/iscsi-drive

[[email protected] ~]# blkid /dev/sdb
/dev/sdb: UUID="3b7e58de-1342-4fbb-98fc-9e5d5888e770" TYPE="ext4"
Configuring Multipath for ISCSI storage LUNS in centos 7

I am using network-vm2 server to configure multipath.

Install multipath packages and start it.

[[email protected] ~]# yum install device-mapper-multipath -y

[[email protected] ~]# systemctl start multipathd

Verify the iscsi targets

[[email protected] ~]# iscsiadm -m discovery -t sendtargets -p,1

[[email protected] ~]# iscsiadm -m discovery -t sendtargets -p,1

Login to all the targets

[[email protected] ~]# iscsiadm -m node -l
Logging in to [iface: default, target:, portal:,3260] (multiple)
Login to [iface: default, target:, portal:,3260] successful.

Configure basic Multipath

[[email protected] ~]# mpathconf --enable --with_multipathd y

add entries

[[email protected] ~]# vi /etc/multipath.conf

defaults {
polling_interval 10
path_selector "round-robin 0"
path_grouping_policy multibus
path_checker readsector0
rr_min_io 100
max_fds 8192
rr_weight priorities
failback immediate
no_path_retry fail
user_friendly_names yes
[[email protected] ~]# multipath -ll
mpatha (360000000000000000e00000000010001) dm-2 IET ,VIRTUAL-DISK
size=50G features='0' hwhandler='0' wp=rw
`-+- policy='round-robin 0' prio=1 status=active
|- 3:0:0:1 sdb 8:16 active ready running
`- 4:0:0:1 sdc 8:32 active ready running

Adding Target partition to multipath

Adding Multipath Alias for the Iscsi LUNs in /etc/multipath.conf

multipaths {
multipath {
wwid 360000000000000000e00000000010001
alias LUN0

Restart multipathd service

[[email protected] ~]# systemctl restart multipathd
[[email protected] ~]# multipath -ll
LUN0 (360000000000000000e00000000010001) dm-2 IET ,VIRTUAL-DISK
size=50G features='0' hwhandler='0' wp=rw
`-+- policy='round-robin 0' prio=1 status=active
|- 3:0:0:1 sdb 8:16 active ready running
`- 4:0:0:1 sdc 8:32 active ready running

check the list of drives

Disk /dev/mapper/LUN0: 53.7 GB, 53686042624 bytes, 104855552 sectors
Units = sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes



Detect New Hard Disk Without Reboot VMware

A new hard disk to your Linux OS running on any Virtual Environment which like VMware workstation. It won’t reflect unless you reboot the Guest OS. In order to detect the new hard drive without reboot use the following steps.

Add a New Disk To VM

First, you need to add hard disk by visiting VMware hardware settings menu.
Click on VM > Settings

Once done, check your existing iscsi device configured on your Linux.

# ls -l /sys/class/scsi_host/
total 0
lrwxrwxrwx 1 root root 0 Feb 10 04:25 host0 -> ../../devices/pci0000:00/0000:00:07.1/ata1/host0/scsi_host/host0
lrwxrwxrwx 1 root root 0 Feb 10 04:25 host1 -> ../../devices/pci0000:00/0000:00:07.1/ata2/host1/scsi_host/host1
lrwxrwxrwx 1 root root 0 Feb 10 04:25 host2 -> ../../devices/pci0000:00/0000:00:10.0/host2/scsi_host/host2

Detect a new hard drive attached you need to first get your host bus number used which you can get by using below command

# grep mpt /sys/class/scsi_host/host?/proc_name

You should get an output like below


Rescan the SCSI Bus to Add a SCSI Device Without rebooting the VM

A rescan can be issued by typing the following command:

# echo "- - -" > /sys/class/scsi_host/host2/scan

Once done verify the list of drives in your machine.

# fdisk -l

Change root password on kvm qcow2 image

How to change root password on kvm qcow2 image

guestfish is an interactive shell that you can use from the command line or from shell scripts to access guest virtual machine file systems. All of the functionality of the libguestfs API is available from the shell.

We will use the guestfish tool to modify the password details and Changing the ‘root’ password on kvm qcow2 (images) for OpenStack environments.

Install lib modules

# yum -y install libguestfs libguestfs-tools*

Generate an encrypted password

# openssl passwd -1 "password"

I used the centos image “CentOS-7-x86_64-GenericCloud-1608.qcow2”

# guestfish -a CentOS-7-x86_64-GenericCloud-1608.qcow2

Welcome to guestfish, the guest filesystem shell for
editing virtual machine filesystems and disk images.

Type: ‘help’ for help on commands
‘man’ to read the manual
‘quit’ to quit the shell

<fs> run
><fs> list-filesystems
/dev/sda1: xfs
><fs> mount /dev/sda1 /
><fs> vi /etc/shadow (update the encrupted password)
><fs> quit


Create new VM from this qcow2 image and verify the modified password.



# guestfish -a CentOS-7-x86_64-GenericCloud-1608.qcow2

Welcome to guestfish, the guest filesystem shell for
editing virtual machine filesystems and disk images.

Type: ‘help’ for help on commands
‘man’ to read the manual
‘quit’ to quit the shell

><fs> run
libguestfs: error: could not create appliance through libvirt.

Try running qemu directly without libvirt using this environment variable:

Original error from libvirt: Cannot access storage file ‘/root/CentOS-7-x86_64-GenericCloud-1608.qcow2’ (as uid:107, gid:107): Permission denied [code=38 int1=13]
><fs> quit
I am running this commands from the openstack qemu environment and it should need to move image file to libvirt image folder.

# mv /root/CentOS-7-x86_64-GenericCloud-1608.qcow2 /var/lib/libvirt/images/

That’s it. Try again with run command.



Add Compute Node on Existing OpenStack using Packstack

While single-node configurations are acceptable for small environments, testing or POCs most production environments will require a multi-node configuration for various reasons. As we know multi-node configurations group similar OpenStack services and provide scalability as well as the possibility for high availability. One of the great things about OpenStack is the architecture. Every service is decoupled and all communication between services is done through RESTful API endpoints. This is the model architecture for a cloud. The advantages are that we have tremendous flexibility in how to build a multi-node configuration. While a few standards have emerged there are many more possible variations and in the end, we are not stuck to a rigid deployment model. The standards for deploying multi-node OpenStack are as a two-node, three-node or four-node configuration. Add compute node on existing openstack using packstack installation.

add compute node

You have installed OpenStack all-in-one with PackStack on your setup. In this tutorial, we will extend existing OpenStack installation (Controller node, Compute node) with new Compute-node1 on-line, without shutting down existing nodes. The easiest and fastest way to extend existing OpenStack Cloud on-line is to use Packstack. We will see how to add Compute Node on Existing OpenStack using Packstack.
Existing nodes:
Installed as all-in-one with packstack

Controller node:, CentOS72
Compute node:, CentOS72

New Compute node:
Compute-node1 :, CentOS72

add additional compute node on my existing all-in-one packstack setup.


Step 1:

Edit the original answer file provided by packstack. This can usually be found in the directory from where packstack was first initiated.

Log in to existing all-in-one node as root and backup your existing answers.txt file:

# cp /root/youranwserfile.txt /root/youranwserfile.txt.old
# vi /root/youranwserfile.txt

Change the value for CONFIG_COMPUTE_HOSTS from the current to the value of your second compute host IP address and update exclude current node IP in EXCLUDE_SERVERS.

Ensure you have set correct IPs in EXCLUDE_SERVERS parameter to prevent existing nodes from being accidentally re-installed

My changes on this node



Here I have added my existing compute node ip to EXCLUDE_SERVERS and replaced the CONFIG_COMPUTE_HOSTS with my new compute node ip

If you have multiple IPs in existing node then mention those ips also in EXCLUDE_SERVERS using comma(,


If you have different network card uses, update your network name. example from lo to eth1


Step 2:

Prepare your new compute node for the OpenStack deployment.

– stop NetworkManager service
– disable selinux
– allow ssh access from existing node

Step 3:

That’s it. Now run packstack again on the controller node.

# packstack --answer-file=/root/youranwserfile.txt
Clean Up [ DONE ]
[email protected]'s password: 
Setting up ssh keys [ DONE ]
Discovering hosts' details [ DONE ]
Adding pre install manifest entries [ DONE ]
Installing time synchronization via NTP [ DONE ]
Preparing servers [ DONE ]
Checking if NetworkManager is enabled and running [ DONE ]
Adding OpenStack Client manifest entries [ DONE ]
Adding Horizon manifest entries [ DONE ]
Adding Swift Keystone manifest entries [ DONE ]
Adding Swift builder manifest entries [ DONE ]
Adding Swift proxy manifest entries [ DONE ]
Adding Swift storage manifest entries [ DONE ]
Adding Swift common manifest entries [ DONE ]
Adding Provisioning manifest entries [ DONE ]
Adding Provisioning Glance manifest entries [ DONE ]
Adding Provisioning Demo bridge manifest entries [ DONE ]
Adding Gnocchi manifest entries [ DONE ]
Adding Gnocchi Keystone manifest entries [ DONE ]
Adding MongoDB manifest entries [ DONE ]
Adding Redis manifest entries [ DONE ]
Adding Ceilometer manifest entries [ DONE ]
Adding Ceilometer Keystone manifest entries [ DONE ]
Adding Aodh manifest entries [ DONE ]
Adding Aodh Keystone manifest entries [ DONE ]
Adding Nagios server manifest entries [ DONE ]
Adding Nagios host manifest entries [ DONE ]
Copying Puppet modules and manifests [ DONE ]
Applying [ DONE ]
Applying [ DONE ]
Applying [ DONE ]
Applying [ DONE ]
Applying Puppet manifests [ DONE ]
Finalizing [ DONE ]

**** Installation completed successfully ******

Additional information:
* Time synchronization installation was skipped. Please note that unsynchronized time on server instances might be problem for some OpenStack components.
* File /root/keystonerc_admin has been created on OpenStack client host To use the command line tools you need to source the file.
* To access the OpenStack Dashboard browse to .
Please, find your login credentials stored in the keystonerc_admin in your home directory.
* To use Nagios, browse to username: nagiosadmin, password: e68a1a992d2b44fd
* The installation log file is available at: /var/tmp/packstack/20161118-074021-mhbsqe/openstack-setup.log
* The generated manifests are available at: /var/tmp/packstack/20161118-074021-mhbsqe/manifests

Step 4 :

Verify your new compute node is include with existing controller.

[[email protected] ~]# source /root/keystonerc_admin
[[email protected] ~(keystone_admin)]# nova-manage service list
Binary Host Zone Status State Updated_At
nova-osapi_compute internal enabled XXX None
nova-metadata internal enabled XXX None
nova-cert internal enabled :-) 2016-11-19 12:59:57
nova-consoleauth internal enabled :-) 2016-11-19 12:59:57
nova-scheduler internal enabled :-) 2016-11-19 12:59:55
nova-conductor internal enabled :-) 2016-11-19 12:59:56
nova-compute nova enabled :-) 2016-11-19 12:59:56
nova-compute nova enabled :-) 2016-11-19 13:00:04

That’s it.


Add Additional Storage Node

It shows as unsupported version, anyway change CONFIG_UNSUPPORTED=y  on your /root/youranwserfile.txt file and updated CONFIG_STORAGE_HOST with your new storage node.

# (Unsupported!) Server on which to install OpenStack services# specific to storage servers such as Image or Block Storage services.