Showing posts with label unix. Show all posts
Showing posts with label unix. Show all posts

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:

Wednesday, July 23, 2008

Configure a Linux DHCP Server

Configure a DHCP Server


Introduction

Normally if you have a cable modem or DSL, you get your home PC's IP address dynamically assigned from your service provider. If you install a home cable/DSL router between your modem and home network, your PC will most likely get its IP address at boot time from the home router instead. You can choose to disable the DHCP server feature on your home router and set up a Linux box as the DHCP server.

This chapter covers only the configuration of a DHCP server that provides IP addresses. The configuration of a Linux DHCP client that gets its IP address from a DHCP server is covered in Chapter 3, "Linux Networking", on Linux Networking.
Download and Install the DHCP Package

Most RedHat and Fedora Linux software products are available in the RPM format. Downloading and installing RPMs aren't hard. If you need a refresher, Chapter 6, "Installing Linux Software", covers how to do this in detail.

When searching for the file, remember that the DHCP server RPM's filename usually starts with the word dhcp followed by a version number like this: dhcp-3.0.1rc14-1.i386.rpm.

Debian Note: With Debian / Ubuntu the package name may include a version number. Use the dpkg --list | grep dhcp command to get a list of all your dhcp packages and use the output to infer what the DHCP server package name would be. In this case we can guess that the package name should be dhcp3-server. If you need a DEB package installation refresher you can take a look at Chapter 6, "Installing Linux Software".

root@u-bigboy:/tmp# dpkg --list | grep dhcp
ii dhcp3-client 3.0.3-6ubuntu7 DHCP Client
ii dhcp3-common 3.0.3-6ubuntu7 Files used by all the dhcp3* packages
root@u-bigboy:/tmp#

The /etc/dhcpd.conf File

When DHCP starts, it reads the file /etc/dhcpd.conf. It uses the commands here to configure your network. The standard DHCP RPM package doesn't automatically install a /etc/dhcpd.conf file, but you can find a sample copy of dhcpd.conf in the following directory which you can always use as a guide.

/usr/share/doc/dhcp-/dhcpd.conf.sample

You have to copy the sample dhcpd.conf file to the /etc directory and then you'll have to edit it. Here is the command to do the copying for the version 3.0p11 RPM file:

[root@bigboy tmp]# cp /usr/share/doc/dhcp-3.0pl1/dhcpd.conf.sample /etc/dhcpd.conf

Debian Note: With Debian / Ubuntu the configuration file name is /etc/dhcp*/dhcpd.conf and has the same syntax as that used by Redhat / Fedora.

Here is a quick explanation of the dhcpd.conf file: Most importantly, there must be a subnet section for each interface on your Linux box.



ddns-update-style interim
ignore client-updates

subnet 192.168.1.0 netmask 255.255.255.0 {

# The range of IP addresses the server
# will issue to DHCP enabled PC clients
# booting up on the network

range 192.168.1.201 192.168.1.220;

# Set the amount of time in seconds that
# a client may keep the IP address

default-lease-time 86400;
max-lease-time 86400;

# Set the default gateway to be used by
# the PC clients

option routers 192.168.1.1;
# Don't forward DHCP requests from this
# NIC interface to any other NIC
# interfaces

option ip-forwarding off;

# Set the broadcast address and subnet mask
# to be used by the DHCP clients

option broadcast-address 192.168.1.255;
option subnet-mask 255.255.255.0;

# Set the DNS server to be used by the
# DHCP clients

option domain-name-servers 192.168.1.100;

# Set the NTP server to be used by the
# DHCP clients

option nntp-server 192.168.1.100;

# If you specify a WINS server for your Windows clients,
# you need to include the following option in the dhcpd.conf file:

option netbios-name-servers 192.168.1.100;

# You can also assign specific IP addresses based on the clients'
# ethernet MAC address as follows (Host's name is "laser-printer":

host laser-printer {
hardware ethernet 08:00:2b:4c:59:23;
fixed-address 192.168.1.222;
}
}
#
# List an unused interface here
#
subnet 192.168.2.0 netmask 255.255.255.0 {
}

There are many more options statements you can use to configure DHCP. These include telling the DHCP clients where to go for services such as finger and IRC. Check the dhcp-options man page after you do your install:

[root@bigboy tmp]# man dhcp-options

Note: The host statement seen in the sample dhcpd.conf file can be very useful. Some devices such as network printers default to getting their IP addresses using DHCP, but users need to access them by a fixed IP address to print their documents. This statement can be used to always provide specific IP address to DHCP queries from a predefined a NIC MAC address. This can help to reduce systems administration overhead.



How to Get DHCP Started

To get DHCP started:

