Showing posts with label linux. Show all posts
Showing posts with label linux. Show all posts

Tuesday, November 7, 2017

Linux SSH - Automation with Send & Expect Scripts

By Ken Hess

Expect is a natural and intuitive automation scripting language that operates in much the same way humans do when interacting with a system. You type in commands and expect a certain response to your command. When you receive the expected response, you enter another command and so on. Expect works in the same way, except you have to provide the script with commands and expected responses to those commands. Basically, you have to script out the entire two-way “conversation.”


You can think of an Expect script as a dialog script written for two actors: a sender and a receiver. One of the more popular activities to automate is an SSH session between two hosts, in which one host is the sender (local host) and the other is the receiver (remote host). Being able to emulate every keystroke and create a true interactive session between two systems via a script is an exciting proposition.


Expect Setup

Most Linux distributions include Expect as part of the available and installable software packages. In other words, you won’t have to download and install from source code. Use your system’s package manager to download and install Expect and any required dependencies or associated packages. For example:


$ sudo yum install expect
or
$ sudo apt-get install expect


Once you have Expect installed, you can begin writing scripts.


Creating an Interactive SSH Session

As stated previously, you must provide both sides of the conversation in your script because you’re setting up an interactive system. Look at a few essential items before diving right into a script.


To make an Expect script executable as a standalone program, you must do two things: Make the script executable, and supply the path to the script for expect . The path on my system is: /usr/bin/expect ; therefore, enter that path on the first line of your script with a preceding “shebang” (#! ):

#!/usr/bin/expect -f

The -f switch tells Expect that it is reading commands from a file.


The spawn command spawns or launches an external command for you. In this case, ssh to a remote host (aspen ):

spawn ssh aspen

Change the host aspen to your remote host. When you SSH to a remote system, you’re prompted for a password. This password prompt is what you “expect” from the remote system; therefore, you enter that expected response:

expect "password: "

From the local side, you have to enter your password at the password prompt. To send anything to the remote system, it must be included in double quotes and must include a hard return (\r ). Change PASSWORD to your password:

send "PASSWORD\r"

Again, you have to enter the expected response from the remote system, which in this case is a user prompt ($ ).

expect "$ "

Now that you’re logged in to the remote system, you can begin your interactive session on that remote host. The following send command issues the ps -ef |grep apache command:

send "ps -ef |grep apache\r"

Output will appear as STDOUT. After the command has executed, you’re returned to a prompt, so tell the Expect script that bit of information:

expect "$ "

Finally, send the exit command to the remote system to log out. Don’t forget that hard return (\r ):

send "exit\r"

The script in its entirety looks as follows:

#!/usr/bin/expect -f
spawn ssh aspen
expect "password: "
send "PASSWORD\r"
expect "$ "
send "ps -ef |grep apache\r"
expect "$ "
send "exit\r"

Change permissions on the script so that it is executable; for example,

$ chmod 755 script.sh

and try it for yourself.


Expect Caveats

If your script hangs and doesn’t continue, try the command manually yourself and look for the response. If the remote system drops you to a prompt as its final act, then place that in your script (e.g., expect "$ " ). Be sure you have entered the hard return (\r ) inside the closing quotation mark in your send line. You might also find that your system needs two backslashes on the send line for a hard return (\r ).


Sometimes Expect scripts execute too fast, and you won’t see your expected response. If that happens, place a sleep command and a number of seconds for the command preceeding it to wait for a response, or your data might be ignored.
For example, if you connect to a remote system and there’s a delay in creating that connection, your script will continue to execute and fail because it sends commands before the remote system has time to respond.


You have to think about network delays, shell responses and system timing when scripting in Expect. Like any scripting language, Expect has its quirks, but you’ll find that it’s an easy way to automate those repetitious keystrokes and procedures. The time you spend debugging your scripts is well worth the effort.


Autoexpect

Of course, some lazy system administrators take lazy to a higher level and even cheat at writing Expect scripts by invoking a shell “watcher” or recorder script named Autoexpect. Once invoked, Autoexpect watches your every keystroke and records it to a file named, script.exp by default. You’ll almost certainly have to edit and prune this script to achieve your desired results; however, it can save hours of script debugging to have an almost complete script from which to work.


If you simply run a freshly created Autoexpect script, it will likely fail because, if you issued a command that answers your request by displaying information to the screen, the script picks up that answer, too, and copies it into the script file.
For example, if during your Autoexpect session, you type, ls , the result of that command appears in your script.exp file as well. After you’ve created a few Expect scripts by hand, you’ll appreciate the cleanup editing you have to do in an Autoexpect-created script.
To install Autoexpect, issue a command like:

$ sudo apt-get install expect-dev

You’ll likely require many more dependencies for this feature, so prepare yourself for a slight delay while everything installs.


Creating an Interactive SSH Session with Autoexpect

After installing Autoexpect and all of its required packages, you’re ready to create Expect scripts automatically by stepping through the procedures you want to automate. Using the above example, SSH to a remote system and run a

ps -ef |grep apache

command and then log out.
Invoking Autoexpect is easy:

$ Autoexpect

Autoexpect started, file is script.exp
$

Although it looks as if nothing has happened or is happening, every keystroke you type will be recorded into script.exp . Every STDOUT response you receive will also be copied into that same file. Your entire session is recorded – but not just recorded, it is also formatted in Expect script style. To stop recording keystrokes to your script, press Ctrl+D on your keyboard to stop Autoexpect and copy the buffer to your file.


The complete transcription of this simple procedure is very long and includes a lot of commentary from the author, Don Libes:

#!/usr/bin/expect -f
#
# This Expect script was generated by Autoexpect on Thu Oct 11 15:53:18 2012
# Expect and Autoexpect were both written by Don Libes, NIST.
#
# Note that Autoexpect does not guarantee a working script.  It
# necessarily has to guess about certain things.  Two reasons a script
# might fail are:
#
# 1) timing - A surprising number of programs (rn, ksh, zsh, telnet,
# etc.) and devices discard or ignore keystrokes that arrive "too
# quickly" after prompts.  If you find your new script hanging up at
# one spot, try adding a short sleep just before the previous send.
# Setting "force_conservative" to 1 (see below) makes Expect do this
# automatically - pausing briefly before sending each character.  This
# pacifies every program I know of.  The -c flag makes the script do
# this in the first place.  The -C flag allows you to define a
# character to toggle this mode off and on.

set force_conservative 0  ;# set to 1 to force conservative mode even if
                           ;# script wasn’t run conservatively originally
if {$force_conservative} {
         set send_slow {1 .1}
         proc send {ignore arg} {
                 sleep .1
                 exp_send -s -- $arg
         }
}

#
# 2) differing output - Some programs produce different output each time
# they run.  The "date" command is an obvious example.  Another is
# ftp, if it produces throughput statistics at the end of a file
# transfer.  If this causes a problem, delete these patterns or replace
# them with wildcards.  An alternative is to use the -p flag (for
# "prompt") which makes Expect only look for the last line of output
# (i.e., the prompt).  The -P flag allows you to define a character to
# toggle this mode off and on.
#
# Read the man page for more info.
#
# -Don

set timeout -1
spawn $env(SHELL)
match_max 100000
expect -exact "]0;khess@trapper: ~khess@trapper:~\$ "
send -- "ssh aspen\r"
expect -exact "ssh aspen\r
khess@aspen’s password: "
send -- "PASSWORD\r"
expect -exact "\r
Linux aspen 2.6.32-43-server #97-Ubuntu SMP Wed Sep 5 16:56:41 UTC 2012 x86_64 GNU/Linux\r
Ubuntu 10.04.4 LTS\r
\r
Welcome to the Ubuntu Server!\r
  * Documentation: 
http://www.ubuntu.com/server/doc\r
\r
   System information as of Thu Oct 11 15:55:28 CDT 2012\r
\r
   System load:  1.09               Temperature:         40 C\r
   Usage of /:   1.0% of 454.22GB   Processes:           168\r
   Memory usage: 22%                Users logged in:     1\r
   Swap usage:   0%                 IP address for eth0: 192.168.1.250\r
\r
   Graph this data and manage this system at
https://landscape.canonical.com/\r
\r
7 packages can be updated.\r
7 updates are security updates.\r
\r
New release ‘precise’ available.\r
Run ‘do-release-upgrade’ to upgrade to it.\r
\r
*** System restart required ***\r
Last login: Thu Oct 11 15:53:41 2012 from trapper\r\r
]0;khess@aspen: ~khess@aspen:~\$ "
send -- "ps -ef|grep apache\r"
expect -exact "ps -ef|grep apache\r
www-data   555 23171  0 Oct07 ?        00:00:00 /usr/sbin/apache2 -k start\r
www-data   556 23171  0 Oct07 ?        00:00:00 /usr/sbin/apache2 -k start\r
www-data   557 23171  0 Oct07 ?        00:00:00 /usr/sbin/apache2 -k start\r
www-data   558 23171  0 Oct07 ?        00:00:00 /usr/sbin/apache2 -k start\r
www-data   559 23171  0 Oct07 ?        00:00:00 /usr/sbin/apache2 -k start\r
khess    21504 21433  0 15:55 pts/1    00:00:00 grep apache\r
root     23171     1  0 Sep27 ?        00:00:28 /usr/sbin/apache2 -k start\r
]0;khess@aspen: ~khess@aspen:~\$ "
send -- "exit\r"
expect -exact "exit\r
logout\r
Connection to aspen closed.\r\r
]0;khess@trapper: ~khess@trapper:~\$ "
send -- "^D"
expect eof
khess@trapper:~$
You can see that you have a lot of cleanup to do before you distill this transcript down to its essential parts. Autoexpect also changes permissions on the script.exp file so that it is executable.
The parts you needed for this script to execute correctly are shown below in my cleaned up version.
#!/usr/bin/expect -f

set force_conservative 0  ;# set to 1 to force conservative mode even if
                           ;# script wasn’t run conservatively originally
if {$force_conservative} {
         set send_slow {1 .1}
         proc send {ignore arg} {
                 sleep .1
                 exp_send -s -- $arg
         }
}

set timeout -1
spawn $env(SHELL)
match_max 100000
expect -exact "$ "
send -- "ssh aspen\r"
expect -exact "password: "
send -- "PASSWORD\r"
expect -exact "$ "
send -- "ps -ef|grep apache\r"
expect -exact "$ "
send -- "exit\r"
expect -exact "$ "


You can see that the complex prompts, such as

expect -exact "exit\r
logout\r
Connection to aspen closed.\r\r
]0;khess@trapper: ~khess@trapper:~\$ "

have been shortened significantly to:

expect -exact "$ "

The prompt still works because Expect looks for the last few characters in an expect line and not the entire string. You could shorten the line that expects the password prompt from:

expect -exact "password: "
to
expect -exact ": "

A word of caution against shortening your expect lines too much – it makes the script more difficult, not easier, to read and interpret in the future when you try to figure out what’s going on.

You might not realize that ": " is a password prompt. Unless you’re great at including comments in your scripts, you might spend hours debugging this shortened version.


Summary

To be perfectly honest, I only use Autoexpect when building an Expect draft script. To sit down and attempt writing Expect line-by-line just isn’t appealing after being seduced and ruined by the ease of removing unwanted lines from an Autoexpect-created script. Autoexpect makes using Expect fun and more intuitive by letting you perform a procedure one time instead of many. After discovering and using Autoexpect, my Expect scripting creation time and debug time has been cut by at least two-thirds. I suspect you’ll have much the same return on your time as well.


Taken From: http://www.admin-magazine.com/Articles/Automating-with-Expect-Scripts

Saturday, February 11, 2017

Linux/Raspberry - Web SSH Shell (No client needed)

You probably access you linux machines via SSH using a client like Putty.

With Shell In A Box, you get the same SSH access but without any client, you just use a browser that shows you the the SSH connection via HTTPS.

This might be usefull in some scenario, so I’m going to show you how to set up it bellow.

To install just type:

sudo apt-get install shellinabox

and that’s it once it finished installing, Shell In A Box is running, just go to you browser and enter this

https://<Machine_IP>:4200/

and you should get this

image

now just login and that’s it.

If you want to change something (ex: the 4200 port) you just edit this file:

nano /etc/default/shellinabox

FILE: shellinabox
----------------------------

# Should shellinaboxd start automatically
SHELLINABOX_DAEMON_START=1

# TCP port that shellinboxd's webserver listens on
SHELLINABOX_PORT=4200

# Parameters that are managed by the system and usually should not need
# changing:
# SHELLINABOX_DATADIR=/var/lib/shellinabox
# SHELLINABOX_USER=shellinabox
# SHELLINABOX_GROUP=shellinabox

# Any optional arguments (e.g. extra service definitions).  Make sure
# that that argument is quoted.
#
#   Beeps are disabled because of reports of the VLC plugin crashing
#   Firefox on Linux/x86_64.
SHELLINABOX_ARGS="--no-beep"

and do

 sudo service shellinabox restart

to load the new configuration.

Monday, February 6, 2017

Docker - Running Applications on Docker Containers

Docker is a “container” platform, which allows applications to be run in their own sandboxed world. These applications share resources, e.g. things like hard drive space or RAM, but otherwise can’t interfere with programs running on the host system. For corporate servers this means an attacker may not be able to use a compromised web server to get at the database holding customer data.

For the desktop user, it means the bleeding-edge app you’re trying out can’t accidentally delete all your cat’s selfies.

 

Pros and Cons of Using Docker

There are several good reasons to try out new programs via Docker, including the following:

  • They are safely isolated from your system, without the means to do damage in most cases.
  • Docker containers have a mechanism to keep them up-to-date, meaning it’s easy to make sure you have the latest and greatest versions.
  • You’re not installing anything on your “real” system, so you won’t run into conflicts with your “regular” versions on the application. You could, for example, run LibreOffice on your host system, but run OpenOffice in a container (you know, in case you don’t believe the project is shutting down).
  • Speaking of versions, you can even have multiple (but different) copies of the same version running on your machine at once. Try that with Word 2016!
  • Some Docker apps run their own minimized version of Linux. This means even if the app isn’t normally compatible with Mac or Windows it may still work for you within a Docker container. Try them out before you switch to Linux full time.
  • They’re easy to clean up. Don’t like the way things turned out? Just trash the container and create a new one.

On the other hand, there are some caveats to using applications this way:

  • As they operate in their own little world, they don’t have access to your files unless you give it to them. That means if you want to try the brand new version of LibreOffice via Docker, you may need to do some additional work to make your files accessible.
  • In general, Docker apps ship with everything they need to run, which often includes libraries that could be re-used with other programs. Some even ship with a full operating system behind them. So you may be doubling up on disk space usage.
  • They don’t provide convenient icons and other desktop-centric niceties. While we’ll show you a GUI you can use to download and run these Docker containers, they won’t show up in your main application launcher unless you create an entry by hand.
  • Like many things open source, it’s members of the community who have been creating these Docker applications from their upstream releases. This means your access to the latest version and/or any bugfixes is at the mercy of these peoples’ free time.

 

Installation and Usage

Getting things up and running involves three preliminary steps:

  1. First, get Docker installed and running on your system (including a graphical interface for it, if you want one).
  2. Next, find and download an image for the application you want to run. While you normally install an application, you get one (and only one) copy of it. Think of an image as a template for the application — you can create as many installs from this template as you like.
  3. Lastly, create one of those copies, called a container, and run it.

Let’s look at each of these in detail.

 

Installation

Most Linux distribution have Docker available in repositories for easy installation. In Ubuntu, the following command will get you what you need:

sudo apt-get install docker.io