1) Some older Fedora/RedHat versions of the DHCP server will fail unless there is an existing dhcpd.leases file. Use the command touch /var/lib/dhcp/dhcpd.leases to create the file if it does not exist.

[root@bigboy tmp]# touch /var/lib/dhcp/dhcpd.leases

2) Use the chkconfig command to get DHCP configured to start at boot:

[root@bigboy tmp]# chkconfig dhcpd on

With Debian / Ubuntu the equivalent command for the dhcp3-server package would be:

root@u-bigboy:/tmp# sysv-rc-conf dhcp3-server on

3) Use the service command to instruct the /etc/init.d/dhcpd script to start/stop/restart DHCP after booting

[root@bigboy tmp]# service dhcpd start
[root@bigboy tmp]# service dhcpd stop
[root@bigboy tmp]# service dhcpd restart

With Debian / Ubuntu the equivalent commands would be:

root@u-bigboy:/tmp# /etc/init.d/dhcp*-server start
root@u-bigboy:/tmp# /etc/init.d/dhcp*-server stop
root@u-bigboy:/tmp# /etc/init.d/dhcp*-server restart

4) Remember to restart the DHCP process every time you make a change to the conf file for the changes to take effect on the running process. You also can test whether the DHCP process is running with the following command; you should get a response of plain old process ID numbers:

[root@bigboy tmp]# pgrep dhcpd

5) Finally, always remember to set your PC to get its IP address via DHCP.




DHCP Servers with Multiple NICs (Network Interfaces)

When a DHCP configured PC boots, it requests its IP address from the DHCP server. It does this by sending a standardized DHCP broadcast request packet to the DHCP server with a source IP address of 255.255.255.255.

If your DHCP server has more than one interface, you have to add a route for this 255.255.255.255 address so that it knows the interface on which to send the reply; if not, it sends it to the default gateway. (In both of the next two examples, we assume that DHCP requests will be coming in on interface eth0).

Note: More information on adding Linux routes and routing may be found in Chapter 3, "Linux Networking".

Note: You can't run your DHCP sever on multiple interfaces because you can only have one route to network 255.255.255.255. If you try to do it, you'll discover that DHCP serving working on only one interface.



Temporary Solution

You can temporarily add a route to 255.255.255.255 using the route add command as seen below.

[root@bigboy tmp]# route add -host 255.255.255.255 dev eth0

If you want this routing state to be maintained after a reboot, then use the permanent solution that's discussed next.


Permanent Solution

The new Fedora Linux method of adding static routes doesn't seem to support sending traffic out an interface that's not destined for a specific gateway IP address. The DHCP packet destined for address 255.255.255.255 isn't intended to be relayed to a gateway, but it should be sent using the MAC address of the DHCP client in the Ethernet frame.

You have one of two choices. Add the route add command to your /etc/rc.local script, or add an entry like this to your /etc/sysconfig/static-routes file.

#
# File /etc/sysconfig/static-routes
#
eth0 host 255.255.255.255

Note: The /etc/sysconfig/static-routes file is a deprecated feature and Fedora support for it will eventually be removed.

Now that you have configured your server, it's time to take a look at the DHCP clients.



Configuring Linux Clients to Use DHCP

A Linux NIC interface can be configured to obtain its IP address using DHCP with the examples outlined in , "Linux Networking". Please refer to this chapter if you need a quick refresher on how to configure a Linux DHCP client.



Configuring Windows Clients to Use DHCP

Fortunately Windows defaults to using DHCP for all its NIC cards so you don't have to worry about doing any reconfiguration.
Using a Single DHCP Server to Serve Multiple Networks

As stated before, DHCP clients send their requests for IP addresses to a broadcast address which is limited to the local LAN. This would imply that a DHCP server is required on each subnet. Not so. It is possible to configure routers to forward DHCP requests to a DHCP server many hops away. This is done by inserting the IP address of the router's interface on the DHCP client's network into the forwarded packet. To the DHCP server, the non-blank router IP address field takes precedence over the broadcast address and it uses this value to provide a DHCP address that is meaningful to the client. The DHCP server replies with a broadcast packet, and the router, which has kept track of the initial forwarded request, forwards it back towards the client. You can configure this feature on Cisco devices by using the ip helper-address command on all the interfaces on which DHCP clients reside. Here is a configuration sample that points to a DHCP server with the IP address 192.168.36.25:

interface FastEthernet 2/1
ip address 192.168.1.30 255.255.255.0
ip helper-address 192.168.36.25



Simple DHCP Troubleshooting

The most common problems with DHCP usually aren't related to the server; after the server is configured correctly there is no need to change any settings and it therefore runs reliably. The problems usually occur at the DHCP client's end for a variety of reasons. The following sections present simple troubleshooting steps that you can go through to ensure that DHCP is working correctly on your network.