You can confirm the system is running by confirming the “dockerd” daemon is running (you do know how to use ps, grep, and pipes, don’t you?): An A-Z of Linux - 40 Essential Commands You Should Know An A-Z of Linux - 40 Essential Commands You Should Know Linux is the oft-ignored third wheel to Windows and Mac. Yes, over the past decade, the open source operating system has gained a lot of traction, but it’s still a far cry from being considered... Read More

ps ax | grep dockerd

The Docker daemon will start up with your system automatically by default, but you can set that differently if you know how to adjust your systemd settings.

If you’re interested, you can also grab the Simple Docker UI Chrome app. Follow the instructions here to get things set up so you can connect to the Docker daemon on your machine.

clip_image001

Note: If you use Simple Docker UI, make sure you add yourself to the “docker” user group as described here. If you’re not part of this group, you won’t be able to use Docker commands from your normal (non-root) user account, the one with which you’ll be running Chrome and its apps, without using sudo all the time.

 

Finding and Installing Desktop Applications With Docker

Now that you’ve got a nice UI going, it’s time to find something to install. Your first stop should be the Hub, a repository of applications hosted by the docker project. Another straightforward way to find some interesting applications is to Google for them. In either case look for a “Launch Command” along the lines of the following:

docker run -it -v someoptions \

-e more options \

yet even more options...

Paste this into a terminal and it will download and launch the application for you.

You can also “pull” the application, then launch it yourself. If you’re using the Simple UI app, it can search Docker Hub automatically for your keyword.

clip_image002

Once you’ve found what you’re looking for, click its listing, then the Pull Image button in the pop-up dialog to download the image of the application.

clip_image003

Remember, an image is a “template” of sorts. Next you’ll need to create a container that uses your new image. Switch over to the Images tab. Clicking the Deploy Container button will create a new, runnable copy of your application.

clip_image004

 

 

Running Your New Docker Container

From the command line, you can view a list of all your docker containers with the command:

docker ps -a

clip_image005

This lists the containers with some of their stats — note the “NAMES” column to the far right. To restart one of your containers, pick the name of the container you want and issue the following:

docker start [containername]

Using the app, go the “Containers” screen, select the container you want, and click the “Start” button in the upper left of the screen. Your application will start in a new window on your desktop, just like a “normal” application.

clip_image006

Your application should open in a new window, just as if you had installed it normally. But remember, it exists in isolation from your other applications. This allows you to do some neat things, like run LibreOffice and OpenOffice in parallel (their dependencies usually conflict with one another):

clip_image007

 

Try Docker-ized Apps for Fun and Profit

Docker provides an easy way to get an app up and running so you can try it out, and an equally easy way to clean it from your system. Once you get through the initial set-up of Docker, a single run command is often all you need to download an image, create a container from it, and launch it on your desktop.

 

Taken From: http://www.makeuseof.com/tag/safely-test-desktop-applications-secure-container-docker/

Tuesday, January 3, 2017

Finding Your Public IP with Telnet (CLI)

Her I’m going to show you a little trick off a way to get you public IP when you just have a command line interface.

This can be done in any equipment with telnet like a:

  • Router
  • Switch
  • Linux Server
  • etc

 

How To Do It – Site: Check IP

The webpage:

gives out you public IP on a Browser, so what we are going to do is to open the Web Page on the HTTP Port (Port 80), and get a response from the webpage with you Public IP.

This Web Page does not need you to send HTML to pretend that your telnet is a Web Browser (like the IP Echo Website bellow)

To do it:

telnet checkip.dyndns.org 80

or

telnet 216.146.38.70 80

if you don’t have DNS configured, and then do as soon as it connects press:

  • ENTER (one or two times)

and it will give you the output bellow.

image

 

 

How To Do It – Site: IP Echo 

The webpage:

gives out you public IP on a Browser, so what we are going to do is to open the Web Page on the HTTP Port (Port 80), and then send some HTML code to pretend that your telnet is a Web Browser to get the HTML response from the webpage with you Public IP.

To do it:

telnet ipecho.net 80

or

telnet 146.255.36.1 80

if you don’t have DNS configured, and then paste the following HTML code

GET / HTTP/1.1
Host: ipecho.net
User-Agent: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)

and press Enter, and you get this:

01

rigth here you can see you IP.

 

See Public IP on a Browser

In both methods/sites if you want, you can see the IP in a more pretty way, just copy the HTML code the Web Page returned (this output is from the IP Echo site):

02

to a text file with the “.html” extension in the computer you are using, I named mine index.html

03

save it and double click in the index.html which will open on your default browser, and show the HTML you copied from the command line:

04

Saturday, July 16, 2016

Linux - Wifi Configuration (Detailed)

This guide was tested with Dapper Drake, Feisty Fawn, Gutsy Gibbon, and Hardy Heron.

Since it appears that very few people take wireless security seriously, I'd like to come up with my first HOWTO and explain how I was able to configure a secure home network using WPA2, the latest encryption & authentication standard. There are also other types of configuration (WPA1, mixed mode, LEAP, PEAP, DHCP, etc.) shown in the appendix. Feedback is much appreciated.

Common stumbling blocks - Make sure that:

  1. Ethernet cable is unplugged.
  2. No firewall & configuration tool is running (e.g. Firestarter).
  3. MAC filtering is disabled.
  4. NetworkManager, Wifi-Radar & similar wireless configuration tools are disabled/turned off and not in use.
  5. Some cards/drivers (e.g. Madwifi) do not support WPA2 (AES). Try WPA1 (TKIP) if WPA2 secured connections fail.
  6. RTxxx (Ralink) drivers do not support this approach. Either install "ndiswrapper" replacing Serialmonkey's driver or visit this site.
  7. Turn off "roaming" if you repeatedly fail to establish a connection.


My Requirements:
1. WPA2 / RSN
2. AES / CCMP
3. Hidden ESSID (no broadcast)
4. Static IP (because I use port forwarding & firewall, etc.)
5. Pre-shared key (no EAP)
If you want to know more about WPA / RSN & 802.11i security specification, I recommend this site.


Now let's get started:


0. Install "wpa-supplicant":

sudo apt-get install wpasupplicant

1. Verify that your network device ("wlan0"?) is working & your wireless network is detected:

iwconfig

iwlist scan

Your network device & wireless network should appear here.


2. Open "/etc/network/interfaces":

sudo gedit /etc/network/interfaces

The content should look similar to this:

auto lo
iface lo inet loopback
auto wlan0
iface wlan0 inet dhcp

3. Now replace the last 2 lines with the following using your own network settings (the sequence in which the lines appear is crucial):

auto wlan0
iface wlan0 inet static
address 192.168.168.40
gateway 192.168.168.230
dns-nameservers 192.168.168.230
netmask 255.255.255.0

wpa-driver wext
wpa-ssid
<your_essid>
wpa-ap-scan 2
wpa-proto RSN
wpa-pairwise CCMP
wpa-group CCMP
wpa-key-mgmt WPA-PSK
wpa-psk
<your_hex_key> [IMPORTANT: See "WPA-PSK key generation"]

  • auto wlan0:
    Your network interface (e.g. wlan0, eth1, rausb0, ra0, etc.).
  • iface wlan0 inet static:
    Self-explanatory... I am using a Static IP instead of DHCP. "iface wlan0" must correspond to your network interface (see above).
  • address, netmask, [..], dns-nameservers:
    Also self-explanatory... Be aware that "broadcast" needs to end with ".255" for negotiation with the router. These lines need to be according to your own (static) network settings. For DHCP see further below.
  • wpa-driver:
    That's the wpa-driver for your card ('wext' is a generic driver that is applicable when using "ndiswrapper"). Leave it as it is. Other drivers are:

hostap = Host AP driver (Intersil Prism2/2.5/3)
atmel = ATMEL AT76C5XXx (USB, PCMCIA)
wext = Linux wireless extensions (generic)
madwifi = Atheros
wired = wpa_supplicant wired Ethernet driver

  • wpa-ssid:
    Your network's ESSID (no quotes "").
  • wpa-ap-scan:
    "1" = Broadcast of ESSID.
    "2" = Hidden broadcast of ESSID.
  • wpa-proto:
    "RSN" = WPA(2)
    "WPA" = WPA(1)
  • wpa-pairwise & wpa-group:
    "CCMP" = AES cipher as part of WPA(2) standard.
    "TKIP" = TKIP cipher as part of WPA(1) standard.
  • wpa-key-mgmt:
    "WPA-PSK" = Authentication via pre-shared key (see 'key generation' further below).
    "WPA-EAP" = Authentication via enterprise authentication server.

 

VERY IMPORTANT ("WPA PSK Key Generation"):
Now convert your WPA ASCII password using the following command:

wpa_passphrase <your_essid> <your_ascii_key>

Resulting in an output like...

network={
ssid="test"
#psk="12345678"
psk=fe727aa8b64ac9b3f54c72432da14faed933ea511ecab1 5bbc6c52e7522f709a
}

Copy the "hex_key" (next to "psk=...") and replace <your_hex_key> in the "interfaces" files with it. Then save the file and restart your network:

sudo /etc/init.d/networking restart

You should be connecting to your router now... However, I figured that a restart is sometimes necessary so that's what I usually do (I know this sounds a bit clumsy - see post #2 for startup script).


*** Revoking read-permission from ‘others' ***

sudo chmod o=-r /etc/network/interfaces

 

*** Revoking read-permission from 'others' ***
*** Sample configuration WPA2 & DHCP, ESSID broadcast enabled ***

auto wlan0
iface wlan0 inet dhcp
wpa-driver wext
wpa-ssid
<your_essid>
wpa-ap-scan 1
wpa-proto RSN
wpa-pairwise CCMP
wpa-group CCMP
wpa-key-mgmt WPA-PSK
wpa-psk
<your_hex_key> [IMPORTANT: See "WPA-PSK key generation"]

 

*** Sample configuration WPA2 & DHCP, ESSID broadcast enabled ***
*** Sample configuration WPA1 & DHCP, ESSID broadcast enabled ***

auto wlan0
iface wlan0 inet dhcp
wpa-driver wext
wpa-ssid
<your_essid>
wpa-ap-scan 1
wpa-proto WPA
wpa-pairwise TKIP
wpa-group TKIP
wpa-key-mgmt WPA-PSK
wpa-psk
<your_hex_key> [IMPORTANT: See "WPA-PSK key generation"]

 

*** Sample configuration WPA1 & DHCP, ESSID broadcast enabled ***
*** Sample configuration mixed mode (WPA1, WPA2) & DHCP, ESSID broadcast ***

auto wlan0
iface wlan0 inet dhcp
wpa-driver wext
wpa-ssid
<your_essid>
wpa-ap-scan 1
wpa-proto WPA RSN
wpa-pairwise TKIP CCMP
wpa-group TKIP CCMP
wpa-key-mgmt WPA-PSK
wpa-psk
<your_hex_key> [IMPORTANT: See "WPA-PSK key generation"]

 

*** Sample configuration mixed mode (WPA1, WPA2) & DHCP, ESSID broadcast*****
*** Sample conf. LEAP, WEP, DHCP, ESSID broadcast ***

auto wlan0
iface wlan0 inet dhcp
wpa-driver wext
wpa-ssid
<your_essid>
wpa-ap-scan 1
wpa-eap LEAP
wpa-key-mgmt IEEE8021X
wpa-identity
<your_user_name>
wpa-password
<your_password>

 

*** Sample conf. LEAP, WEP, DHCP, ESSID broadcast ***
*** Sample conf. PEAP, AES, DHCP, ESSID broadcast ***

auto wlan0
iface wlan0 inet dhcp
wpa-driver wext
wpa-ssid
<your_essid>
wpa-ap-scan 1
wpa-proto RSN
wpa-pairwise CCMP
wpa-group CCMP
wpa-eap PEAP
wpa-key-mgmt WPA-EAP
wpa-identity
<your_identity>
wpa-password
<your_password>

 

*** Sample conf. PEAP, AES, DHCP, ESSID broadcast ***
*** Sample conf. TTLS, WEP, DHCP, ESSID broadcast ***

auto wlan0
iface wlan0 inet dhcp
wpa-driver wext
wpa-ssid
<your_essid>
wpa-ap-scan 1
wpa-eap TTLS
wpa-key-mgmt IEEE8021X
wpa-anonymous-identity
<anonymous_identity>
wpa-identity
<your_identity>
wpa-password
<your_password>
wpa-phase2
auth=PAP [Also: CHAP, MSCHAP, MSCHAPV2]

 

*** Sample conf. TTLS, WEP, DHCP, ESSID broadcast ***
*** NOT TESTED: Sample conf. EAP-FAST, WPA1/WPA2, DHCP, ESSID broadcast ***

auto wlan0
iface wlan0 inet dhcp
wpa-driver wext
wpa-ssid
<your_essid>
wpa-ap-scan 1
wpa-proto RSN WPA
wpa-pairwise CCMP TKIP
wpa-group CCMP TKIP
wpa-key-mgmt WPA-EAP
wpa-eap FAST
wpa-identity
<your_user_name>
wpa-password
<your_password>
wpa-phase1
fast_provisioning=1
wpa-pac-file
/path/to/eap-pac-file

 

*** NOT TESTED: Sample conf. EAP-FAST, WPA1/WPA2, DHCP, ESSID broadcast ****
***Tested adapters***

1. Linksys WUSB54G V4 (ndiswrapper; wpa-driver = wext)
2. Intel IPW2200 (Linux driver; wpa-driver = wext)
3. Linksys WPC54G (ndiswrapper; wpa-driver = wext)
4. D-Link WNA-2330 (Linux driver; wpa-driver = madwifi)
5. Linksys WMP54G V2 (ndiswrapper; wpa-driver = wext)
6. D-Link WDA-2320 (Linux driver; wpa-driver = madwifi)
7. Netgear WPN311 (Linux driver; wpa-driver = wext)
8. Netgear WG511v2 (ndiswrapper; wpa-driver = wext)

 

*** Tested adapters ***
*** Post this if you are stumped ***

# route
# iwconfig
# sudo iwlist scan
# sudo lshw -C network
# sudo cat /etc/network/interfaces
# sudo ifdown -v
<your_interface>

# sudo ifup -v
<your_interface>

 

*** Post this if you are stumped ***
*** Other useful commands ***

# Ubuntu version & kernel >> uname -a
# Root file access >> alt F2 then 'gksudo nautilus' in cli
# Get IP Address or Renew >> sudo dhclient wlan0 [or whatever your wl adapter is]
# Get wireless info >> iwconfig
# Get AP info >> iwlist scan
# Get wireless info >> iwlist (lots of options will list)
# Routes if wlan0 working >> route
# DNS resolving via eth1 >> cat /etc/resolv.conf
# List devices/modules >> lspci, lsusb, lshw, lsmod
# Restart network >> sudo /etc/init.d/networking restart
# Boot messages >> dmesg
# Kill NWM >> sudo killall NetworkManager
# Events from your wl >> iwevent
# Restart all daemons >> sudo /etc/init.d/dbus restart
# Restart network >> sudo /etc/init.d/networking restart

 

Taken From:

Saturday, July 2, 2016

Raspberry Pi – Media Server for Streaming (via DLNA)

 

Here I’m going to quickly show you how to set up you Raspberry Pi as a Media Server for Streaming via DLNA which is a protocol suported in many TVs, Windows PCs (Windows Media Player) and Android Devices (App: Media House).

## Install Mini DLNA ##
sudo apt-get update
sudo apt-get install minidlna

## Mount The Media Disk ##
sudo mkdir /media/HD1
sudo mount /dev/sda1 /media/HD1