DHCP Clients Obtaining 169.254.0.0 Addresses

Whenever Microsoft DHCP clients are unable to contact their DHCP server they default to selecting their own IP address from the 169.254.0.0 network until the DHCP server becomes available again. This is frequently referred to as Automatic Private IP Addressing (APIPA). Here are some steps you can go through to resolve the problem:

* Ensure that your DHCP server is configured correctly and use the pgrep command discussed earlier to make sure the DHCP process is running. Pay special attention to your 255.255.255.255 route, especially if your DHCP server has multiple interfaces.
* Give your DHCP client a static IP address from the same range that the DHCP server is supposed to provide. See whether you can ping the DHCP server. If you cannot, double-check your cabling and your NIC cards.
* DHCP uses the BOOTP protocol for its communication between the client and server. Make sure there are no firewalls blocking this traffic. DHCP servers expect requests on UDP port 67 and the DHCP clients expect responses on UDP port 68.



Conclusion

In most home-based networks, a DHCP server isn't necessary because the DSL router / firewall usually has DHCP capabilities, but it is an interesting project to try. Just remember to make sure that the range of IP addresses issued by all DHCP servers on a network doesn't overlap because it could possibly cause unexpected errors. You might want to disable the router/firewall's DHCP server capabilities to experiment with your new Linux server.

A DHCP server may be invaluable in an office environment where the time and cost of getting a network engineer to get the work done may make it simpler for Linux systems administrators to do it by themselves.

Creating a Linux DHCP server is straightforward and touches all the major themes in the previous chapters. Now it's time to try something harder, but before we do, we'll do a quick refresher on how to create the Linux users who'll be using many of the applications outlined in the rest of the book.


Taken From: "http://www.linuxhomenetworking.com/wiki/index.php/Quick_HOWTO_:_Ch08_:_Configuring_the_DHCP_Server"

Scp - Secure File Transfer (using ssh) Between UNIX Machines

Scp - Secure File Transfer (using ssh) between UNIX machines

Introduction and setup

Scp is a utility which allows files to be copied between machines. Scp is an updated version of an older utility named Rcp. It works the same, except that information (including the password used to log in) is encrypted. Also, if you have set up your .shosts file to allow you to ssh between machines without using a password as described in help on setting up your .shosts file, you will be able to scp files between machines without entering your password.
Usage of the Scp Command



The general form of the command is:

$ scp source-specification destination-specification

where source-specification indicates which file or directory is to be copied, and destination-specification indicates where the copied material is to be placed.

Either the source or the destination may be on the remote machine; i.e., you may copy files or directories into the account on the remote system OR copy them from the account on the remote system into the account you are logged into.



Example:

$ scp myfile xyz@sdcc7:myfile


To copy a directory, use the -r (recursive) option. Example:

$ scp -r mydir xyz@sdcc7:mydir



File Specification Formats

The format for the remote specification (source or destination) is:

user@machine:filename

where filename is the name (path) of the file or directory relative to the home (login) directory on the remote system.



The format for file specification on the local system is just:

filename


where fname is the name (path) relative to the current working directory on that system.
How scp is similar to cp

Just like the cp command, scp will overwrite an existing destination file. In addition, if the destination is an existing directory, the copied material will be placed beneath the directory.
Examples of remote file copies

1. While logged into xyz on sdcc7, copy file "letter" into file "application" in remote account abc on sdcc3:

$ scp letter abc@sdcc3:application


2. While logged into abc on sdcc3, copy file "foo" from remote account xyz on sdcc7 into filename "bar" in abc:

$ scp xyz@sdcc7:foo bar


3. While logged into account xyz on sdcc7, copy file "garfield" from subdirectory "comix" into filename "fatcat" in subdirectory "stuff" in remote account abc on sdcc3:

$ scp comix/garfield abc@sdcc3:stuff/fatcat


4. While logged into account abc on sdcc3, copy file "garfield" from subdirectory "comix" of account xyz on sdcc7 into subdirectory "stuff" with the same name "garfield":

$ scp xyz@sdcc7:comix/garfield stuff


5. While logged into account abc on sdcc3 , copy subdirectory "Section" into a new subdirectory called "Section" in existing subdirectory "Chapter" in account xyz on sdcc7:

$ scp -r Section xyz@sdcc7:Chapter


6. From account abc on sdcc3, copy entire account to ir123 on iacs5. This needs to be done from the parent directory of the account to be moved.

$ cd
$ cd ..
$ scp -r abc ir123@iacs5:abc



For more information about the scp (secure copy) command, check the on-line manual page for scp:

$ man scp