## Create The MiniDLNA DB Folder ##
sudo mkdir -p /opt/minidlna
sudo chmod 777 /opt/minidlna

## Edit The MiniDLNA Config File ##
sudo nano /etc/minidlan.conf

minidlna.conf - My Config
------------------------------------
media_dir=V,/media/HD1/Movies
#root_container=B,/media/HD1
network_interface=eth0
inotify=yes
friendly_name=HomePi
db_dir=/opt/minidlna

sudo service minidlna force-reload
sudo service minidlna restart


minidlna.conf – My Config Detailed
-------------------------------------------------------
#################################################
# Path to the directory you want scanned
# for media files.
#
# This option can be specified more than
# once if you want multiple directories
# scanned.
#
# If you want to restrict a media_dir to
# a specific content type, you can prepend
# the directory name with a letter representing
# the type (A, P or V),followed by a comma, as so:
#   * "A" for audio    (eg. media_dir=A,/media/HD1/music)
#   * "P" for pictures (eg. media_dir=P,/media/HD1/pictures)
#   * "V" for video    (eg. media_dir=V,/media/HD1/videos)
#   * "PV" for pictures and video
#  (eg. media_dir=PV,/media/HD1/digital_camera)
#################################################
media_dir=V,/media/HD1/Movies
NOTE: Use media_dir or root_container

#################################################
# Use a different container as the root
# of the directory tree presented to
# clients.
#
# The possible values are:
#   * "." - standard container
#   * "B" - "Browse Directory"
#   * "M" - "Music"
#   * "P" - "Pictures"
#   * "V" - "Video"
#   * Or, you can specify the ObjectID
#     of your desired root container
#     (eg. 1$F for Music/Playlists)
#
# If you specify "B" and the client
# device is audio-only then "Music/Folders"
# will be used as root.
###########################################
#root_container=B,/media/HD1

#################################################
# Network interface(s) to bind to
#(e.g. eth0), comma delimited.
#
# This option can be specified more than once.
#################################################
network_interface=eth0

#################################################
# Automatic discovery of new files
# in the media_dir directory.
#################################################
inotify=yes

#################################################
# Name that the DLNA server presents to clients.
# Defaults to "hostname: username".
#################################################
friendly_name=HomePi

#################################################
# Path to the directory that should
# hold the database and album art cache
#################################################
db_dir=/opt/minidlna
 
 
Now from you TV or other media device, like Android (use MediaHouse) you can stream
or download you media, with no config required on the clients, because these automatically
detect the DLNA server on the LAN.

Related Links

Monday, June 20, 2016

GRUB - Rescue BootLoader on a USB Flash Drive

My goal is to just have a GRUB bootloader (without a Linux instalation) on a USB Flash Drive to:

  • Boot OS with Bootloaders without entering the BIOS
  • Boot OS with Broken Boot Loaders
  • Boot Linux Live CDs

 

Installing the GRUB Boot Loader

Run a live CD like Ubuntu, a boot i without installing it.

First list your disks in order to identify you USB Flash Drive

    sudo fdisk -l

if you have trouble identifying you USB Flash Drive just run the command above without the USB Flash Drive, the insert it and list again, compare the outputs, and the extra disk is you USB Flash Drive.

My USB Flash Drive is “sdb1” (b=second HD | 1=first partition), now let’s make a folder to mount the usb flash drive (my Flash Drive was formated with the ext4 filesystem), and mount it:

    sudo mkdir /mnt/USB
    sudo mount /dev/sdb1 /mnt/USB

Now let’s just install the the bootloader

    sudo grub-install --force --removable --boot-directory=/mnt/USB/boot /dev/sdb

boot code goes on /dev/sdb and grub files on /mnt/USB/boot.

 

Set Up the Grub Configuration FIle

Now just create/edit the grub config file

    nano /mnt/USB/boot/grub/grub.cfg

and input the following configuration:

grub.cfg
_____________________________________________

set timeout=10
set default=0

menuentry "#### Boot OS with Bootloaders without entering the BIOS ####" {set root=(hd1)}

menuentry "HD0 (First HD – This USB Flash Drive)" {
set root=(hd0)
chainloader +1
}

menuentry "HD1 (Second HD)" {
set root=(hd1)
chainloader +1
}

menuentry "HD2 (Third HD)" {
set root=(hd2)
chainloader +1
}

menuentry "HD3 (Fourth HD)" {
set root=(hd3)
chainloader +1
}

 

menuentry "#### Boot OS with Broken Boot Loaders ####" {set root=(hd1)}

menuentry "Ubuntu 16.04 (HD1 - First HD)"  {

    insmod part_msdos
    insmod ext2
    set root=(hd1,msdos1)

    echo 'Loading Linux Kernel...'
    linux /boot/vmlinuz-4.4.0-24-generic root=/dev/sda1
       
    echo 'Loading Initial Ramdisk ...'
    initrd /boot/initrd.img-4.4.0-24-generic
    boot
}

menuentry "Windows XP/7/10 (HD1 - First HD)"  {

    insmod part_msdos
    insmod ntfs
    set root=(hd1,msdos1)

    drivemap -s (hd0) ${root}
    chainloader +1
}

 

menuentry "#### Boot Linux Live CDs ####" {set root=(hd1)}
   
menuentry "Ubuntu 16.04 ISO (On This USB PEN Drive)" {

    set isofile="/ubuntu-16.04-desktop-amd64.iso"
    loopback loop (hd0,msdos1)$isofile
    linux (loop)/casper/vmlinuz.efi boot=casper iso-scan/filename=$isofile noprompt noeject
    initrd (loop)/casper/initrd.lz
}

This is what it looks like:

image

You migth need to adjust some things if you have more disks, partitions or diferent linux distro. To make it easyer I have put the things you migth need to change in bold.

The above config was for the following setup

  • One USB Flash Drive (with Grub Installed)
    • hd0,msdos1 - First HD | First Partition – MBR Geometry
    • This is was my USB Flash Drive
  • One Hard Drive for OS
    • hd1,msdos1 – Second HD | First Partition – MBR Geometry
    • This is the Disk with the OS

If you have trouble Identifying you disks and partion you can press ‘c’, on the grub menu, to get the GRUB command line and run “ls” :

image

this was very hepfull, specially identifying the the name for the MBR partitions aka “msdos” .

Related Links

Monday, May 30, 2016

Linux – Howto Boot an ISO from GRUB

Linux’s GRUB2 boot loader can boot Linux ISO files directly from your hard drive. Boot Linux live CDs or even install Linux on another hard drive partition without burning it to disc or booting from a USB drive.

We performed this process on Ubuntu 14.04 — Ubuntu and Ubuntu-based Linux distributions have good support for this. Other Linux distributions should work similarly.

This trick requires you have a Linux system installed on your hard drive. Your computer must be using the GRUB2 boot loader, which is a standard boot loader on most Linux systems. Sorry, you can’t boot a Linux ISO file directly from a Windows system using the Windows boot loader.

Download the ISO files you want to use and store them on your Linux partition. GRUB2 should support most Linux systems. if you want to use them in a live environment without installing them to your hard drive, be sure to download the “live CD” versions of each Linux ISO. Many Linux-based bootable utility discs should also work.

 

Check the Contents of the ISO File

You may need to look inside the ISO file to determine exactly where specific files are. For example, you can do this by opening the ISO file with the Archive Manager/File Roller graphical application that comes with Ubuntu and other GNOME-based desktop environments. In the Nautilus file manager, right-click the ISO file and select Open with Archive Manager.

Locate the kernel file and the initrd image. If you’re using a Ubuntu ISO file, you’ll find these files inside the casper folder — the vmlinuz file is the Linux kernel and the initrd file is the initrd image. You’ll need to know their location inside the ISO file later.

clip_image001

 

Determine the Hard Drive Partition’s Path

GRUB uses a different “device name” scheme than Linux does. On a Linux system, /dev/sda1 is the first partition on the first hard disk — a means the first hard disk and 1 means its first partition. In GRUB, (hd0,1) is equivalent to /dev/sda0. The 0 means the first hard disk, while the1 means the first partition on it. In other words, in a GRUB device name, the disk numbers start counting at 0 and the partition num6ers start counting at 1 — yes, it’s unnecessarily confusing. For example, (hd3,6) refers to the sixth partition on the fourth hard disk.

You can use the fdisk -l command to view this information. On Ubuntu, open a Terminal and run the following command:

sudo fdisk -l

You’ll see a list of Linux device paths, which you can convert to GRUB device names on your own. For example, below we can see the system partition is /dev/sda1 — so that’s (hd0,1) for GRUB.

clip_image002

 

Create the GRUB2 Boot Entry

The easiest way to add a custom boot entry is to edit the /etc/grub.d/40_custom script. This file is designed for user-added custom boot entries. After editing the file, the contents of your /etc/defaults/grub file and the /etc/grub.d/ scripts will be combined to create a /boot/grub/grub.cfg file — you shouldn’t edit this file by hand. It’s designed to be automatically generated from settings you specify in other files.

You’ll need to open the /etc/grub.d/40_custom file for editing with root privileges. On Ubuntu, you can do this by opening a Terminal window and running the following command:

sudo gedit /etc/grub.d/40_custom

Feel free to open the file in your favorite text editor. For example, you could replace “gedit” with “nano” in the command to open the file in the Nano text editor.

Unless you’ve added other custom boot entries, you should see a mostly empty file. You’ll need to add one or more ISO-booting sections to the file below the commented lines.

clip_image003

Here’s how you can boot an Ubuntu or Ubuntu-based distribution from an ISO file. We tested this with Ubuntu 14.04:

menuentry “Ubuntu 14.04 ISO” {
set isofile=”/home/name/Downloads/ubuntu-14.04.1-desktop-amd64.iso
loopback loop (hd0,1)$isofile
linux (loop)/casper/vmlinuz.efi boot=casper iso-scan/filename=${isofile} quiet splash
initrd (loop)/casper/initrd.lz
}

Customize the boot entry to contain your desiredmenu entry name, the correct path to the ISO file on your computer, and the device name of the hard disk and partition containing the ISO file. If the vmlinuz and initrd files have different names or paths, be sure to specify the correct path to those files, too.

(If you have a separate /home/ partition, omit the /home bit, like so: set isofile=”/name/Downloads/${isoname}”).

Important Note: Different Linux distributions require different boot entries with different boot options. The GRUB Live ISO Multiboot project offers a variety of menu entries for different Linux distributions. You should be able to adapt these example menu entries for the ISO file you want to boot. You can also just perform a web search for the name and release number of the Linux distribution you want to boot along with “boot from ISO in GRUB” to find more information.

clip_image004

If you want to add more ISO boot options, add additional sections to the file.

Save the file when you’re done. Return to a Terminal window and run the following command:

sudo update-grub

clip_image005

The next time you boot your computer, you’ll see the ISO boot entry and you can choose it to boot the ISO file. You may have to hold Shift while booting to see the GRUB menu.

If you see an error message or a black screen when you attempt to boot the ISO file, you misconfigured the boot entry somehow. Even if you got the ISO file path and device name right, the paths to the vmlinuz and intird files on the ISO file may not be correct or the Linux system you’re booting may require different options.

Taken From: http://www.howtogeek.com/196933/how-to-boot-linux-iso-images-directly-from-your-hard-drive/

Monday, March 28, 2016

Linux - Parted the CLI Disk Management Tool

Parted is a famous command line tool that allows you to easily manage hard disk partitions. It can help you add, delete, shrink and extend disk partitions along with the file systems located on them. Parted has gone a long way from when it first came out. Some of it’s functions have been removed, others have been added.

In this tutorial you will learn the basics of parted and we will show you some practical examples. If you don’t have any previous experience with parted, please be aware that parted writes the changes immediately to your disk, so be careful if you try to modify your disk partitions.

If you plan on testing parted, the better option would be to simply use a virtual machine or old computer/laptop without any valuable information on it. To make modifications on a disk partition it must not be in use. If you need to work on primary partition, you may boot into rescue mode.

Note: You will need to have root access to the machine you will be working on in order to use parted.

 

How to Install Parted on Linux

On many Linux distributions, parted comes pre-installed. If it is not included in your distro, you can install it with:

$ sudo apt-get install parted        [On Debian/Ubuntu systems]
# yum install parted                    [On RHEL/CentOS and Fedora]
# dnf install parted                      [On Fedora 22+ versions]

Once you have make sure that parted is installed, you can proceed further to check out some real world examples of parted command in the rest of this article.

 

1. Check Parted Version

Run the following command, you see message similar to the one shown on the image below. Don’t worry if your parted version is different. Unless specified otherwise, parted will use your primary drive, which in most cases will be/dev/sda.

$ parted

clip_image001

Check Parted Command Version

If you want to exit parted, simply type:

$ quit

 

2. List Linux Disk Partitions

Now that parted is started, let’s list the partitions of the selected hard disk. As mentioned earlier, parted chooses your first drive by default. To see the disk partitions run print.

(parted) print

clip_image002

Check Linux Partitions

When running print, it will also display the hard disk information and model. Here is example from a real hard disk (not virtual as shown on the image above) :

(parted) print

Model: ATA TOSHIBA MQ01ACF0 (scsi)
Disk /dev/sda: 320GB
Sector size (logical/physical): 512B/4096B
Partition Table: msdos

Number  Start   End    Size   Type      File system  Flags

1      1049kB  256MB  255MB  primary   ext2         boot
2      257MB   320GB  320GB  extended
5      257MB   320GB  320GB  logical                    lvm

sector size and partition table.

 

3. List or Switch to Different Disk

If you have more than one hard disk, you can easily switch between disks, by using the “select” command. In the example below, I will switch from /dev/sda to/dev/sdb which is a secondary drive on my system.

To easily switch between disks you can use:

(parted) select /dev/sdX

clip_image003

Select Different Disk

Change "X" with the letter of the disk to which you wish to switch.

 

4. Create Primary or Logical Partition in Linux

Parted can be used to create primary and logical disk partitions. In this example, I will show you how to create primary partition, but the steps are the same for logical partitions.

To create new partition, parted uses “mkpart“. You can give it additional parameters like "primary" or "logical" depending on the partition type that you wish to create.

Before you start creating partitions, it’s important to make sure that you are using (you have selected) the right disk.

Start by using print:

(parted) print

clip_image004

Show Current Linux Disk

As shown on the above image, we are using a virtual drive of 34 GB. First we will give the new disk a label and then create a partition and set a file system on it.

Now the first step is to give the new disk a label name with:

(parted) mklabel msdos

Now create the new partition with  mkpart. The listed units are in megabytes (MB). We will create a 10 GB partition starting from 1 to 10000:

(parted) mkpart

Partition type?  primary/extended? primary
File system type?  [ext2]?
Start? 1
End? 10000
(parted) print
Model: ATA VBOX HARDDISK (scsi)
Disk /dev/sdb: 34.4GB
Sector size (logical/physical): 512B/512B
Partition Table: msdos
Disk Flags:
Number  Start   End     Size    Type     File system  Flags
1      1049kB  10.0GB  9999MB  primary   ext2         lba

clip_image005

Create Primary or Logical Linux Partitions

Next,  exit parted with "quit" command. We will format our new partition in ext4 file system using mkfs. To make this happen run the following command:

# mkfs.ext4 /dev/sdb1

Note: It’s important to select the right disk and partition when executing the above command!

Now let’s verify our results, by printing the partition table on our secondary disk. Under file system column, you should see ext4 or the file system type that you have decided to use for your partition:

clip_image006

Verify Disk Partition Filesystem

 

5. Resize Linux Disk Partition

Parted includes multiple useful functions and one of them is "resizepart". As you have probably figured this out by now, "resizepart" helps you resize a partition.

In the example below, you will see how to resize an existing partition. For the purpose of this example, we will be using the earlier created partition.

First you will need to know the number of the partition that you will be resizing. This can be easily found by using "print":

(parted) print

clip_image007

Find Linux Partition Number

In our example, the partition number is "1". Now run the resizepart command:

(parted) resizepart

You will be asked for the number of the partition that you will resize. Enter it’s number. After that, you will be asked to set the new ending point for this partition. Remember that by default the units are in MB. In our example, we have set the new partition size to 15 GB:

(parted) resizepart
Partition number? 1
End?  [10.0GB]? 15000
Now verify the results with "print":
(parted) print

clip_image008

Verify Linux Resize Partition

 

6. Delete Linux Partition

The next thing you will learn is how to delete a partition from your hard drive. To do this, you will need to use the "rm" command within parted. To delete a disk partition you will need to know it’s number.

As mentioned earlier, you can easily obtain this number by using "print". In our example, we will delete the partition with number 1 from our secondary drive/dev/sdb1:

(parted) rm 1

Verify the results by printing the partitions table:

clip_image009

Delete a Linux Partition

 

7. Rescue Linux Disk Partition

Parted supports a “rescue" utility that helps you recover a lost partition between a starting and ending point. If a partition is found within that range, it will attempt to restore it.

Here is an example:

(parted) rescue
Start? 1
End? 15000
(parted) print
Model: Unknown (unknown)
Disk /dev/sdb1: 15.0GB
Sector size (logical/physical): 512B/512B
Partition Table: loop
Disk Flags:

Number Start End Size File system Flags
1 0.00B 15.0GB 15.0GB ext4

 

8 Change Linux Partition Flag

Using parted, you can change the state of a flag for disk partitions. The supported flags are:

  • boot
  • root
  • swap
  • hidden
  • raid
  • lvm
  • lba
  • legacy_boot
  • irst
  • esp
  • palo

The states can be either "on" or "off". To change a flag simply run "set"command within parted:

(parted) set 2 lba on

The above command sets lba flag to on for second partition. Verify the results with print:

clip_image010

Change Partition Flag

 

Conclusion

Parted is a useful and powerful utility that can help you manage your disk partitions in Linux systems. As always, when working with disk partitions you need to be extra careful. It is strongly recommend to go through parted man pages to learn how you can customize it’s output and find more information about its capabilities.

If you have any questions or comments, please do not hesitate to use the comment section below.

 

Taken From: http://www.tecmint.com/parted-command-to-create-resize-rescue-linux-disk-partitions/

Sunday, February 14, 2016

Linux - GRE Tunnel

How to create a GRE tunnel on Linux

GRE tunnels are IP-over-IP tunnels which can encapsulate IPv4/IPv6 and unicast/multicast traffic. To create a GRE tunnel on Linux, you need ip_gre kernel module, which is GRE over IPv4 tunneling driver.

So first make sure that ip_gre is loaded.

  $ sudo modprobe ip_gre
  $ lsmod | grep gre

    ip_gre 22432 0
    gre 12989 1 ip_gre

Here, we assume that you want to create a GRE tunnel between two interfaces with the following IP addresses.

    - Host A: 192.168.233.204
    - Host B: 172.168.10.25

   
On host A, run the following command.

  $ sudo ip tunnel add gre0 mode gre remote 172.168.10.25 local 192.168.233.204 ttl 255
  $ sudo ip link set gre0 up
  $ sudo ip addr add 10.10.10.1/24 dev gre0

In the above, we create a GRE-type tunnel device called gre0, and set its remote address to 172.168.10.25. Tunneling packets will be originating from 192.168.233.204 (local IP address), and their TTL field will be set to 255. The tunnel device is assigned IP address 10.10.10.1 with netmask 255.255.255.0.

Now verify that route for the GRE tunnel is set up correctly:

  $ ip route show
    default via 135.112.29.1 dev eth0 proto static
    10.10.10.0/24 dev gre0 proto kernel scope link src 10.10.10.1

On host B, run similar commands as follows.

  $ sudo ip tunnel add gre0 mode gre remote 192.168.233.204 local 172.168.10.25 ttl 255
  $ sudo ip link set gre0 up
  $ sudo ip addr add 10.10.10.2/24 dev gre0

At this point, a GRE tunnel should be established between host A and host B.

To verify that, from one tunneling end point, ping the other end point.

  $ ping 10.10.10.2 (from host A)

    PING 10.10.10.2 (10.10.10.2) 56(84) bytes of data.
    64 bytes from 10.10.10.2: icmp_req=1 ttl=64 time=0.619 ms
    64 bytes from 10.10.10.2: icmp_req=2 ttl=64 time=0.496 ms
    64 bytes from 10.10.10.2: icmp_req=3 ttl=64 time=0.587 ms

If you want to tear down the GRE tunnel, run the following command from either end.

  $ sudo ip link set gre0 down
  $ sudo ip tunnel del gre0

Taken From: http://ask.xmodulo.com/create-gre-tunnel-linux.html

Monday, November 23, 2015

Cisco - Linux Commands on IOS


Today we’re going to go over a little known shell in IOS that gives us some bash like functionality! It is called IOS.sh

We can enable this little known functionality with the terminal shell command, like the rest of the terminal commands this only enables IOS.sh for the current terminal session.

R1#terminal shell

If you want to have the shell enabled permanently with the following global command

R1(config)#shell processing full

R1#show terminal | in Shell
Shell: enabled
Shell trace: off

Now IOS.sh is enabled! Awesome! But what does it do?
The simple answer is it makes IOS more like a Linux shell, it allows us to create variables, make loops, and use some linux utilities like grep or wc on the shell.

 

Using GREP

One of the neatest features of IOS.sh is the ability to use the grep utility to filter output. Let’s start by looking at the manpage for Grep, yes there are manpages!

R1#man grep
NAME
grep - get regular expression

SYNOPSIS
    grep [OPTIONS] <Regular Expression> [<file>...]

DESCRIPTION
    The 'grep' command matches lines in the given files
    with the supplied regular expression, and prints matching
    lines. There are lots of options
   
    -b              - match everything in a file after pattern
    -c              - print a count of lines instead of matched lines
    -e <pat>    - use &lt;pat&gt; as the pattern (it may have a leading minus)
    -h             - do not print filename for each match (default)
    -H             - print filename for each match
    -i              - ignore case
    -l              - print only files with match
    -L             - print only files without match
    -m            - match everything in a matching mode
    -n             - print line numbers along with matches
    -q             - quiet, only set status
    -s             - supress printing errors
    -u             - match everything in a file until pattern
    -v             - invert match, print non-matching lines

Part of the power of this command is because you can be more flexible than the standard include pipe command because you can do things like combine include and exclude like statements in the same line.

R1#show ip route | grep (150) | grep (10003)    
O        150.1.2.2 [110/10003] via 155.1.146.4, 15:51:41, GigabitEthernet1.146
O        150.1.3.3 [110/10003] via 155.1.146.4, 15:51:41, GigabitEthernet1.146
O IA     150.1.22.22 [110/10003] via 155.1.146.4, 1d11h, GigabitEthernet1.146

R1#show ip route | grep (150) | grep -v (10003)
      150.1.0.0/32 is subnetted, 11 subnets
C        150.1.1.1 is directly connected, Loopback0
O        150.1.4.4 [110/2] via 155.1.146.4, 15:51:57, GigabitEthernet1.146
O        150.1.5.5 [110/3] via 155.1.146.4, 15:51:57, GigabitEthernet1.146
O        150.1.6.6 [110/2] via 155.1.146.6, 1d12h, GigabitEthernet1.146
O IA     150.1.7.7 [110/3] via 155.1.146.6, 1d12h, GigabitEthernet1.146
O IA     150.1.8.8 [110/4] via 155.1.146.4, 15:52:07, GigabitEthernet1.146
O IA     150.1.9.9 [110/4] via 155.1.146.6, 1d12h, GigabitEthernet1.146
O IA     150.1.10.10 [110/5] via 155.1.146.4, 15:52:07, GigabitEthernet1.146

R1#show ip route | grep 150 | grep -v 10003 | grep 6\.6
O 150.1.6.6 [110/2] via 155.1.146.6, 00:35:18, GigabitEthernet1.146
O IA 150.1.7.7 [110/3] via 155.1.146.6, 00:35:08, GigabitEthernet1.146
O IA 150.1.9.9 [110/4] via 155.1.146.6, 00:35:08, GigabitEthernet1.146

 

WC

WC can be used to count the number of things in the output.

R1#man wc
NAME
    wc

SYNOPSIS
    wc [OPTION]... [FILE]...

DESCRIPTION
    Print newline, word, and byte counts for each FILE, and a total line if
    more than one FILE is specified. Read pipe input if no files are given
    -c print the byte counts
    -m print the character counts
    -l print the newline counts
    -L print the length of the longest line
    -w print the word counts

R1#show run | wc -l
216

 

Heads and Tails

These commands can be used to show the top x or bottom x lines of output, this can be handy with trying to see the latest logs.

R1#man head
NAME
    head - print the first lines in the input

SYNOPSIS
    head [<n>]

DESCRIPTION
    The 'head' program will print the first lines in
    its input. If given a numeric argument, it will
    print that many lines. The default number of lines
    is 10.


R1#man tail
NAME
    tail - print the last lines in the input

SYNOPSIS
    tail [<n>]

DESCRIPTION
    The 'tail' program will print the last lines
    in its input. If given a numeric argument, it
    will print that many lines. The default number
    of lines is 10.
    R1#

R1#show run | head 10
Building configuration...

Current configuration : 2844 bytes
!
! Last configuration change at 18:14:38 UTC Tue Nov 17 2015
!
version 15.5
no service timestamps debug uptime
no service timestamps log uptime
no platform punt-keepalive disable-kernel-core

R1#show run | tail 10
exec-timeout 0 0
privilege level 15
logging synchronous
stopbits 1
line vty 0 4
privilege level 15
no login
!
!
end

 

CAT

Ok fine, we can use the cat command to view text files on the Cisco device.

R1#man cat
NAME
    cat - write files or standard input to output

SYNOPSIS
    cat [<file>...]

DESCRIPTION
    The cat command writes whatever it sees to its output

    R1#copy running-config flash:cat.test
    Destination filename [cat.test]?
    2844 bytes copied in 0.463 secs (6143 bytes/sec)


R1#cat flash:cat.test
!
! Last configuration change at 18:14:38 UTC Tue Nov 17 2015
!
version 15.5
no service timestamps debug uptime
no service timestamps log uptime
no platform punt-keepalive disable-kernel-core
platform console serial

 

Variables

Lets start with making variables by first looking at the variables

R1#man variables
NAME
    variables - describe the usage of variables

DESCRIPTION
    Variables can be used in any context except single quotes. Variables
    can either be named, or numbered parameters to functions. Setting a
    named variable can be accomplished using an assignment statement.
    Assignment statments have a specific form, which is that the name of
    the variable must be immediately followed by an '=' sign. There can be
    no whitespace between the name and the '=':

    router> MYVAR='abc'

    The right side of the assignment is any string, but can also be the
    result of execution of a backquote expression, or the evaluation of a
    variable expansion.

    Variables may be used anywhere in subsequent input lines. One could,
    for example, create a shortcut for an interface name, and use it in
    config mode, or create a variable containing a number, and increment
    its value using arithmetic expression syntax (see man expressions).

    The main issue here is that the variable introduction character may
    conflict with existing usages, and so must be escaped in situations
    where a compatibility issue may arise. Please see man compatibility
    for more information.

To make a variable you simply have to enter VariableName=VariableValue

R1#VAR1=Value1
R1#VAR2=Value2

We can view the contents with the echo command

R1#echo $VAR1 $VAR2
Value1 Value2

You can also use variables in your commands

R2#var1=150.1.4.4

R2#ping $var1
Type escape sequence to abort.
Sending 5, 100-byte ICMP Echos to 150.1.4.4, timeout is 2 seconds:
!!!!!
Success rate is 100 percent (5/5), round-trip min/avg/max = 71/100/167 ms

 

Conditions and Loops

Following comparison operators can be used for working with integer values:
Operators   Characteristics
-eq               ==
-ne               !=
-lt                 <
-gt                >
-ge               >=
-le                =<

For working with files following conditions are available:

Operator    Characteristics
-a  or –e      True if file exists
-d               True if file exist and it is a directory
-f                True if file exists and is a regular file
-r                True if file exists and is readable
-s               True if file exists and has a size greater than zero
-w               True if file exists and is executable
-nt              Test if file1 is newer than file2. The modification date on the file is used for this comparison
-ot              Test if file1 is older than file2

Loops are very powerful (and dangerous if you don’t terminate them correctly) tools that allow you to carry out complex tasks.

R1#for x in 1 2 3 4 5 6 7 8 9
do..done>do
do..done>;ping 150.1.$x.$x
do..done>done

Type escape sequence to abort.
Sending 5, 100-byte ICMP Echos to 150.1.1.1, timeout is 2 seconds:
!!!!!
Success rate is 100 percent (5/5), round-trip min/avg/max = 5/13/39 ms
Type escape sequence to abort.
Sending 5, 100-byte ICMP Echos to 150.1.2.2, timeout is 2 seconds:
!!!!!
Success rate is 100 percent (5/5), round-trip min/avg/max = 64/140/228 ms
Type escape sequence to abort.
Sending 5, 100-byte ICMP Echos to 150.1.3.3, timeout is 2 seconds:
!!!!!
Success rate is 100 percent (5/5), round-trip min/avg/max = 52/91/186 ms
Type escape sequence to abort.
Sending 5, 100-byte ICMP Echos to 150.1.4.4, timeout is 2 seconds:
!!!!!
Success rate is 100 percent (5/5), round-trip min/avg/max = 31/61/117 ms
Type escape sequence to abort.
Sending 5, 100-byte ICMP Echos to 150.1.5.5, timeout is 2 seconds:
!!!!!
Success rate is 100 percent (5/5), round-trip min/avg/max = 42/73/117 ms
Type escape sequence to abort.
Sending 5, 100-byte ICMP Echos to 150.1.6.6, timeout is 2 seconds:
!!!!!
Success rate is 100 percent (5/5), round-trip min/avg/max = 34/51/93 ms
Type escape sequence to abort.
Sending 5, 100-byte ICMP Echos to 150.1.7.7, timeout is 2 seconds:
!!!!!
Success rate is 100 percent (5/5), round-trip min/avg/max = 53/73/97 ms
Type escape sequence to abort.
Sending 5, 100-byte ICMP Echos to 150.1.8.8, timeout is 2 seconds:
!!!!!
Success rate is 100 percent (5/5), round-trip min/avg/max = 67/98/116 ms
Type escape sequence to abort.
Sending 5, 100-byte ICMP Echos to 150.1.9.9, timeout is 2 seconds:
!!!!!
Success rate is 100 percent (5/5), round-trip min/avg/max = 78/98/122 ms

 

Functions

Lastly for this blog entry, you can define functions to make repeated tasks easier.

R1#function test-r1() {
{..} >ping 150.1.4.4
{..} >}
R1#

R4#test-r1
Type escape sequence to abort.
Sending 5, 100-byte ICMP Echos to 150.1.5.5, timeout is 2 seconds:
!!!!!
Success rate is 100 percent (5/5), round-trip min/avg/max = 26/39/63 ms


You can see the functions defined on the system with show shell function

R4#show shell functions
User defined functions:

Function namespace: DEFAULT
    R1#function test-r1()
    {
     ping 150.1.5.5
    }

 

Taken From: