Archive for November, 2008

Sendmail Mods — Using Sendmail Correctly As an Internal Mail Handler

Modifying the sendmail.mc file for internal servers….

Listed below are the changes to a default RH 9 /etc/mail/sendmail.mc file required to operate a mail server behind a corectly configured Sendmail gateway server. These intranet servers can send mail to local users, users on the gateway server, and external Internet addresses. Why would you want to do this? There are many applications that utilize mail (sendmail) to send status information and data to you or other users. Some examples of such handy software include cron, apinger, and logwatch. However, you may not want to expose these internal machines to the outside world. The following details will allow you to use your gateway server as a relay.

Again, this is a specialized application of Sendmail. For a more general application, see our other page.

We will assume that your firewall will not let outsiders touch these internal servers on port 25. As such, several of the lock-down and anti-spam measures that were implemented on the gateway server will not be emplemented here.

You are NOT done once you change the .mc file. There are other changes that need to be done to the server.

Anything not listed for change/add/delete here should work fine with the default settings. I do NOT know if this will work for any other installation (e.g. Red Hat 7.2 or Mandrake). This worked with the default sendmail RPM shipped with RH 9 (and subsequent sendmail updates). I gleaned some parts of this from several sources but one of your best resources is the published Red Hat documentation.RTFM. Red Hat has excellent manuals and you will find most of this stuff there.

Some hearty souls may chose to edit the sendmail.cf file directly however I do not see the need for this. The whole idea of the sendmail.mc file is to make the configuration file manageable and to generate the .cf file. When I dove into this, I read as much as I could, including the vaunted O’Reilly Bat Book. Everything I read said to stick with the macros (m4 and mc) and let them generate the .cf. I’ve played with both files from time to time and find the .mc to be much more manageable for my pea-brain. The sendmail.mc file is 145 lines, the sendmail.cf file is 1800 lines. You figure it out….

You will need to run make -C /etc/mail as root to generate the sendmail.cf file from the sendmail.mc macro after you are finished making these changes. You will also need to do a /sbin/service sendmail restart as root once you have made the new sendmail.cf file. More on this below.

Please let me know if you see any errors or omissions in this document. Also, note that I am well aware I am not saving the world here.


Some definitions:

Comment out: Place a dnl or a dnl # in front of the line in the macro file. This will cause the m4 compiler to ignore that line.

Uncomment: Remove the dnl or dnl # in front of the line in the macro file. There may also be changes after you uncomment.

Add: New lines that should be added just like they are shown.

Replace: Replace the existing line (which will be shown) with the new line.

Notes: These are listed in roughly the order they appear in the sendmail.mc file, not by importance. I suggest you read through them all and sort out the ones you need. Don’t change the order of things too much as the compiler can get picky if too many things are defined out of order. Also, they insist on using forward-single-quotes (`) which are a pain if you don’t notice them. It is best to copy existing lines and modify them so you don’t mix up the forward and standard quotes.


Modify the actual sendmal.mc file

1. The most important change you need to make is this first step. You must comment out the following line:

DAEMON_OPTIONS(`Port=smtp,Addr=127.0.0.1, Name=MTA’)dnl

This will allow sendmail to make connections with machines other than the localhost. Duh. The reason for having this line included (turned on) by default will be left as an exercise for the reader.

2. Comment out the following line:

define(`UUCP_MAILER_MAX’, 2000000′)dnl

You don’t need this. Leave it if you like.

3. Comment out the following line:

FEATURE(`local_procmail,`’, `procmail -t -Y -a $h -d $u’)dnl

You don’t need procmail for the simple stuff. Leave it or modify it if you like.

4. Comment out the following line:

EXPOSED_USER(`root’)dnl

Leave it or modify it if you like.

5. Comment out the following line:

FEATURE(`accept_unresolvable_domains’)dnl

If this line is NOT commented out, you will open yourself up to more spam as sendmail will not do one of its basic checks on the incoming MTA.

6. Another key change is to set up your gateway machine as your “null client”. This is done by the following add:

FEATURE(`nullclient’,`[192.168.100.1]’)dnl   (assuming your SMTP gateway machine is 192.168.100.1)

This will forward mail to your other machine which will interface to the outside world and local users. You will need to have your access file set up correctly on your gateway machine to allow relaying from this internal sendmail machine.

7. Replace the following line and modify it as required.

MASQUERADE_AS(`mydomain.com’)dnl Becomes

MASQUERADE_AS(`eexamplee.net’)dnl

This causes all sent mail to appear to come from eexamplee.net.

8. Replace the following line and modify it as required.

MASQUERADE_AS(mydomain.com)dnl Becomes

MASQUERADE_AS(eexamplee.net)dnl

Note this is identical to the previous line except without the single quotes. Don’t know about this one.

9. Uncomment the following:

FEATURE(masquerade_envelope)dnl

This is similar to the previous masquerade statement except in also masquerades the entire envelope.

10. Replace and modify the following:

LOCAL_DOMAIN(`mydomain.com’)dnl Becomes

LOCAL_DOMAIN(`eexamplee.net’)dnl

This defines the domain name to masquerade.

11. Comment out the following line:

MAILER(smtp)dnl

12. Comment out the following line:

MAILER(procmail)dnl

Other changes beyond sendmail.mc

The next step is to modify the ancillary files to let sendmail do its thing.

Setting up the access file

The /etc/mail/access file allows you to block access to the mail server based on host names and IP addresses. You can use this to create blacklists and whitelists although they can be a bit hard to maintain as they are static. There are some lines you need to have in here even if you don’t explicitly list anything else. The required lines are the localhost and the hostname.

hostname.eexamplee.net RELAY localhost RELAY 127.0.0.1 RELAY 192.168.5 RELAY 192.168.100 RELAY

Setting up the local-host-names file

The /etc/mail/local-host-names file defines the aliases for the local machine. You want to put all the names in here that will be used by sendmail to define the host.

# local-host-names – include all aliases for your machine here.
eexamplee.net.net
mail.eexamplee.net

Pretty self explanatory.

Modifying the aliases file

The /etc/aliases file contains the mail aliases for the server. It is important that some of these be here to be compliant with RFCs. Usually you will only need to edit the last line.

# Person who should get root’s mail
root:           billybob

You may want to add some other lines for something like spamtrap: or any other aliases.

 

Burn it!

Now we will make sure everything is prepped and ready to use by sendmail. Execute the following commands as root:

/usr/bin/newalises    This activates the changes you made to the /etc/aliases file. Note: if you change aliases in the future, you only need to execute this command, you do not need to restart sendmail for the changes to show through.

makemap hash /etc/mail/access < /etc/mail/access    This creates a hashed version of your access database. This will keep your ISP username and password secure. A new /etc/mail/access.db file will be created.

makemap hash /etc/mail/local-host-names < /etc/mail/local-host-names    Like above, this creates a one-way hash of the local-host-names file you modified.

make -C /etc/mail    (That’s an upper case “C”) This creates the /etc/mail/sendmail.cf file from the /etc/mail/sendmail.mc file you modified earlier. Note: some of the above steps are covered here by the makefile but it won’t hurt to make them again.

Now all you have to do is restart the server.

/sbin/service sendmail restart    This will kill the sendmail job (if its running) and restart it using all your configuration changes.

That’s it!

Sendmail Mods — Using Sendmail Correctly From Your Dynamic ISP Address

Modifying the sendmail.mc file to make it work….

Listed below are the changes to a default RH 9 /etc/mail/sendmail.mc file required to operate a mail server behind a non-reversible IP address. This should work for DSL, cable modem and [shudder] dial-up. If you can’t do a reverse DNS lookup on your domain and have it resolve to your IP (dynamic or otherwise) you may have trouble delivering mail to many destinations. These changes are also good for general sendmail set-up except you may want to omit step 3.

You are NOT done once you change the .mc file. There are other changes that need to be done to the server.

shoulder

Anything not listed for change/add/delete here should work fine with the default settings. I do NOT know if this will work for any other installation (e.g. Red Hat 7.2 or Mandrake). This worked with the default sendmail RPM shipped with RH 9 (and subsequent sendmail updates). I gleaned some parts of this from several sources but one of your best resources is the published Red Hat documentation.RTFM. Red Hat has excellent manuals and you will find most of this stuff there.

Some hearty souls may chose to edit the sendmail.cf file directly however I do not see the need for this. The whole idea of the sendmail.mc file is to make the configuration file manageable and to generate the .cf file. When I dove into this, I read as much as I could, including the vaunted O’Reilly Bat Book. Everything I read said to stick with the macros (m4 and mc) and let them generate the .cf. I’ve played with both files from time to time and find the .mc to be much more manageable for my pea-brain. The sendmail.mc file is 145 lines, the sendmail.cf file is 1800 lines. You figure it out….

You will need to run make -C /etc/mail as root to generate the sendmail.cf file from the sendmail.mc macro after you are finished making these changes. You will also need to do a /sbin/service sendmail restart as root once you have made the new sendmail.cf file. More on this below.

Please let me know if you see any errors or omissions in this document. Also, note that I am well aware I am not saving the world here.


 

Some definitions:

Comment out: Place a dnl or a dnl # in front of the line in the macro file. This will cause the m4 compiler to ignore that line.

Uncomment: Remove the dnl or dnl # in front of the line in the macro file. There may also be changes after you uncomment.

Add: New lines that should be added just like they are shown.

Replace: Replace the existing line (which will be shown) with the new line.

Notes: These are listed in roughly the order they appear in the sendmail.mc file, not by importance. I suggest you read through them all and sort out the ones you need. Don’t change the order of things too much as the compiler can get picky if too many things are defined out of order. Also, they insist on using forward-single-quotes (`) which are a pain if you don’t notice them. It is best to copy existing lines and modify them so you don’t mix up the forward and standard quotes.


Modify the actual sendmal.mc file

 

1. The most important change you need to make is this first step. You must comment out the following line:

DAEMON_OPTIONS(`Port=smtp,Addr=127.0.0.1, Name=MTA’)dnl

This will allow sendmail to make connections with machines other than the localhost. Duh. The reason for having this line included (turned on) by default will be left as an exercise for the reader.

2. Comment out the following line:

FEATURE(`accept_unresolvable_domains’)dnl

If this line is NOT commented out, you will open yourself up to more spam as sendmail will not do one of its basic checks on the incoming MTA.

3. Another key change is to set up your ISP as your “smart host”. This is done by the following replace:

dnl define(`SMART_HOST’,`smtp.your.provider’)  Becomes

define(`SMART_HOST’,`outgoing.earthlink.net’)   (or whatever your ISP’s SMTP gateway is)

You are essentially using your ISP as a mail relay. This is the same technique that spammers use (in an attempt) to hide their identity. Here, we do it so that the mail will be sourced from an established IP that will pass a reverse DNS test. The server at outgoing.earthlink.net will very likely require a login to relay like this. We will take care of that later. Your ISP sees this as an SMTP (port 25) connection just like you sent it from an MUA like Outlook. Most large organizations like AOL, Hotmail and Juno will not accept mail from your DSL or cable-modem address. You do not have to do this to make your server work, but expect a large number of bounces if you don’t.

4. Add the following line:

define(`confBIND_OPTS’, `WorkAroundBrokenAAAA’)dnl

This change is a work-around for broken name servers. Its not a big deal although some of the blacklists (See below) recommend you have this enabled.

5. Replace the following line to fine tune the response to MTA queries and increase your privacy:

define(`confPRIVACY_FLAGS’, `authwarnings,novrfy,noexpn,restrictqrun’)dnl  Becomes

define(`confPRIVACY_FLAGS’, `goaway,restrictqrun’)dnl

This increases security by limiting the amount of information your sendmail server spews out to door-knockers. This is also an anti-spam measure. Note that “goaway” is a short-hand version of many of the flags in the original configuration line.

6. This one is just for fun and probably violates some RFCs so I would not recommend doing it. Add the following:

define(`confSMTP_LOGIN_MSG’,`$j Microsoft SMTPSVC 4.0.1095.2600′)

This makes the mail server advertise itself as the defined string during SMTP connections. I did this in an attempt to fool people into believing that I was running a Microsoft server. Security through obscurity. It doesn’t work. Any scanning tool such as Nessus can see right through this ruse.

7. Uncomment the following line:

FEATURE(`delay_checks’)dnl

Another non-essential change, however it provides some extra information when spammers attempt to connect or relay through your machine.

8. Now we add some heavyweight spam fighters. The blacklists. Add the following lines:

FEATURE(dnsbl,`zen.spamhaus.org’,`”550 Mail from site rejected; see http://www.spamhaus.org”&#8216;)dnl
FEATURE(enhdnsbl,`bl.spamcop.net’,`”550 Server blocked see: http://spamcop.net/bl.shtml?”$&amp;{client_addr}’,`t’)dnl
FEATURE(dnsbl, `dnsbl.njabl.org’, `”550 Email rejected – see http://njabl.org”&#8216;)dnl

These are only some of the blacklists available. A good list can be found here. Be careful about using some of those listed on that site as they are very aggressive and may cause false positives. The whole idea of blacklists has caused some vociferous arguments. If you are gun shy about possibly blocking some legitimate email, don’t use them or use something tame like McFadden Associates blacklist which will allow legit users to over-ride your blacklist. The “enhdnsbl” is an enhanced blacklist check that gives you other options on the FEATURE line. Check the homepage of the sites for instructions on how to use the dnsbl command with their particular blacklist.
NOTE: We no longer use or recommend the SORBS blacklist because of unreliable data and inaccessible web page.

9. Replace the following line and modify it as required.

MASQUERADE_AS(`mydomain.com’)dnl Becomes

MASQUERADE_AS(`eexamplee.net’)dnl

This causes all sent mail to appear to come from eexamplee.net.

10. Replace the following line and modify it as required.

MASQUERADE_AS(mydomain.com)dnl Becomes

MASQUERADE_AS(eexamplee.net.)dnl

Note this is nearly identical to the previous line except without the single quotes. Don’t know about this one although it comes directly from Red Hat documentation, I don’t believe it is required (???).

11. Uncomment the following:

FEATURE(masquerade_envelope)dnl

This is similar to the previous masquerade statement except in also masquerades the entire envelope.

12. Uncomment the following line:

FEATURE(masquerade_entire_domain)dnl

This causes all hosts to be masqueraded as eexamplee.net even host1.eexamplee.net and hostxyx.eexamplee.net. This will be important if you set up other machines behind your mail server and use it as a gateway.

13. Add the following line:

FEATURE(always_add_domain)dnl

This will add the domain name to all outbound mail.

14. Replace and modify the following:

MASQUERADE_DOMAIN(`mydomain.com’)dnl Becomes

MASQUERADE_DOMAIN(`eexamplee.net’)dnl

This defines the domain name to masquerade.

 

Other changes beyond sendmail.mc

The next step is to modify the ancillary files to let sendmail do its thing.

Setting up the access file

The /etc/mail/access file allows you to block access to the mail server based on host names and IP addresses. You can use this to create blacklists and whitelists although they can be a bit hard to maintain as they are static. There are some lines you need to have in here even if you don’t explicitly list anything else.

mail.eexamplee.net RELAY localhost RELAY 127.0.0.1 RELAY 192.168.5 RELAY 192.168.100 RELAY

These allow mail from the local host and from others on your network to use the server to get to the outside world. Of course you will need to modify these networks to your configuration. I have 192.168.5 and 192.168.100 addresses behind my firewall so they are in this list.

The next step is to add the login information to the /etc/mail/access file. This is required to let your ISP server know who you are when you request a relay of mail to the rest of the world. The example below uses plain text logins which means your username and password are sent in plain text. Although this is not secure, it is also not uncommon. You will want to see if they will allow secure password authentication. You can then modify the lines below to use a different method other than LOGIN PLAIN. Also, you will want to make sure privileges on this file are set accordingly so that local users can not see these username/password combinations. This is not a problem as sendmail doesn’t use this file directly, it uses the database hash which will be created later.

AuthInfo:earthlink.net “U:username1” “P:secret” “M:LOGIN PLAIN”
AuthInfo:outgoing.earthlink.net “U:username1” “P:secret” “M:LOGIN PLAIN”

AuthInfo tells sendmail to use this information to answer authorization requests from the remote MTA. The next item is obviously the server name. U is the username to login and P is the password. M is the method of authentication used (see comments in above paragraph).

Setting up the local-host-names file

The /etc/mail/local-host-names file defines the aliases for the local machine. You want to put all the names in here that will be used by sendmail to define the host.

# local-host-names – include all aliases for your machine here.
eexamplee.net.net
mail.eexamplee.net

Pretty self explanatory.

Modifying the aliases file

The /etc/aliases file contains the mail aliases for the server. It is important that some of these be here to be compliant with RFCs. Usually you will only need to edit the last line.

# Person who should get root’s mail
root:           billybob

You may want to add some other lines for something like spamtrap: or any other aliases.

 

Burn it!

Now we will make sure everything is prepped and ready to use by sendmail. Execute the following commands as root:

/usr/bin/newalises    This activates the changes you made to the /etc/aliases file. Note: if you change aliases in the future, you only need to execute this command, you do not need to restart sendmail for the changes to show through.

makemap hash /etc/mail/access < /etc/mail/access    This creates a hashed version of your access database. This will keep your ISP username and password secure. A new /etc/mail/access.db file will be created.

makemap hash /etc/mail/local-host-names < /etc/mail/local-host-names    Like above, this creates a one-way hash of the local-host-names file you modified.

make -C /etc/mail    (That’s an upper case “C”) This creates the /etc/mail/sendmail.cf file from the /etc/mail/sendmail.mc file you modified earlier. Note: some of the above steps are covered here by the makefile but it won’t hurt to make them again.

Now all you have to do is restart the server.

/sbin/service sendmail restart    This will kill the sendmail job (if its running) and restart it using all your configuration changes.

That’s it! Now just sit back and watch the spam roll in.

SSH BLACKLISTING

Posted: November 30, 2008 in LINUX
Tags:

The sshblack script is a real-time security tool for secure shell (ssh). It monitors *nix log files for suspicious activity and reacts appropriately to aggressive attackers by adding them to a “blacklist” created using various firewalling tools — such as iptables — available in most modern versions of Unix and Linux. The blacklist is simply a list of source IP addresses that are prohibited from making ssh connections to the protected host. Once a predetermined amount of time has passed, the offending IP address is removed from the blacklist.

Download :

http://www.pettingers.org/media/sshblackv281.tar.gz 

suggest you figure out what these do (and tweak them to meet your needs) before blindly executing them.

  • list — manually adds an IP address to the blacklist and modifies the $CACHE file accordingly
  • unlist — manually remove an IP address from the blacklist and the $CACHE file
  • bl — a manual blacklisting tool (one liner that modifies the iptables configuration only)
  • unbl — a manual UNblacklisting tool (one liner that modifies the iptables configuration only)
  • iptables-setup — a few shell commands to set up the iptables chains if you don’t want to do it manually

 

##########################################################

ssh balcklist init script

****************************************

#!/bin/bash # # Startup script for SSH Black List by Vadim Reznik # See http://www.pettingers.org/code/sshblack.html for details # # chkconfig: 345 86 14 # description: SSH Black monitors ssh connections for attacks # # processname: sshblack # pidfile: /var/run/sshblack.pid # Source function library. . /etc/rc.d/init.d/functions # Source networking configuration. . /etc/sysconfig/network # Check that networking is up. [ ${NETWORKING} = “no” ] && exit 0 # See how we were called. case “$1” in start) echo -n “Starting sshblack: ” /usr/local/sshblackD/sshblack.pl echo touch /var/lock/subsys/sshblack ;; stop) echo -n “Shutting down sshblack: ” pid=`ps axw | awk {‘if(match($7, “/usr/local/sshblackD/sshblack.pl”)) print$1}’` kill -9 $pid RETVAL=$? echo rm -f /var/lock/subsys/sshblack rm -f /var/run/sshblack.pid ;; restart) $0 stop $0 start ;; *) echo “Usage: $0 {start|stop|restart}” exit 1 esac exit 0 ################################################################### Configuring sshblack for RedHat Enterprise 4 Linux

The following sequence is executed as root user.

  1. Download sshblack from http://www.sshblack.com/

  2. Unpack the tar file into a working directory, and check that an executable file sshblackv28.pl is created. I have used /usr/local/sbin/sshblackv28; the sshblack installation suggests /usr/src/sshblack. E.g.:

  • [root@luggage sshblack]# cd /usr/local/sbin/sshblackv28 [root@luggage sshblack]# tar xvzf /file/kit/TUXKIT/SSHBlack/sshblackv28.tar.gz bl INSTALL.TXT iptables-setup.sh README.TXT sshblack.pl sshblack-start.sh unbl [root@luggage sshblack]# ls -al total 116 drwx—— 2 root root 4096 Dec 11 12:01 . drwxr-xr-x 3 root root 4096 Dec 11 11:52 .. -rwxrwxr-x 1 root root 263 Aug 10 06:07 bl -rw-rw-r– 1 root root 24731 Aug 6 18:23 INSTALL.TXT -rwxrwxr-x 1 root root 447 Aug 10 05:18 iptables-setup.sh -rw-rw-r– 1 root root 14742 Aug 6 18:01 README.TXT -rwxr-xr-x 1 root root 11487 Aug 10 06:46 sshblackv.pl -rwxrwxr-x 1 root root 223 Aug 10 05:18 sshblack-start.sh -rwxrwxr-x 1 root root 278 Aug 10 06:07 unbl
  • Ensure perl is installed; e.g.
    • [root@luggage sshblack]# perl –version This is perl, v5.8.5 built for i386-linux-thread-multi : (etc.)
  • Ensure iptables is installed and running; e.g.
    • root@luggage sshblack]# iptables –list Chain INPUT (policy ACCEPT) target prot opt source destination RH-Firewall-1-INPUT all — anywhere anywhere Chain FORWARD (policy ACCEPT) target prot opt source destination RH-Firewall-1-INPUT all — anywhere anywhere Chain OUTPUT (policy ACCEPT) target prot opt source destination Chain RH-Firewall-1-INPUT (2 references) target prot opt source destination ACCEPT all — anywhere anywhere ACCEPT icmp — anywhere anywhere icmp any ACCEPT ipv6-crypt– anywhere anywhere ACCEPT ipv6-auth– anywhere anywhere ACCEPT udp — anywhere 224.0.0.251 udp dpt:5353 ACCEPT udp — anywhere anywhere udp dpt:ipp ACCEPT all — anywhere anywhere state RELATED,ESTABLISHED ACCEPT tcp — anywhere anywhere state NEW tcp dpt:http ACCEPT tcp — anywhere anywhere state NEW tcp dpt:https ACCEPT tcp — anywhere anywhere state NEW tcp dpt:ssh ACCEPT udp — anywhere anywhere state NEW udp dpt:domain ACCEPT tcp — anywhere anywhere state NEW tcp dpt:domain ACCEPT udp — anywhere anywhere state NEW udp dpt:bootps ACCEPT udp — anywhere anywhere state NEW udp dpt:netbios-ns ACCEPT tcp — anywhere anywhere state NEW tcp dpt:netbios-ns ACCEPT tcp — anywhere anywhere state NEW tcp dpt:netbios-ssn ACCEPT tcp — anywhere anywhere state NEW tcp dpt:ipp ACCEPT tcp — anywhere anywhere state NEW tcp dpt:rsync REJECT all — anywhere anywhere reject-with icmp-host-prohibited
  • This step can be skipped if creating the init.d script described below. Create a new iptables chain called BLACKLIST, add this to the start of the INPUT chain for incoming TCP data on port 22 (SSH), and save the resulting iptables configuration:

    • [root@luggage sshblack]# iptables -N BLACKLIST [root@luggage sshblack]# iptables -I INPUT 1 -p tcp –dport 22 -j BLACKLIST [root@luggage sshblack]# /sbin/service iptables save Saving firewall rules to /etc/sysconfig/iptables: [ OK ] [root@luggage sshblack]#
  • Tailor the sshblack script: look in particular for my($LOCALNET), my($ADDRULE), my($DELRULE), my($REASONS). In my case, I changed just the following definition to allow for my local net:

    • # regex for whitelisted IPs – never blacklist these addresses my($LOCALNET) = ‘^(?:127\.0\.0\.1|192\.168\.0|193\.123\.216)’;
  • This step can be skipped if creating the init.d script described below. Start the script:

    • [root@luggage sshblack]# /usr/local/sbin/sshblack/sshblack.pl >>/var/log/sshblacklisting 2>&1 & [1] 8105
  •  

    2. Arrange sshblack to run on system reboot

    To arrange for the script to be started automatically on system reboot (on my RedHat-based system), I created a script file that conforms to the chkconfig init file conventions. (Remove the (-) from the first line – I don’t know why, but the wiki puts that there.)

     

    #!/bin/bash (-) # # /etc/rc.d/init.d/sshblack # # Controls the sshblackv28.pl sshd breakin attempt monitoring script # # chkconfig: 345 86 14 # description: SSH Black monitors ssh connections for attacks # processname: sshblack # pidfile: /var/run/sshblack.pid # # : : : # | | | # | | priority for kill scripts # | | # | priority for start scripts # | # run levels at which to start service # # The code in this script adapted from /etc/init.d/atd on my RHEL4-derived system, # with some additional clues from [http://www.pettingers.org/media/sshblackinit.txt] # # See also: http://www.netadmintools.com/art94.html # Source function library. . /etc/init.d/functions progname=”sshblackv28.pl” progpath=”/usr/local/sbin/sshblackv28/” prog=”${progpath}${progname}” logfile=”/var/log/sshblacklisting” test -x ${prog} || exit 0 RETVAL=0 # # See how we were called. # start() { # Create firewall table for blacklist (in case it got lost) # (On Redhat Linux, running the system security level script causes additional # IPtables entries to be removed, so this code reinstates the sshblack entries if iptables -L INPUT | grep BLACKLIST >/dev/null then # Blacklist already configured : else # Blacklist missing. # Lines 2-4 below may need adjusting to match the local iptables usage: # currently they insert the blacklist check at the start of the INPUT chain iptables -N BLACKLIST iptables -I INPUT 1 -m state –state RELATED,ESTABLISHED -j ACCEPT iptables -I INPUT 2 -i lo -j ACCEPT iptables -I INPUT 3 -p tcp –dport 22 -j BLACKLIST # Remove any old blacklist cache # (if iptables is reset without clearing this, previously started attacks # may be allowed through) rm -f /var/tmp/ssh-blacklist-pending fi # Check if prog is already running if [ ! -f /var/lock/subsys/${progname} ]; then echo -n $”Starting ${progname}: ” ${prog} >>${logfile} 2>&1 & RETVAL=$? if [ $RETVAL -eq 0 ]; then touch /var/lock/subsys/${progname} success else failure fi echo fi return $RETVAL } stop() { echo -n $”Stopping $progname: ” killproc ${prog} RETVAL=$? [ $RETVAL -eq 0 ] && rm -f /var/lock/subsys/${progname} echo return $RETVAL } restart() { stop start } reload() { restart } status_prog() { status ${prog} } case “$1″ in start) start ;; stop) stop ;; reload|restart) restart ;; condrestart) if [ -f /var/lock/subsys/${progname} ]; then restart fi ;; status) status_prog ;; reset) [ -f /var/lock/subsys/${progname} ] && rm -f /var/lock/subsys/${progname} ;; *) echo $”Usage: $0 {start|stop|restart|condrestart|status}” exit 1 esac exit $? exit $RETVAL

    Placing this file in directory /etc/init.d, and making it executable, the whole sshblack utility becomes manageable using chkconfig and service commands; e.g.

     

    [root@luggage sshblack]# cp sshblack /etc/init.d [root@luggage sshblack]# ls -al /etc/init.d/sshblack -rwxr-xr-x 1 root root 1863 Dec 11 15:03 /etc/init.d/sshblack [root@luggage sshblack]# chkconfig –add sshblack [root@luggage sshblack]# chkconfig –list sshblack sshblack 0:off 1:off 2:on 3:on 4:on 5:on 6:off [root@luggage sshblack]# service sshblack start 

    This is what you can expect to see from this script (approximately):

    host # ./double.pl www.google.com

    #######################################################

    #!/usr/bin/perl
    #
    # double.pl – Double Check That Hostnames Match The IP’s They’re Advertising
    #
    # 2008 – Mike Golvach – eggi@comcast.net
    #
    # Creative Commons Attribution-Noncommercial-Share Alike 3.0 United States License
    #
    use Socket;
    if ( $#ARGV != 0 )      {
               print “Usage: $0 hostname\n”;    
                exit(1);
    }
    $entry = $ARGV[0];
    $hostname1 = $entry;
    $ip1 = gethostbyname($hostname1) || die “error – gethostbyname: $!\n\n”;
    $hostip1 = inet_ntoa($ip1) || die “error – inet_ntoa: $!\n\n”;
    print “\nHostname: $hostname1 = IP: $hostip1\n\n”;
    $hostname2 = gethostbyaddr(inet_aton($hostip1),AF_INET) || die “error – inet_aton: $!\n\n”;
    print “IP: $hostip1 = Hostname: $hostname2\n\n”;
    if ( $hostname1 eq $hostname2 ) {
      print “$hostname1 and $hostname2 Match!\n”;      
       print “Good Deal!\n\n”;  
           exit(0);
    }       else    {
          print “$hostname1 and $hostname2 Do Not Match\n”;
              print “Checking Reverse…\n\n”;
            $ip2 = gethostbyname($hostname2) || die “error – gethostbyname: $!\n\n”;
             $hostip2 = inet_ntoa($ip2) || die “error – inet_ntoa: $!\n\n”;
              if ( $hostip1 eq $hostip2 )     {             
       print “$hostip1 and $hostip2 match\n”;
       print “Everything is probably ok!\n\n”;
       exit(0);
            }       else    {        
            print “$hostip1 and $hostip2 don’t match\n”; 
             print “This DNS may be bogus or setup incorrectly!\n\n”;  
                  exit(0);
            }
    }

    ###########################################################################

    http://www.nixcraft.com

     How do I Move or migrate user accounts to from old Linux server a new Cent OS Linux server including mails? This new system a fresh installation.

    A. You can migrate users from old Linux server to new Linux sever with standard commands such as tar, awk, scp and others. This is also useful if you are using old Linux distribution such as Redhat 9 or Debian 2.x.

    Following files/dirs are required for traditional Linux user management:
    /etc/passwd – contains various pieces of information for each user account

    /etc/shadow – contains the encrypted password information for user’s accounts and optional the password aging information.

    /etc/group – defines the groups to which users belong

    /etc/gshadow – group shadow file (contains the encrypted password for group)

    /var/spool/mail – Generally user emails are stored here.

    /home – All Users data is stored here.

    You need to backup all of the above files and directories from old server to new Linux server.

    Commands to type on old Linux system

    First create a tar ball of old uses (old Linux system). Create a directory:
    # mkdir /root/move/
    Setup UID filter limit:
    # export UGIDLIMIT=500
    Now copy /etc/passwd accounts to /root/move/passwd.mig using awk to filter out system account (i.e. only copy user accounts)
    # awk -v LIMIT=$UGIDLIMIT -F: '($3>=LIMIT) && ($3!=65534)' /etc/passwd > /root/move/passwd.mig
    Copy /etc/group file:
    # awk -v LIMIT=$UGIDLIMIT -F: '($3>=LIMIT) && ($3!=65534)' /etc/group > /root/move/group.mig
    Copy /etc/shadow file:
    # awk -v LIMIT=$UGIDLIMIT -F: '($3>=LIMIT) && ($3!=65534) {print $1}' /etc/passwd | tee - |egrep -f - /etc/shadow > /root/move/shadow.mig
    Copy /etc/gshadow (rarely used):
    # cp /etc/gshadow /root/move/gshadow.mig
    Make a backup of /home and /var/spool/mail dirs:
    # tar -zcvpf /root/move/home.tar.gz /home
    # tar -zcvpf /root/move/mail.tar.gz /var/spool/mail

    Where,

    • Users that are added to the Linux system always start with UID and GID values of as specified by Linux distribution or set by admin. Limits according to different Linux distro:
      • RHEL/CentOS/Fedora Core : Default is 500 and upper limit is 65534 (/etc/libuser.conf).
      • Debian and Ubuntu Linux : Default is 1000 and upper limit is 29999 (/etc/adduser.conf).
    • You should never ever create any new system user accounts on the newly installed Cent OS Linux. So above awk command filter out UID according to Linux distro.
    • export UGIDLIMIT=500 – setup UID start limit for normal user account. Set this value as per your Linux distro.
    • awk -v LIMIT=$UGIDLIMIT -F: ‘($3>=LIMIT) && ($3!=65534)’ /etc/passwd > /root/move/passwd.mig – You need to pass UGIDLIMIT variable to awk using -v option (it assigns value of shell variable UGIDLIMIT to awk program variable LIMIT). Option -F: sets the field separator to : . Finally awk read each line from /etc/passwd, filter out system accounts and generates new file /root/move/passwd.mig. Same logic is applies to rest of awk command.
    • tar -zcvpf /root/move/home.tar.gz /home – Make a backup of users /home dir
    • tar -zcvpf /root/move/mail.tar.gz /var/spool/mail – Make a backup of users mail dir

    Use scp or usb pen or tape to copy /root/move to a new Linux system.
    # scp -r /root/move/* user@new.linuxserver.com:/path/to/location

    Commands to type on new Linux system

    First, make a backup of current users and passwords:
    # mkdir /root/newsusers.bak
    # cp /etc/passwd /etc/shadow /etc/group /etc/gshadow /root/newsusers.bak

    Now restore passwd and other files in /etc/
    # cd /path/to/location
    # cat passwd.mig >> /etc/passwd
    # cat group.mig >> /etc/group
    # cat shadow.mig >> /etc/shadow
    # /bin/cp gshadow.mig /etc/gshadow

    Please note that you must use >> (append) and not > (create) shell redirection.

    Now copy and extract home.tar.gz to new server /home
    # cd /
    # tar -zxvf /path/to/location/home.tar.gz

    Now copy and extract mail.tar.gz (Mails) to new server /var/spool/mail
    # cd /
    # tar -zxvf /path/to/location/mail.tar.gz

    Now reboot system; when the Linux comes back, your user accounts will work as they did before on old system:
    # reboot

    Please note that if you are new to Linux perform above commands in a sandbox environment. Above technique can be used to UNIX to UNIX OR UNIX to Linux account migration. You need to make couple of changes but overall the concept remains the same.

    Further readings

    • Read man pages of awk, passwd(5), shadow(5), group(5), tar command

    Tested on . CentOS, Fedora, Redhat

    Configuring a Router

    Posted: November 22, 2008 in CISCO, IP, ROUTING
    Tags: ,
    Configuration Example: VTP and Inter-VLAN Routing

    ISP Router

    Router>en

    Router>#config t

    Router(config)#hostname ISP
    Sets the host name

    ISP(config)#no ip domain-lookup
    Turns off DNS resolution to avoid wait time dur to DNS lookup of spelling errors

    ISP(config)#line con 0

    ISP(config-line)#logging synchronous
    Appends the command line to a new lineno interruption from info items

    ISP(config-line)#exec-timeout 0 0
    Console session will never time out

    ISP(config-line)#exit

    ISP(config)#enable secret cisco
    Sets the secret password to cisco

    ISP(config)#int lo 0
    Creates a loopback address for testing purposes

    ISP(config-if)#description simulated address representing remote website

    ISP(config-if)#ip address 172.16.1.1 255.255.255.0

    ISP(config-if)#int s0/0
    Enters serial interface configuration mode

    ISP(config-if)#description WAN link to the Corporate Router

    ISP(config-if)#ip address 200.200.200.13 255.255.255.252

    ISP(config-if)#clock 56000
    Sets the clock rate for the serial link

    ISP(config-if)#no shut

    ISP(config-if)#exit

    ISP(config-if)#router eigrp 10
    Turns on the EIGRP routing process

    ISP(config-router)#network 172.16.0.0
    Advertises the 172.16.0.0 network

    ISP(config-router)#network 200.200.200.0
    Advertises the 200.200.200.0 network

    ISP(config-router)#no auto-summary
    Turns off automatic summarization at the classful boundary

    ISP(config-router)#exit

    ISP(config)#exit

    ISP#copy run start
    Saves the configuration to NVRAM

    CORP Router (1721 Router Running Cisco IOS Software Release 12.2(4)
    These commands work also for the 1760 and the 2620/2621 series routers

    Router>en

    Router#config t

    Router(config)#hostname CORP
    Sets host name

    CORP(config)#no ip domain-lookup
    Turns off resolution to avoid wait time due to DNS lookup of spelling errors

    CORP(config)#line con 0

    CORP(config-line)#logging synchronous
    Appends the command line to a new lineno interruption from info items

    CORP(config-line)#exec-timeout 0 0
    Console session will never time out

    CORP(config-line)#exit

    CORP(config)#enable secret cisco
    Sets the secret password to cisco

    CORP(config)#int s1

    CORP(config-if)#desc WAN link to ISP Router

    CORP(config-if)#ip add 200.200.200.14 255.255.255.252

    CORP(config-if)#bandwidth 1544
    Sets bandwith to 1544 kilobits for EIGRP calculation

    CORP(config-if)#no shut

    CORP(config-if)#exit

    CORP(config)#int fa0

    CORP(config-if)#full duplex

    CORP(config-if)#no shut

    CORP(config-if)#int fa0.1
    Creates a subinterface

    CORP(config-if)#no ip address
    Ensures there is no IP address assigned to the interface

    CORP(config-subif)#desc Management VLAN 1
    Assigns a description to the subinterface

    CORP(config-subif)#encapsulation dot1q 1 native
    Enables Dot1Q encapsulation with VLAN 1 as the native VLAN

    CORP(config-subif)#ip add 192.168.1.1 255.255.255.0
    Assigns an IP address to the subinterface

    CORP(config-subif)#int fa0.10
    Creates a subinterface

    CORP(config-subif)#desc Sales VLAN 10
    Assigns a description to the subinterface

    CORP(config-subif)#encapsulation dot1q 10
    Enables Dot1Q encapsulation on VLAN 10

    CORP(config-subif)#ip add 192.168.10.1 255.255.255.0
    Assigns an IP address to the subinterface

    CORP(config-subif)#int fa0.20
    Creates a subinterface

    CORP(config-subif)#desc Engineering VLAN 20
    Assigns a description to the subinterface

    CORP(config-subif)#encapsulation dot1q 20
    Enables Dot1Q encapsulation on VLAN 20

    CORP(config-subif)#ip add 192.168.20.1 255.255.255.0
    Assigns an IP address to the subinterface

    CORP(config-subif)#int fa0.30
    Creates a subinterface

    CORP(config-subif)#desc Marketing VLAN 30
    Assigns a description to the subinterface

    CORP(config-subif)#encapsulation dot1q 30
    Enables Dot1Q encapsulation on VLAN 30

    CORP(config-subif)#ip add 192.168.1.1 255.255.255.0
    Assigns an IP address to the subinterface

    CORP(config-subif)#exit

    CORP(config)#router eigrp 10
    Turns on the EIGRP routing process

    CORP(config-router)#network 192.168.1.0
    Advertises the 192.168.1.0 network

    CORP(config-router)#network 192.168.10.0
    Advertises the 192.168.10.0 network

    CORP(config-router)#network 192.168.20.0
    Advertises the 192.168.20.0 network

    CORP(config-router)#network 192.168.30.0
    Advertises the 192.168.30.0 network

    CORP(config-router)#network 200.200.200.0
    Advertises the 200.200.200.0 network

    CORP(config-router)#no auto-summary
    Turns off auto summari-zation

    CORP(config-router)#exit

    CORP(config)#exit

    CORP#copy run start
    Saves the configuration to NVRAM

    Caution: Remember to advertise all networks. Advertising 192.168.0.0 does not advertise networks from 192.168.0.0192.168.255.0. These are separate classful networks, so they must be advertised separately, just like 200.200.200.0 is advertised separately.

    2900 Series Switch

    switch>en

    switch>#config t

    switch(config)#hostname 2900Switch
    Sets host name

    2900Switch(config)#no ip domain-lookup
    Turns off DNS resolution to avoid wait time due to DNS lookup of spelling errors

    2900Switch(config)#line con 0

    2900Switch(config-line)#logging synchronous
    Appends the command line to a new lineno interruption from info items

    2900Switch(config-line)#exec-timeout 0 0
    Console session will never time out

    2900Switch(config)#exit

    2900Switch(config)#enable secret cisco
    Sets the secret password to cisco

    2900Switch(config)#exit

    2900Switch#vlan database
    Enters VLAN database mode

    2900Switch(vlan)#vlan 10 name Sales
    Creates VLAN 10 with the name Sales

    2900Switch(vlan)#vlan 20 name Engineering
    Creates VLAN 20 with the name Engineering

    2900Switch(vlan)#vlan 30 name Marketing
    Creates VLAN 30 with the name Marketing

    2900Switch(vlan)#vtp server
    Makes the switch a VTP server

    2900Switch(vlan)#vtp domain academy
    Assigns a domain name of academy

    2900Switch(vlan)#exit
    Applies all changes to VLAN database and exits mode

    2900Switch#config t

    2900Switch(config)#int vlan1

    2900Switch(config-if)#ip add 192.168.1.2 255.255.255.0

    2900Switch(config-if)#no shutdown

    2900Switch(config-if)#exit

    2900Switch(config)#ip default-gateway 192.168.1.1

    2900Switch(config)#int fa 0/1

    2900Switch(config-if)#desc Trunk Link to CORP Router

    2900Switch(config-if)#switchport mode trunk
    Creates a trunk link

    2900Switch(config-if)#switchport trunk encapsulation dot1q
    Sets encapsulation to Dot1Q

    2900Switch(config-if)#int fa 0/2

    2900Switch(config-if)#switchport access vlan 10
    Assigns a port to VLAN 10

    2900Switch(config-if)#spanning-tree portfast
    Transitions the port directly to the Forwarding state in Spanning Tree Protocol (STP)

    Note: The command switchport mode access is not needed, because this is the default mode for interfaces. Use it only if the port was previously set to be a trunk link.

    2900Switch(config-if)#int fa0/3

    2900Switch(config-if)#switchport access vlan 10
    Assigns a port to VLAN 10

    2900Switch(config-if)#spanning-tree portfast
    Transitions the port directly to the Forwarding state in STP

    2900Switch(config-if)#int fa0/4

    2900Switch(config-if)#switchport access vlan 10
    Assigns a port to VLAN 10

    2900Switch(config-if)#spanning-tree portfast
    Transitions the port directly to the Forwarding state in STP

    2900Switch(config-if)#int fa0/5

    2900Switch(config-if)#switchport access vlan 20
    Assigns a port to VLAN 20

    2900Switch(config-if)#spanning-tree portfast
    Transitions the port directly to the Forwarding state in STP

    2900Switch(config-if)#int fa0/6

    2900Switch(config-if)#switchport access vlan 20
    Assigns a port to VLAN 20

    2900Switch(config-if)#spanning-tree portfast
    Transitions the port directly to the Forwarding state in STP

    2900Switch(config-if)#int fa0/7

    2900Switch(config-if)#switchport access vlan 20
    Assigns a port to VLAN 20

    2900Switch(config-if)#spanning-tree portfast
    Transitions the port directly to the Forwarding state in STP

    2900Switch(config-if)#int fa0/8

    2900Switch(config-if)#switchport access vlan 20
    Assigns a port to VLAN 20

    2900Switch(config-if)#spanning-tree portfast
    Transitions the port directly to the Forwarding state in STP

    2900Switch(config-if)#int fa0/9

    2900Switch(config-if)#switchport access vlan 30
    Assigns a port to VLAN 30

    2900Switch(config-if)#spanning-tree portfast
    Transitions the port directly to the Forwarding state in STP

    2900Switch(config-if)#int fa0/10

    2900Switch(config-if)#switchport access vlan 30
    Assigns a port to VLAN 30

    2900Switch(config-if)#spanning-tree portfast
    Transitions the port directly to the Forwarding state in STP

    2900Switch(config-if)#int fa0/11

    2900Switch(config-if)#switchport access vlan 30
    Assigns a port to VLAN 30

    2900Switch(config-if)#spanning-tree portfast
    Transitions the port directly to the Forwarding state in STP

    2900Switch(config-if)#int fa0/12

    Save as Draft
    2900Switch(config-if)#switchport access vlan 30
    Assigns a port to VLAN 30

    2900Switch(config-if)#spanning-tree portfast
    Transitions the port directly to the Forwarding state in STP

    2900Switch(config-if)# CTRL + Z

    2900Switch#copy run start
    Saves the configuration to NVRAM

    2900Switch#

    2950 Series Switch

    switch>en

    switch>#config t

    switch(config)#hostname 2950Switch
    Sets the host name

    2950Switch(config)#no ip domain-lookup
    Turns off DNS resolution to avoid wait time due to DNS lookup of spelling errors

    2950Switch(config)#line con 0

    2950Switch(config-line)#logging synchronous
    Appends the command line to a new lineno interruption from info items

    2950Switch(config-line)#exec-timeout 0 0
    Console session will never time out

    2950Switch(config-line)#exit

    2950Switch(config)#enable secret cisco
    Sets the secret password to cisco

    2950Switch(config)#vlan 10
    Creates VLAN 10

    2950Switch(config-vlan)#name Sales
    Defines the name of Sales

    2950Switch(config-vlan)#vlan 20
    Creates VLAN 20

    2950Switch(config-vlan)#name Engineering
    Defines the name of Engineering

    2950Switch(config-vlan)#vlan 30
    Creates VLAN 30

    2950Switch(config-vlan)#name Marketing
    Defines the name of Marketing

    2950Switch(config-vlan)#exit

    2950Switch(config)#vtp mode server
    Makes the switch a VTP server

    2950Switch(config)#vtp domain academy
    Assigns a domain name of academy

    2950Switch(config)#int vlan1
    Creates the virtual VLAN 1 interface

    2950Switch(config-if)#ip add 192.168.1.2 255.255.255.0
    Assigns an IP address to the interface

    2950Switch(config-if)#no shutdown

    2950Switch(config-if)#exit

    2950Switch(config)#ip default-gateway 192.168.1.1
    Assigns the IP address of the default gateway

    2950Switch(config)#int fa 0/1

    2950Switch(config-if)#desc Trunk Link to CORP Router

    2950Switch(config-if)#switchport mode trunk
    Creates a trunk link

    2950Switch(config-if)#int range fa 0/2 4

    2950Switch(config-if-range)#switchport access vlan 10
    Assigns ports to VLAN 10

    2950Switch(config-if-range)#spanning-tree portfast
    Transitions ports directly to the Forwarding state in STP

    Note: The command switchport mode access is not needed, because this is the default mode for interfaces. Use it only if the port was previously set to be a trunk link.

    2950Switch(config-if-range)#int range fa0/5 8

    2950Switch(config-if-range)#switchport access vlan 20
    Assigns ports to VLAN 20

    2950Switch(config-if-range)#spanning-tree portfast
    Transitions port directly to the Forwarding state in STP

    2950Switch(config-if-range)#int range fa0/9 – 12

    2950Switch(config-if-range)#switchport access vlan 30
    Assigns ports to VLAN 10

    2950Switch(config-if-range)#spanning-tree portfast
    Transitions ports directly to the Forwarding state in STP

    2950Switch(config-if-range)# CTRL + Z

    2950Switch#copy run start
    Saves the configuration to NVRAM

     

    Monday, November 17, 2008

    Inter-VLAN Communication: Router-on-a-Stick

    Inter-VLAN Communication: Router-on-a-Stick

    Router(config)#int fa 0/0

    Enters interface mode for interface fa 0/0

    Router(config-if)#no shut

    Turns the interface on

    Router(config-if)#int fa 0/0.1

    Creates subinterface 0/0.1

    Router(config-subif)#encapsulation dot1q 1 native

    Assigns the native VLAN (usually VLAN 1) to this logical subinterface

    Router(config-subif)#ip address 192.168.1.1 255.255.255.0

    Assigns an IP address to the subinterface

    Router(config-subif)#int fa 0/0.10

    Creates subinterface 0/0.10

    Router(config-subif)#encapsulation dot1q 10

    Assigns VLAN 10 to this subinterface

    Router(config-subif)#ip address 192.168.10.1 255.255.255.0

    Assigns an IP address to the subinterface

    Router(config-subif)# CNTL + Z


    Router#



    Thursday, April 3, 2008

    Configuration Example: Basic Router Configuration


    Figure A shows the network topology for the configuration that follows, which shows a basic router configuration using the commands covered in this chapter. 




    Boston Router

    Router>en

    Enters privileged mode

    Router#clock set 18:30:00 15 Nov 2004

    Sets local time on router

    Router#config t

    Enters global config mode

    Router(config)#hostname Boston

    Sets router name to Boston

    Boston(config)#no ip domain-lookup

    Turns off name resolution on unrecognized commands (spelling mistakes)

    Boston(config)#banner motd #

    Creates an MOTD banner

    This is the Boston Router.


    Authorized Access Only


    #


    Boston(config)#clock timezone EST 5

    Sets time zone to Eastern Standard Time (5 from UTC)

    Boston(config)#enable secret cisco

    Enables secret password set to cisco

    Boston(config)#service password-encryption

    Passwords will be given weak encryption

    Boston(config)#line con 0

    Enters line console mode

    Boston(config-line)#logging sync

    Commands will not be interrupted by unsolicited messages

    Boston(config-line)#password class

    Sets password to class

    Boston(config-line)#login

    Enables password checking at login

    Boston(config-line)#line vty 0 4

    Moves to virtual Telnet lines 0 through 4

    Boston(config-line)#password class

    Sets password to class

    Boston(config-line)#login

    Enables password checking at login

    Boston(config-line)#line aux 0

    Moves to line auxiliary mode

    Boston(config-line)#password class

    Sets password to class

    Boston(config-line)#login

    Enables password checking at login

    Boston(config-line)#exit

    Moves back to global config mode

    Boston(config)#no service password-encryption

    Turns off password encryption

    Boston(config)#int fa 0/0

    Moves to Fast Ethernet 0/0 mode

    Boston(config-if)#desc Engineering LAN

    Sets locally significant description of the interface

    Boston(config-if)#ip address 172.16.10.1 255.255.255.0

    Assigns IP address and subnet mask to the interface

    Boston(config-if)#no shut

    Turns on the interface

    Boston(config-if)#int s0/0

    Moves directly to Serial 0/0 mode

    Boston(config-if)#desc Link to Buffalo Router

    Sets locally significant description of the interface

    Boston(config-if)#ip address 172.16.20.1 255.255.255.0

    Assigns IP address and subnet mask to the interface

    Boston(config-if)#clock rate 56000

    Sets a clock rate for serial transmission. DCE cable must be plugged into this interface

    Boston(config-if)#no shut

    Turns on the interface

    Boston(config-if)#exit

    Moves back to global config mode

    Boston(config)#ip host buffalo 172.16.20.2

    Sets a local host name resolution to IP address 172.16.20.2

    Boston(config)#exit

    Moves back to privileged mode

    Boston#copy run start

    Saves running-config to NVRAM

     

    Wednesday, April 2, 2008

    Erasing Configurations – Networking How-to

    Erasing Configurations

    Router#erase start

    Deletes the startup-config file from NVRAM


    Tip:

    Running-config is still in dynamic memory. Reload the router to clear the running-config.

    Tuesday, April 1, 2008

    Saving Configurations – Networking How-to

    Saving Configurations

    Router#copy run start

    Saves the running-config to local NVRAM

    Router#copy run tftp

    Saves the running-config remotely to TFTP server

    exec-timeout Command – Networking How-to

    exec-timeout Command

    Router(config)#line con 0


    Router(config-line)#exec-timeout 0 0

    Sets time limit when console automatically logs off. Set to 0 0 (minutes seconds) means console never logs off

    Router(config-line)#



    Tip:

    exec-timeout 0 0 is great for a lab because the console never logs out. This bad security is very dangerous in the real world.

    Monday, March 31, 2008

    logging synchronous Command – Networking How-to

    logging synchronous Command

    Router(config)#line con 0

    Router(config-line)#logging synchronous

    Turns on synchronous logging. Information items sent to console will not interrupt the command you are typing. The command will be moved to a new line


    Tip:

    Ever try to type in a command and an informational line appears in the middle of what you were typing? Lose your place? Do not know where you are in the command, so you just press Enter and start all over? The logging synchronous command will tell the router that if any informational items get displayed on the screen, your prompt and command line should be moved to a new line, so as not to confuse you.

    The informational line does not get inserted into the middle of the command you are trying to type. If you were to continue typing, the command would execute properly, even though it looks wrong on the screen.

    Sunday, March 30, 2008

    no ip domain-lookup Command

    Router(config)#no ip domain-lookup Router(config)#

    Turns off trying to automatically resolve an unrecognized command to a local host name


    Tip:

    Ever type in a command incorrectly and are left having to wait for a minute or two as the router tries to translate your command to a domain server of 255.255.255.255? The router is set by default to try to resolve any word that is not a command to a DNS server at address 255.255.255.255. If you are not going to set up DNS, turn this feature off to save you time as you type, especially if you are a poor typist.


    Monday, March 17, 2008

    Assigning a Local Host Name to an IP Address – Networking How-to

    Assigning a Local Host Name to an IP Address

    Router(config)#ip host london 172.16.1.3

    Assigns a host name to the IP address. After this assignment, you can use the host name instead of an IP address when trying to Telnet or ping to that address

    Router#ping london

    =

    Router#ping 172.16.1.3

     

    Tip:

    The default port number in the ip host command is 23, or Telnet. If you want to Telnet to a device, just enter the IP host name itself:

    Router#london = Router#telnet london = Router#telnet 172.16.1.3

    Sunday, March 16, 2008

    Setting the Clock Time Zone on a Cisco Router – Networking How-to

    Setting the Clock Time Zone

    Router(config)#clock timezone EST 5

    Sets the time zone for display purposes. Based on coordinated universal time (Eastern Standard Time is 5 hours behind UTC)

    Thursday, March 13, 2008

    Creating an MOTD Banner on a Router – Networking How-to

    Creating an MOTD Banner

    Router(config)#banner motd # This is a secure system. Authorized Personnel Only! # Router(config)#

    # is known as a delimiting character. The delimiting character must surround the banner message and can be any character so long as it is not a character used within the body of the message

    Wednesday, March 12, 2008

    Configuring an Ethernet/Fast Ethernet Interface on a Router – Networking How-to

    Configuring an Ethernet/Fast Ethernet Interface

    Router(config)#int fa0/0

    Moves to Fast Ethernet 0/0 interface mode

    Router(config-if)#description Accounting LAN

    Optional descriptor of the link is locally significant

    Router(config-if)#ip address 192.168.20.1 255.255.255.0

    Assigns address and subnet mask to interface

    Router(config-if)#no shut

    Turns interface on

    Tuesday, March 11, 2008

    Configuring a Serial Interface on a Cisco Router – Networking How-to

    Configuring a Serial Interface

    Router(config)#int s0/0

    Moves to interface Serial 0/0 mode

    Router(config-if)#description Link to ISP

    Optional descriptor of the link is locally significant

    Router(config-if)#ip address 192.168.10.1 255.255.255.0

    Assigns address and subnet mask to interface

    Router(config-if)#clock rate 56000

    Assigns a clock rate for the interface

    Router(config-if)#no shut

    Turns interface on

    Tip:

    The clock rate command is used only on a serial interface that has a DCE cable plugged into it. There must be a clock rate set on every serial link between routers. It does not matter which router has the DCE cable plugged into it, or which interface the cable is plugged into. Serial 0 on one router can be plugged into Serial 1 on another router.

    Sunday, March 9, 2008

    Moving Between Router Interfaces – Networking How-to

    Moving Between Interfaces

    What happens in Column 1 is the same thing occurring in Column 2.

    Router(config)#int s0

    Router(config)#int s0

    Moves to interface S0 mode

    Router(config-if)#exit

    Router(config-if)#int e0

    In int S0, move to E0

    Router(config)#int e0

    Router(config-if)#

    In E0 mode now

    Router(config-if)#


    Prompt does not change; be careful

    Thursday, March 6, 2008

    Interface Names on a Cisco Router – Networking How-to

    Interface Names

    One of the biggest problems that new administrators face is the interface names on the different models of routers. With all of the different Cisco devices that are in production networks today, some administrators are becoming confused on the names of their interfaces.

    The following chart is a sample of some of the different interface names for various routers. This is by no means a complete list. Refer to the hardware guide of the specific router that you are working on to see the different combinations, or use the following command to see which interfaces are installed on your particular router:

    router#show ip interface brief

    Router Model

    Port Location/Slot Number

    Slot/Port Type

    Slot Numbering Range

    Example

    2501

    On Board

    Ethernet

    Interface-type Number

    ethernet0 (e0)

    On Board

    Serial

    Interface-type Number

    serial0 (s0) & s1

    2514

    On Board

    Ethernet

    Interface-type Number

    e0 & e1

    On Board

    Serial

    Interface-type Number

    s0 & s1

    1721

    On Board

    FastEthernet

    Interface-type Number

    fastethernet0 (fa0)

    Slot 0

    WAC (WIN Interface Card) (Serial)

    Interface-type Number

    s0 & s1

    1760

    On Board

    Fast Ethernet

    Interface-types 0/port

    fa0/0

    Slot 0

    WIC/VIC (Voice Interface Card)

    Interface-type 0/port

    s 0/0 & s0/1

    v0/0 & v0/1

    Slot 1

    WIC/VIC

    Interface-type 1/port

    s1/0 & s1/1

    v1/0 & v1/1

    Slot 2

    VIC

    Interface-type 2/port

    v2/0 & v2/1

    Slot 3

    VIC

    Interface-type 3/port

    v3/0 & v3/1

    2610

    On Board

    Ethernet

    Interface-type 0/port

    e0/0

    Slot 0

    WIC (Serial)

    Interface-type 0/port

    s0/0 & s0/1

    2611

    On Board

    Ethernet

    Interface-type 0/port

    e0/0 & e0/1

    Slot 0

    WIC (Serial)

    Interface-type 0/port

    s0/0 & s0/1

    2620

    On Board

    FastEthernet

    Interface-type 0/port

    fa0/0

    Slot 0

    WIC (Serial)

    Interface-type 0/port

    s0/0 & s0/1

    2621

    On Board

    FastEthernet

    Interface-type 0/port

    fa0/0 & fa 0/1

    Slot 0

    WIC (Serial)

    Interface-type 0/port

    s0/0 & s0/1

    1841

    On Board

    FastEthernet

    Interface-type 0/port

    fa 0/0 & fa 0/1

    Slot 0

    High Speed WAN Interface Card (HWIC)/WIC/VWIC

    Interface-type 0/slot/port

    s0/0/0 & s0/0/1

    1841

    Slot 1

    HWIC/WIC/VWIC

    Interface-type 0/slot/port

    s0/1/0 & s0/1/1

    2801

    On Board

    FastEthernet

    Interface-type 0/port

    fa0/0 & fa 0/1

    Slot 0

    VIC/VWIC (voice only)

    Interface-type 0/slot/port

    voice0/0/0 voice0/0/3

    Slot 1

    HWIC/WIC/VWIC

    Interface-type 0/slot/port

    0/1/0 0/1/3 (single-wide HWIC) 0/1/0 0/1/7 (double-wide HWIC)

    Slot 2

    WIC/VIC/VWIC

    Interface-type 0/slot/port

    0/2/0 – 0/2/3

    Slot 3

    HWIC/WIC/VWIC

    Interface-type 0/slot/port

    0/3/0 0/3/3 (single-wide HWIC) 0/3/0 – 0/3/7 (double-wide HWIC)

    2811

    Built into Chassis Front

    USB

    Interface-type port

    usb0 & usb 1

    Built into Chassis Rear

    FastEthernet Gigabit Ethernet

    Interface-type 0/port

    fa0/0 & fa 0/1

    gi0/0 & gi0/1

    Slot 0

    HWIC/HWIC-D/WIC/VWIC/VIC

    Interface-type 0/slot/port

    s0/0/0 & s0/0/1

    fa0/0/0 & 0/0/1

    Slot 1

    HWIC/HWIC-D/WIC/VWIC/VIC

    Interface-type 0/slot/port

    s0/1/0 & s0/1/1

    fa0/1/0 & 0/1/1

    NME Slot

    NM/NME

    Interface-type 1/port

    gi1/0 & gi1/1

    s1/0 & s1/1


    Wednesday, March 5, 2008

    Show Commands on Cisco Routers – Networking How-to

    show Commands

    Router#show ?

    Lists all show commands available

    Router#show interfaces

    Displays statistics for all interfaces

    Router#show interface serial 0

    Displays statistics for a specific interface, in this case Serial 0

    Router#show ip interface brief

    Displays a summary of all interfaces, including status and IP address assigned

    Router#show controllers serial 0

    Displays statistics for interface hardware. Statistics display if the clock rate is set and if the cable is DCE, DTE, or not attached

    Router#show clock

    Displays time set on device

    Router#show hosts

    Displays local host-to-IP address cache. These are the names and addresses of hosts on the network to which you can connect

    Router#show users

    Displays all users connected to device

    Router#show history

    Displays history of commands used at this edit level

    Router#show flash

    Displays info about Flash memory

    Router#show version

    Displays info about loaded software version

    Router#show arp

    Displays the ARP table

    Router#show protocols

    Displays status of configured Layer 3 protocols

    Router#show startup-config

    Displays configuration saved in NVRAM

    Router#show running-config

    Displays configuration currently running in RAM

    Tuesday, March 4, 2008

    Password Encryption on a Router/Switch – Networking How-to

    Password Encryption

    Router(config)#service password-encryption

    Applies a weak encryption to passwords

    Router(config)#enable password cisco

    Sets enable password to cisco

    Router(config)#line con 0

    Router(config-line)#password Cisco

    Continue setting passwords as above


    Router(config)#no service password-encryption

    Turns off password encryption

    Caution:

    If you have turned on service password encryption, used it, and then turned it off, any passwords that you have encrypted will stay encrypted. New passwords will remain unencrypted.

    Monday, March 3, 2008

    Configuring Passwords on a Cisco Router – Networking How-to

    Configuring Passwords

    Works on both routers and switches.


    Router(config)#enable password cisco Sets enable password

    Router(config)#enable secret class Sets enable secret password

    Router(config)#line con 0 Enters console-line mode
    Router(config-line)#password console Sets console-line mode password to console
    Router(config-line)#login Enables password checking at login

    Router(config)#line vty 0 4 Enters vty line mode for all five vty lines
    Router(config-line)#password telnet Sets vty password to telnet
    Router(config-line)#login Enables password checking at login

    Router(config)#line aux 0 Enters auxiliary line mode
    Router(config-line)#password backdoor Sets auxiliary line mode password to backdoor
    Router(config-line)#login Enables password checking at login

     

    Caution:

    enable secret password is encrypted by default. enable password is not. For this reason, recommended practice is that you never use the enable password. Use only the enable secret password in a router configuration.

    Caution:

    You cannot set both enable secret and enable password to the same password. Doing so defeats the use of encryption.

    Sunday, March 2, 2008

    Networking How-to: Configuring a Router Name

    This command works on both routers and switches.

    Router(config)#hostname Cisco

    Name can be any word you choose

    Cisco(config)#

    Networking How-to: Cisco Router Modes

    Router Modes

    Router>

    User mode

    Router#

    Privileged mode

    Router(config)#

    Global configuration mode

    Router(config-if)#

    Interface mode

    Router(config-subif)#

    Subinterface mode

    Router(config-line)#

    Line mode

    Router(config-router)#

    Router configuration mode


    Tip:

    There are other modes than these. Not all commands work in all modes. Be careful. If you type in a command that you know is correctshow run, for exampleand you get an error, make sure that you are in the correct mode.

    Configuration Example: RIP-2 Routing

    Figure A shows the network topology for the configuration that follows, which shows how to configure RIP-2 using the commands covered in this chapter.

     

    Figure 8-1. Network Topology for RIP-2 Routing Configuration

    Boston Router

    Boston>en

    Boston#config t

    Boston(config)#router rip

    Enables RIP routing

    Boston(config-router)#version 2

    Enables RIP-2

    Boston(config-router)#network 172.16.0.0

    Advertises directly connected networks (classful address only)

    Boston(config-router)#no auto-summary

    Turns off autosummarization

    Boston(config-router)#exit

    Boston(config)#exit

    Boston#copy run start


    Buffalo Router

    Buffalo>en

    Buffalo#config t

    Buffalo(config)#router rip

    Enables RIP routing

    Buffalo(config-router)#version 2

    Enables RIP-2

    Buffalo(config-router)#network 172.16.0.0

    Advertises directly connected networks (classful address only)

    Buffalo(config-router)#no auto-summary

    Turns off autosummarization

    Buffalo(config-router)#Cntl+z

    Exits back to privileged mode

    Buffalo#copy run start


    Bangor Router

    Bangor>en

    Bangor#config t

    Bangor(config)#router rip

    Enables RIP routing

    Bangor(config-router)#version 2

    Enables RIP-2

    Bangor(config-router)#network 172.16.0.0

    Advertises directly connected networks (classful address only)

    Bangor(config-router)#no auto-summary

    Turns off autosummarization

    Bangor(config-router)#Cntl+z

    Exits back to privileged mode

    Bangor#copy run start

    Sunday, April 20, 2008

    RIP Version 2: Optional Commands

    RIP Version 2: Optional Commands

    Router(config-router)#no version 2

    Changes back to RIP-1

    Router(config-router)#version 1

    Changes RIP routing to RIP-1

    Router(config-router)#no auto-summary

    RIP-2 summarizes networks at the classful boundary. This command turns autosummarization off

    Router(config-router)#auto-summary

    Re-enables autosummarization at the classful boundary


    Thursday, April 17, 2008

    RIP Version 2: Mandatory Commands Networking How-to

    RIP Version 2: Mandatory Commands

    Router(config)#router rip

    Turns on the RIP routing process; the same command as used for RIP Version 1 (RIP-1)

    Router(config-router)#version 2

    Turns on Version 2 of the routing process. Version 1 is default

    Router(config-router)#network w.x.y.z

    w.x.y.z is the network number of the directly connected classful network you want to advertise

    Wednesday, April 16, 2008

    Troubleshooting RIP Networking How-to

    Troubleshooting RIP Issues

    Router#debug ip rip

    Displays all RIP activity in real time

    Router#show ip rip database

    Displays contents of the RIP database


    Tuesday, April 15, 2008

    RIP Version 2 Networking How-to

    RIP Version 2

    Note:

    RIP-2 is not currently part of the CCNA certification exam. Commands are listed here for reference only.


    Router(config-router)#version 2

    RIP will now send and receive RIP-2 packets globally

    Router(config-if)#ip rip send version 1

    Interface will send only RIP-1 packets

    Router(config-if)#ip rip send version 2

    Interface will send only RIP-2 packets

    Router(config-if)#ip rip send version 1 2

    Interface will send both RIP-1 and RIP-2 packets

    Router(config-if)#ip rip receive version 1

    Interface will receive only RIP-1 packets

    Router(config-if)#ip rip receive version 2

    Interface will receive only RIP-2 packets

    Router(config-if)#ip rip receive version 1 2

    Interface will receive both RIP-1 and RIP-2 packets


    Monday, April 14, 2008

    RIP Routing: Optional Commands Networking How-to


    RIP Routing: Optional Commands

    Router(config)#no router rip

    Turns off the RIP routing process

    Router(config-router)#no network w.x.y.z

    Removes network w.x.y.z from the RIP routing process

    Router(config-router)#passive-interface s0/0

    RIP updates will not be sent out this interface

    Router(config-router)#neighbor a.b.c.d

    Defines a specific neighbor with which to exchange information

    Router(config-router)#no ip split-horizon

    Turns off split horizon (on by default)

    Router(config-router)#ip split-horizon

    Re-enables split horizon

    Router(config-router#timers basic 30 90 180 270 360

    Changes timers in RIP:

    30 = Update timer (in seconds)

    90 = Invalid timer (in seconds)

    180 = Hold-down timer (in seconds)

    270 = Flush timer (in seconds)

    360 = Sleep time (in milliseconds)

    Router(config-router)#maximum-paths x

    Limits the number of paths for load balancing to x (4 = default, 6 = maximum)

    Router(config-router)#default-information originate

    Generates a default route into RIP


    RIP Routing: Mandatory Commands Networking How-to

    RIP Routing: Mandatory Commands

    Router(config)#router rip

    Enables RIP as a routing protocol

    Router(config-router)#network w.x.y.z

    w.x.y.z is the network number of the directly connected network you want to advertise


    Note:

    You need to advertise only the classful network number, not a subnet:

    Router(config-router)#network 172.16.0.0


    not

    Router(config-router)#network 172.16.10.0


    If you advertise a subnet, you will not receive an error message, because the router will automatically convert the subnet to the classful network address.

    Thursday, April 10, 2008

    IP Classless Command Networking How-to

    IP Classless

    Router(config)#ip classless

    Instructs IOS to forward packets destined for an unknown subnet to the best supernet route

    Router(config)#no ip classless

    Turns off the ip classless command

    Note:
    A supernet route is a route that covers a range of subnets with a single entry.


    Note:
    The ip classless command is enabled by default in Cisco IOS Software Release 11.3 and later.

    Figure A. Network Topology for Basic Router Configuration

    Figure A shows the network topology for the configuration of VTP and inter-VLAN routing. There are separate sections on configuring both 2900 and 2950 series switches.

    Figure A. Network Topology for VTP and Inter-VLAN Routing Configuration

    Welcome to the first in what I hope will be a series of quick tips and tricks collections. These collections will consist of one and two line commands that don’t warrant entire stand-alone tips to be written for them.

    These tips are in no particular order….

    Watch a log file as its appended to

    tail -f logfile

    Redirect a man page to a file

    man whatever | col -b > whatever.out

    Allow a command to continue execution after logout

    nohup mycommand &

    Extract tarball when tar has no z option

    gzip -dc mytarball.tar.gz | tar xvf -

    Display one particular line from a file

    set linenumber = 8  # tcsh
    linenumber=8        # ksh
    sed -n "${linenumber}p" filename

    Display current runlevel

    who -r

    Split lines of text into n-char lines

    echo "some line of chars" | fold -w 3

    Temporary directories

    # /tmp gets cleared at boot, whereas /var/tmp does not

    Insert spaces at beginning of each line in vi

    :5,16s/^/   /    # for lines 5 through 16, for example

    Make init re-examine /etc/inittab

    init q

    Find out MAC address

    arp `uname -n`     # as regular user
    ifconfig -a        # ethernet address only displayed when run as root

    Display last 10 system reboots

    last reboot | head

     

    Set backspace to do the right thing

    stty erase ^H # sometimes ^? - just do stty erase <hit backspace here!>

    Linux – display /proc information

    procinfo -a

    Solaris – display processor information

    /usr/sbin/psrinfo -v
    /usr/platform/`uname -i`/sbin/prtdiag | sed -n '/CPUs/,/Mem/p' | sed '/==/d'

    Solaris – display memory information

    /usr/sbin/prtconf | grep "Memory"

    Solaris – display system information

    /usr/platform/`uname -i`/sbin/prtdiag | more
    /usr/sbin/prtconf | more

    Solaris – find out whether kernel modules are 32 or 64-bit

    /usr/bin/isainfo -kv

    Solaris – kill all matching processes – e.g. all “tip” processes

    pgrep -l tip         # check output....
    pkill -x tip         # -x to kill only full searchterm matched processes
    # for linux - man killall

    Solaris – get syslogd to re-read config

    pkill -HUP syslogd

    Solaris – display numeric uid

    /usr/xpg4/bin/id -u username

    Solaris – crude halt….

    sync;sync;sync;halt
    
    These tips are in no particular order.... 
    
    CDE: Start a dtterm and log it
    
    dtterm -l -lf $HOME/logs/`date +%d%m%y`.log &

    Truss a process from start of execution

    truss -f -wall -rall -vall whatever

    Truss an already running process and output to file

    ps -ef | grep myprocess   # find pid
    truss -f -wall -rall -vall -o outputfile -p pid

    Execute command as different user

    su - username -c "my;commands;here"

    Stop users logging in

    # kill user processes; then
    touch /etc/nologin

    Set correct permissions on /tmp

    chmod 1777 /tmp
    ls -lad /tmp         # just checking!

    View NIS hosts and passwd files

    ypcat hosts
    ypcat passwd

    Editing crontab

    Only use crontab -e - signals change to cron daemon

    Check which processes are listening on which ports

    lsof -i | grep LISTEN

    Print range of lines from a file

    sed -n '100,200 p' filename

    du without mountpoint traversal

    du -kd /

    tcsh: redirect stderr only – stupid c-based shells!

    ( command_here >/dev/tty ) >& /dev/null

    tcsh: Stop any alias from being evaluated

    \rm -rf /    # i.e. preceed with backslash

    Move last file modified

    mv `ls -1 -t *.txt | head -1` whatever.txt

    Get to telnet prompt from a telnet session

    Ctrl-]  # usually....

    Disable ftp login for a user

    echo "banned_username" >> /etc/ftpusers

    ksh: Debug a script

    ksh -x ./some_ksh_script.ksh

    ksh: Set up r alias – see my article on customising your home environment for details (see /etc)

    alias r='fc -e -'

    ksh: Remove extensions from filenames

    for file in *.ext; do
      mv $file ${file%%.*}
    done

    Bourne-type shells: Find a file’s hard links

    inode=`ls -li /path/and/filename | awk '{print $1}'`
    find / -inum $inode -exec ls -li {} \;

    ksh: Access positional parameters

    $1 $2               # and so on, up to and including 9th param
    ${10} ${11}			# params >= 10

    ksh: Substitute old for new in current pwd then cd

    cd old new
    e.g.
    $ pwd
    /path/to/foo/here
    $ cd foo bar
    /path/to/bar/here

    Linux: Make image of floppy disk

    dd if=/dev/fd0 of=/path/to/my/new.img
    
    Tail the newest file in a directory
    
    tail -f `ls -1rt | tail -1`

    Find out which application caused a core dump

    file /some/path/to/core

    Sybase – Check status of databases

    # su - sybase
    Password:
    > isql -Usa -Ppassword -w200
    1> use master
    2> go
    1> select status, name from sysdatabases
    2> go

    Convert single column into two columns line by line

    $ cat foofile
    a
    b
    c
    d
    e
    f
    $ paste -d: - - < foofile
    a:b
    c:d
    e:f

    gunzip and untar with one pipe

    gzip -dc SOMEFILE.tar.gz | tar xvf -
    # or with GNU tar
    tar xvzf SOMEFILE.tar.gz

    Solaris: Standard UNIX ping

    ping -s xxx.xxx.xxx.xxx

    Simple command line arithmetic

    echo " ( 10 + 20 ) / 15 " | bc

    Solaris: Mount an ISO image located on NFS share

    # mount -F nfs ip_address:/path/to/iso/store /mnt
    # lofiadm -a /mnt/my_iso.iso
    /dev/lofi/1
    # mount -F hsfs /dev/lofi/1 /mnt2
    # ls /mnt2
    ...

    Solaris: Set server to automatically boot

    # Note - to reverse this either use eeprom or just bust
    # out with Stop-A
    
    # init 0
    ok printenv                # check auto-boot?
    ok setenv auto-boot? true
    ok boot

    Quickly copy a directory tree with tar

    cd /path/to/source
    tar cvf - ./* | ( cd /dest; tar xvf - )

    Access the local shell from an ftp session

    # note - this depends on your ftp client
    ftp> !
    $ echo "Now in local shell"

    Truncate a log file

    # note - you might need to restart whichever process is
    # writing to the file... kill -HUP some_pid may be appropriate
    > /log/file
    # or
    cat /dev/null > /log/file

    Solaris: Non-interactive pkgadd without admin files

    pkgadd -d ${PKG_PATH} ${PKG} <<EOF
    y
    y
    EOF
    # obviously, your supplied input may need to be adjusted

    Solaris: Check loaded kernel modules

    modinfo | grep -i "whatever"

    Add stuff to beginning or end of every line

    sed 's/^/stuff/' file > newfile    # at the beginning
    sed 's/$/stuff/' file > newfile    # at the end

    Solaris: Screwy vi behaviour when using console

    # set TERM properly...
    TERM=sun-cmd
    export TERM

    ksh: Using local environment file

    # Ensure that you enter the following in your $HOME/.profile file
    ENV=${HOME}/.kshrc
    export ENV

    Create tar archives where files have absolute paths

    tar cvf foo.tar /path/to/files

    Create tar archives where files have relative paths

    cd /path/to
    tar cvf foo.tar ./files

    Check if two files are hardlinked

    ls -li file1 file2  # are inode numbers the same and the files
                        # residing on the same filesystem?

    Recursive grep without GNU grep

    find / -type f -name "*foo*" -exec grep "bar" {} /dev/null \; -print

    Replace spaces in filenames with underscores

    ls | while read file; do
      mv "${file}" `echo "${file}" | tr ' ' '_'`
    done
    
    see differences between two files
    
    diff file_1 file_2
    # also see
    man comm

    count processes running on system (-1 to remove header)

    echo $((`ps -ef | wc -l` - 1))

    recursive wget

    cd /where/to/put/files; wget -r http://somewhere.com/somedir

    check number of fields on each line (delimited by |)

    awk 'BEGIN {FS="|"} {print NF}' somefile

    perform verbose nmap scan

    nmap -v hostname

    perform UDP scan

    nmap -sU -v hostname

    renice a process to increase priority

    renice -10 -p 123

    remove all .log files in /tmp that haven’t been modified in over two days

    find /tmp -type f -name "*.log" -mtime +2 -exec rm -rf '{}' \;

    indent output from a command

    my_command | sed 's/^/   /'

    Print last four characters in each line

    awk '{printf("%s\n",substr($0,length($0)-3))}' foofile

    output man page to file

    man foo | col -b > outfile

    view man page that’s not yet installed

    nroff -man man_file | more

    show unprintable characters with cat

    cat -vET somefile

    ls -l sorted by filesize

    ls -l | sort -k5,5rn

    extract a single file from a tar

    tar cvf foo.tar single_file

    ksh/bash change to previous directory

    cd -

    bash / ksh95 variable pattern substitution

    $ FOO="bash"
    $ echo "${FOO/ba/k}"
    ksh

    my standard useradd line

    useradd -m -d /home/kwaldron -c "Kevin Waldron" -s "/bin/ksh" kwaldron && passwd kwaldron

    perform snmpwalk of localhost

    snmpwalk -v 1 localhost -c community_string | more

    ksh – left pad numbers with zeros

    $ typeset -Z8 foo
    $ foo=1234
    $ echo $foo
    00001234

    find files larger than 300k

    find / -size +300k -ls 2> /dev/null

    find two different types of file extensions

    find . \( -name "*.c" -o -name "*.c" \) -print

    remove the first character from a variable

    $ foo=12345
    $ echo "${foo#?}"
    2345

    find what program has caused a core file

    file /path/to/core

    convert from ebcdic to ascii

    dd if=/yourdir/your-ebcdicfile of=/yourdir/your-asciifile conv=ascii

    replace current process with another (i.e. don’t fork, just exec)

    exec newprocess

    display unprintable filenames

    ls -lb somedir

    correct permissions on /tmp and /var/tmp

    chmod 1777 /var/tmp
    # or
    chmod a=rwx,+t /var/tmp

    recover corrupt terminal

    stty sane
    echo "^O" 	# Ctrl-V Ctrl-O

    ring the terminal bell

    /usr/bin/echo "\a"

    bash substitution in previous command

    ls
    ^l^p
    ps

    crontab location

    /var/spool/cron/crontabs	# solaris
    /var/spool/cron			# linux

    GNU grep

    # show 2 lines either side of match
    grep -C 2 "somestring" filename
    # show 2 lines after match
    grep -A 2 "somestring" filename
    # show 2 lines before match
    grep -B 2 "somestring" filename

    grep for a word

    grep "\<something\>" somefile

    GNU sed relative addressing

    sed -n '/searchstring/,+2 p' filename
    # i.e. to print line containing searchstring plus the next two lines

    convert dos file to unix (remove carriage returns)

    dos2unix < infile.dos > outfile.unix  # dos2ux on HP-UX
    tr -d '\r' < infile.dos > outfile.unix
    # the unix2dos command (ux2dos) exists for the opposite conversion
    # or just ftp the file in ascii mode in the first place, but beware that
    # all sftp transfers are binary only

    searching for a literal $ in a file

    grep '\$' filename
    # or fgrep / grep -F
    fgrep '$' filename

    bash – funky curly brace substitution

    ls file{1,3,4}
    # to list file1 file3 and file4

    ksh – alias r

    alias r='fc -e -'
    # then
    r vi
    # will execute last vi command

    copy directory tree

    cd /src; tar cvf - ./* | ( cd /dest; tar xvpf - )
    cd /src; find . -depth -print | cpio -pvdum /dest

    show OS and kernel info

    uname -a

    wc -l without the filename

    wc -l < filename
    # or
    wc -l filename | awk '{print $1}'
    # as opposed to
    wc -l filename

    list mounts

    mount		# no arguments
    df -k

    show my history

    history

    disregard alias

    # rm -r dir
    rm: descend into directory `dir'? n
    # \rm -r dir

    su and inherit user environment

    su - [ user ] [ -c "commands ]

    set terminal type

    export TERM=vt100

    ksh – concise tests

    [[ -f foo ]] || {
      echo "Foo doesn't exist" >&2
      exit 2
    }

    traceroute using ICMP

    traceroute -I destination

    using last argument of previous command in bash

    $ echo foohost
    foohost
    $ ping !$
    ping foohost
    .
    .
    .

    make an alias global for all users

    - add entry to /etc/profile

    check for listening ports

    netstat -an | grep LISTEN

    define sendmail smarthost for relaying in sendmail.cf

    DSsomehost.foodomain.com

    copy, preserving permissions, ownership and timestamps

    cp -p source dest
    # recursively too
    cp -Rp source dest

    create soft link

    ln -s file_to_link link_name
    # hard link
    ln file_to_link link_name

    create directories including non-existent parents

    mkdir -p /some/lengthy/dir/tree

    recursive chown

    chown -R user:group /some/dir

    recursive chmod

    chmod -R 744 somedir

    cut the last character from a string

    a="somestring"
    echo ${a} | cut -c${#a}
    # other ways to do this
    echo "${a#${a%?}}"
    # or
    echo "${a}" | sed 's/.*\(.\)/1/'
    # or
    echo "${a}" | nawk '{print substr($0, length($0))}'
    # or
    expr "${a}" : '.*\(.\)'
    # or
    echo "${a}" | tail -2c

    truncate log file

    cp /dev/null logfile
    > logfile
    cat /dev/null > logfile
    # may need to restart
    kill -HUP `cat /var/run/syslog.pid`

    the true use of cat – to conCATenate files

    cat file1 file2 file3 > finalfile

    show subdirectories only in an ls listing

    ls -l | grep "^d"
    # recursively
    find . -type d -exec ls -ld {} \;

    show information about directory entry itself (not contents)

    ls -ld dir
    # show size
    ls -ls
    # show inode numbers
    ls -lia

    recursive grep

    find . -type f -exec grep "somestring" {} /dev/null \;

    sed to replace \ with \\

    sed -e 's_\\_\\\\_g'

    getent

    getent hosts hostname
    # using getent with ssh
    ssh -l admin `get hosts hostname | awk '{print $1}'`

    view available signals

    kill -l

    search for strings in a binary file

    strings binary_name

    show current runlevel

    who -r
    (or on some Linuxen - runlevel)

    show uptime and processor run queue averages

    uptime
    # or with who output
    w

    stop people logging in

    touch /etc/nologin

    temporarily change your prompt

    PS1='$ '
    export PS1

    bourne based shells – show current environment variables

    env
    # show all variables
    set
    # show shell options
    set -o
    # current shell options (set via set -x, etc)
    echo $-
    # bash
    shopt
    # show current shell
    echo $0

    filename completion ksh (vi mode)

    ESC-\

    check for interactive shell

    case $- in
      *i*)  echo "Interactive"
            ;;
      *)    echo "Not interactive"
            ;;
    esac

    find ip address for an interface

    /sbin/ifconfig interface | grep inet
    # e.g.
    /sbin/ifconfig bge0 | grep inet

    changing my primary group to one of my secondary groups

    $ groups
    kwaldron wheel
    $ grep kwaldron /etc/group
    wheel:x:10:root,kwaldron
    kwaldron:x:502:
    $ newgrp wheel
    $ id
    uid=502(kwaldron) gid=10(wheel) groups=10(wheel),502(kwaldron) context=user_u:system_r:unconfined_t

    gunzip and untar in one line

    gzip -dc foo.tar.gz | tar xvf -

    gzip and tar in one line

    tar cvf - ./* | gzip -c > foo.tar.gz

    with GNU tar this can happen in one command

    tar xzvf foo.tar.gz
    tar cvzf foo.tar.gz files
    tar tvzf foo.tar.gz
    etc...

    uncompress and untar

    zcat foo.tar.Z | tar xvf -

    find SUID files

    /usr/bin/find / -perm -4000 -exec /usr/bin/ls -ld {} \;

    find SGID files

    /usr/bin/find / -perm -2000 -exec /usr/bin/ls -ld {} \;

    find world writable files

    /usr/bin/find / -perm -0777 -exec /usr/bin/ls -ld {} \;
    # symbolic links will always be 77 so we can ignore them
    /usr/bin/find -perm -0777 ! -type l -exec /usr/bin/ls -ld {} \;

    remove files older than one week

    /usr/bin/find /some/dir -name "*whatever*" -mtime +7 | xargs rm

    find device files located where they shouldn’t be

    /usr/bin/find / \( -type b -o -type c \) | egrep -v 'proc|/dev'

    remove old core files (see Tip 0001 and Tip 0040)

    /usr/bin/find / -name core -mtime +7 -exec rm {} \;

    ksh/bash – damn emacs editing mode – turn it off!

    set +o emacs
    set -o vi

    remove duplicate occurrences of characters

    # echo "ssoommeetthhiinngg" | tr -s [a-z]
    something
    ## remove all occurrences of characters
    # echo "ssoommeetthhiinngg" | tr -d [m-z]
    eehhiigg

    check whois information for a domain

    whois -h whois.opensrs.net foo.com

    view dynamically linked library dependencies for a binary

    ldd /path/to/some/binary

    enable a service

    vi /etc/inetd.conf
    # then
    kill -HUP `cat /var/run/syslog.pid`
    # or (Solaris)
    kill -HUP `pgrep syslogd`

    remove a user, and their homedirectory

    userdel -r someuser

    check routing table

    netstat -rn

    check interfaces for collisions and errors, tx/rx packets, etc

    netstat -ivn
    # check for just one interface
    netstat -ivn -I eth0

    check NTP status

    ntpq -p

    perform a verbose trace of NTP

    ntptrace -dv

    ksh arithmetic – very flexible about variables

    $ foo=1
    $ bar=20
    $ echo $(( foo + bar ))
    21
    $ echo $(( ${foo} + ${bar} ))
    21

    output to screen and file

    my_command | tee -a /some/file

    output to two files

    my_command | tee -a /some/file > /some/other/file

    append stderr and stdout to a file and then perform further actions

    some_command 2>&1 | tee -a some_file | some_other_command > some_other_file

    redirect stdout and stderr somewhere (in this case, /dev/null)

    some_command >/dev/null 2>&1

    place command in background

    # either
    some_command &
    # or
    some_command
    ^Z
    bg
    # can then view jobs
    jobs
    # and kill by job number
    kill %1

    line numbering

    nl -ba infile > outfile

    create 100kb file

    dd if=/dev/zero of=/some/file bs=1 count=100

    octal dump (show octal and ascii)

    od -bc somefile
    # use this to check a directory entry
    od -bc somedirectory

    show the arp cache

    arp -a

    view tracked alias cache (bash/ksh)

    hash

    clear tracked alias cache (bash/ksh)

    hash -r

    show all stty modes

    stty -a

    create a core dump

    stty intr ^\
    # then
    launch a process in the foreground and hit Ctrl-\

    ksh read-only variables

    # typeset -r somevar="something"
    # somevar="newval"
    ksh: somevar: is read only

    using at

    at now + 5 min
    at> ls
    at> ^D
    # then show list of jobs
    atq	# linux atq output less verbose, but with simpler job identifiers
    atrm 1135911587.a	# remove an at jon (Solaris)
    atrm 1			# ditto (Linux)

    remove crontab

    crontab -r

    list crontab

    crontab -l user	   # solaris
    crontab -u user -l # linux

    exporting X

    display_host# xhost +
    application_server# DISPLAY=mybox:0.0
    application_server# export DISPLAY
    application_server# somexprog &

    append a line to a file

    echo "new line" >> some_file

    apache control

    apachectl restart
    # or
    /etc/init.d/httpd restart
    # or
    /etc/init.d/httpd stop && /etc/init.d/httpd start

    take log of session

    script /my/log/file

    common vi(m) options

    # ignore case
    :set ic
    # line numbers
    :set num
    :set nonum
    # turn off search highlighting (VIM)
    :nohl
    # syntax highlight on (VIM)
    :sy on
    # show unprintable characters
    :set list

    view kernel message buffer

    dmesg

    check TCPD rules in /etc/hosts.{allow,deny}

    grep -v "^#" /etc/hosts.allow /etc/hosts.deny | grep -v "^[ 	]*$"

    disable HTTP TRACE in apache

    # vi /etc/httpd/conf/httpd.conf
    # grep Rewrite /etc/httpd/conf/httpd.conf
    RewriteEngine On
    RewriteCond %{REQUEST_METHOD} ^TRACE
    RewriteRule .* - [F]
    # apachectl restart

    get postfix to reload configuration

    postfix reload

    change user foo’s login name to bar

    usermod -l bar foo
    
    view Group membership
    
    $ id -Gn -- anyuser
    anyuser wheel

    tcpdump port 123 (ntp)

    tcpdump port 123

    disable SELinux protection for syslogd

    # setsebool -P syslogd_disable_trans 1        ;; -P to make change permanent
    # getsebool -a | grep sys
    syslogd_disable_trans --> active
    # getsebool syslogd_disable_trans
    syslogd_disable_trans --> active

    Display SELinux context in ls listings

    ls -lZ /some/dir

    Show all SELinux booleans

    getsebool -a

    is SELinux enabled?

    selinuxenabled && echo Yes
    # or
    # getenforce
    Enforcing

    view usb infomation

    lsusb
    cat /proc/bus/usb/devices

    submit a job for printing

    lp -d destination filename

    print cups status information

    lpstat

    xorg.conf

    /etc/X11/xorg.conf
    xorgconfig

    show partition table

    /sbin/fdisk -l /dev/cciss/c0d0p1

    check mouse is operational

    cat /dev/mouse       # then move the mouse

    perform a reverse DNS lookup

    host xxx.xxx.xxx.xxx dns_server_ip

    Linux screenshots

    # see http://www.troubleshooters.com/linux/index.htm
    import -window root -display servername:0 myfile01.pcx
    import -window root -geometry 640:480 -display servername:0 myfile01.pcx
    xwd -display servername:0 -root > myfile.dmp
    # can view with
    xwd | xwud

    show inode information for all files in a directory

    find . -type f -exec stat {} \;

    root .profile under Linux

    Most recent Linux distributions use a home directory for root of /root
    
    You can check this with
    # awk -vFS=':' '/^root/ {print $6}' /etc/passwd
    /root
    
    Again, most Linux distributions have root set up to use bash
    # awk -vFS=':' '/^root/ {print $7}' /etc/passwd
    /bin/bash
    
    If you look in roots home directory, you'll see .bash_profile
    # ls -la $HOME/.bash_profile
    -rw-r--r-- 1 root root 234 Jul 6 2001 /root/.bash_profile

    show multiple processor usage statistic

    mpstat 1 10 	# for ten iterations with 1 second interval

    make a file immutable

    chattr +i somefile

    shutdown your system

    init 0
    shutdown -h now
    # reboot
    init 6
    shutdown -r now

    grub – boot in single user mode

    # Hit the a key at the grub menu, then append 'single' to the list of
    # kernel arguments

    add a log entry via syslog (will be directed as dictated by rules in /etc/syslog.conf)

    # logger -p kern.error Test message
    # tail -1 /var/log/messages
    Dec 28 11:31:09 somehost root: Test message

    get account password summary for a user

    passwd -S username
    # e.g.
    # passwd -S kwaldron
    Password set, MD5 crypt
    # passwd -S ntop
    Password locked.

    Vixie cron – increments

    */5 * * * * command (would mean every five minutes)
    # Vixie cron - ranges
    10 0-5 * * * command (10 minutes past each hour from 00:10 'til 05:10)

    set global library path

    echo "/some/lib/path" >> /etc/ld.so.conf
    # then run....
    ldconfig
    # can also do this on a session/user basis with
    export LD_LIBRARY_PATH=${LD_LIBRARY_PATH}:/some/lib/path

    chfn – change finger information

    # e.g.
    /usr/sbin/useradd bob
    /usr/bin/chfn -f "Bob Smith" bob	# could also use usermod -c "Bob Smith"
    # set the encrypted password...
    /usr/sbin/usermon -p 'abcd$01834HFB1a' bob

    chsh can be used to change login shell

    chsh -l 	# will list shells available in /etc/shells

    curses based runlevel management

    ntsysv

    view CPU information

    cat /proc/cpuinfo

    view memory information

    cat /proc/meminfo

    check nic info

    cat /proc/net/nicinfo/eth0.info

    find out what type file is

    file filename

    module configuration file

    # RHEL3
    /etc/modules.conf
    # RHEL4
    /etc/modprobe.conf

    module commands

    lsmod
    insmod
    rmmod
    depmod
    modprobe

    remount a filesystem (e.g. mount read-only FS read-write)

    mount -o rw,remount /some/mountpoint

    mount an iso image

    mount -t iso9660 -o ro,loop /some/foo.iso /mnt

    grab last 10 lines of messages file

    su - root -c "tail /var/log/messages"

    use mii-tool on interface to gather link speed and duplex

    mii-tool eth0

    use ethtool for further information

    ethtool eth0

    set interface speed and duplex using ethtool

    ethtool -s eth0 speed 100 duplex full autoneg off

    display iptables policy

    iptables -L

    RHEL – display init.d scripts configured with chkconfig

    chkconfig --list
    # set script to start in runlevels 2, 3, 4 and 5
    chkconfig --level 2345 foosvc on
    # start the service
    service foosvc start

    display filehandle usage

    lsof

    show current runlevel

    runlevel

    show /proc info for HBA

    cat /proc/scsi/qla2300/0

    show top processes ignoring inactive and zombie (i.e. running on CPU only)

    top -i
    # run at highest priority with no delay
    top -q -i
    # using top in a script - batch mode
    top -b -n 1

    pstree – kind-of equivalent to ptree

    $ pstree -c -p -a -G PID
    # e.g. pstree of current shell process
    $ pstree -c -p -a -G $$
    bash,24195
      +-pstree,24858 -c -p -a -G 24195

    show filesystem types in df output

    df -kT

    define kernel parameters

    vi /etc/sysctl.conf
    man sysctl
    e.g.
    # /sbin/sysctl -a | grep shmmax
    kernel.shmmax = 33554432

    set hardware clock to system clock date and time

    hwclock --systohc

    display memory usage (in megabytes)

    free -m

    ssh as different user than currently logged in user

    ssh -l username hostname
    # or
    ssh username@hostname

    basic scp syntax

    scp /src/files user@host:/dest/path

    List users accessing mounted filesystem

    fuser -u /mnt

    Kill all processes accessing this filesystem

    fuser -km /mnt
    
    A big heap of (mostly) Solaris specific one-liners 
    
    copy ACL from one file to another
    
    getfacl file_one | setfacl -f - file_two

    Print all lp status information

    lpstat -t

    view the files that make up a Solaris package

    /usr/sbin/pkgchk -l SUNWcsr | grep Pathname | sed 's/Pathname: \(.*\)/\1/'

    check which package a file belongs to

    /usr/sbin/pkgchk -lp somefile

    snoop an interface for icmp

    snoop -d eri0 | grep -i icmp

    view a NIS+ map

    niscat passwd.org_dir
    # for NIS
    ypcat passwd

    backup to tape

    tar cvf /dev/rmt/0n /some/crap
    mt rew
    tar tvf /dev/rmt/0n
    mt rew
    tar xvf /dev/rmt/0n single_file

    Solaris 10 – list current zones

    /usr/sbin/zoneadm list -cv

    Solaris 10 – list current service state

    svcs -a

    Show extended information about a Solaris 10 service

    svcs -xv svc:/network/nfs/client

    Display all available information about a service

    svcs -l svc:/network/nfs/status:default

    List the services on which a Solaris 10 service depends

    svcs -d svc:/network/nfs/client

    List the services which depend on this Solaris 10 service

    svcs -D svc:/network/nfs/client

    View Solaris 10 inet services

    inetadm

    Convert new inetd.conf entries to new SMF format

    inetconf

    list users belonging to a group

    listusers -g groupname

    share a filesystem

    share /some/fs
    # then on another system
    mount -F nfs some_ip:/some/fs /some/mnt
    # when we're done
    umount /some/mnt
    # then back on original system
    unshare /some/fs

    find filesystem type

    fstyp /dev/dsk/c0t0d0s0

    set auto-boot to false

    ok setenv auto-boot? false
    # or
    eeprom 'auto-boot?=false'

    eject cdrom

    umount /cdrom/cdrom0
    eject cdrom
    # or if vold isn't running
    umount /mnt
    eject /dev/dsk/c0t6d0s0		(get this info from iostat -En)

    Solaris DHCP configuration table management utility

    dhtadm

    DHCP Graphical interface

    /usr/sadm/admin/bin/dhcpmgr

    solaris print manager

    /usr/sadm/admin/bin/printmgr

    solaris graphical configuration

    man fbconfig
    man m64config
    man kdmconfig		# ia86

    administer system controller

    /usr/platform/`uname -i`/sbin/scadm

    create windex with nohup -p

    # catman &
    [1] 2345
    # jobs
    [1] + Running    catman &
    # nohup -p 2345
    # exit

    boot Solaris 10 in verbose mode

    ok boot -m verbose

    view disabled services on Solaris 10

    svcs -a | grep disabled

    disable / enable telnet

    # disable telnet
    inetadm -d telnet
    # re-enable telnet
    inetadm -e telnet
    # or
    svcadm disable telnet
    svcadm -v enable -r telnet
    (-v verbose, -r recursively enable dependencies)
    # example
    # svcadm -v disable telnet
    svc:/network/telnet:default disabled.
    # svcadm -v enable -r svc:/network/ftp:default

    shutdown your system

    init 5
    shutdown -y -g0 -i5
    # reboot
    init 6
    shutdown -y -g0 -i6

    dynamically adding solaris interface

    ifconfig hme0 plumb
    ifconfig hme0 192.168.0.2 netmask 255.255.255.0 broadcast + up
    route add default 192.168.0.1
    # to make this permanent
    echo "hostname" > /etc/hostname.hme0
    echo "192.168.0.2" >> /etc/inet/hosts # on Solaris 10 - ensure you modify /etc/inet/ipnodes too
    echo "192.168.0.0 255.255.255.0" >> /etc/inet/netmasks
    echo "192.168.0.1" > /etc/defaultrouter
    init 6

    display tape drive status

    mt -f /dev/rmt/0 status

    find installed physical memory

    /usr/sbin/prtconf | grep Mem

    standard single user mode boot

    ok boot -s
    # or
    init s
    # or
    reboot -- -s

    power off

    init 5
    # or
    init 0
    power-off
    # or
    shutdown -y -i5 -g0

    single user mode cdrom boot

    stop-A
    # or
    init 0
    # then
    ok boot cdrom -s
    # on intel
    b -s (insert CD first, it will attempt to boot then give you a prompt)

    show configuration information (controllers)

    $ /usr/sbin/cfgadm
    Ap_Id                          Type         Receptacle   Occupant     Condition
    c0                             scsi-bus     connected    configured   unknown
    c1                             scsi-bus     connected    configured   unknown
    c2                             scsi-bus     connected    unconfigured unknown
    usb0/1                         unknown      empty        unconfigured ok
    usb0/2                         unknown      empty        unconfigured ok

    burning cd’s under Solaris (see Solaris 10 Devices and Filesystems guide on docs.sun.com )

    man cdrw
    man mkisofs

    truss a process that’s already running (see strace on Linux)

    truss -f -wall -rall -vall -o /some/outfile.out -p PID &

    show kernel parameters for an interface ( <= Solaris 9 only )

    netstat -k interface
    # e.g.
    netstat -k hme0

    ping using alternative interface

    ping -i bge1 somehost

    ping 5 x 64 byte packets

    ping -s somehost 64 5

    Just added a new device to the system?

    devfsadm   # pre Solaris 8 this was tapes, disks, drvconfig
    # or
    touch /reconfigure
    init 6
    # or
    reboot -- -rs
    # or
    init 0
    ok boot -rs

    mount an iso

    # lofiadm -a /path/to/foo.iso
    /dev/lofi/1
    # mount -F hsfs /dev/lofi/1 /mnt
    # umount /mnt
    # lofiadm -d /dev/lofi/1

    show uname information in SCO format

    uname -X

    grab system diagnostics information and variables

    /usr/platform/`uname -i`/sbin/prtdiag -v
    /usr/platform/`uname -i`/sbin/eeprom
    prtconf -D
    isainfo -kv			# show kernel module version
    pagesize 			# show pagesize
    psrinfo -v			# verbose processor information

    Show loaded kernel modules

    modinfo
    # other module commands
    modload
    modunload

    Finding network parameters of bge interfaces

    ndd -get /dev/bge0 link_status
    ndd -get /dev/bge0 link_speed
    ndd -get /dev/bge0 link_duplex

    check metadbs

    metadb

    check metastat

    metastat
    # view brief config snapshot
    metastat -p

    view swap information

    swap -l
    swap -s
    sar -r
    # view info n 5 samples at 5 second intervals
    sar -r 5 5

    make 100M swap file to temporarily fix swap issues

    mkfile 100m /export/swapfile
    swap -a /foo/swapfile
    swap -l
    swap -s
    # problem fixed - dodgy application patched or removed
    swap -d /foo/swapfile
    rm /foo/swapfile
    # if it needs to be made persistent, then add it to /etc/vfstab

    wide ps listing

    /usr/ucb/ps auwwwx

    get CLOSE_WAIT interval

    /usr/sbin/ndd -get /dev/tcp tcp_close_wait_interval

    see if IP Forwarding is enabled

    /usr/sbin/ndd -get /dev/tcp ip_forwarding

    view information on signals

    man -s3HEAD signal

    fsck (on RAW device)

    fsck /dev/rdsk/c1t1d0s0

    view errors on devices (an easy way to find out device name of CD/DVD drives)

    iostat -En

    display inode to filename mapping

    ff /dev/dsk/c1t1d0s0

    display which processes have a file open (also works on some Linux distros)

    fuser filename

    display which files a process has open

    pfiles PID
    pfiles `pgrep process_name`

    Solaris 9 and above – reap zombie process

    preap PID

    show who is doing what

    /usr/sbin/whodo

    iostat

    iostat interval iterations
    # e.g.
    iostat 1 10
    # same can be done with prstat and vmstat

    ptree – show parent/child process relationship

    ptree PID
    # e.g. for current shell
    ptree `pgrep $( echo $0 | tr -d '-' )`
    # or
    ptree `pgrep $( echo $0 | sed 's/-//' )`

    view current eeprom settings

    /usr/platform/`uname -i`/sbin/eeprom

    set MTU value for an interface

    ifconfig interface mtu n
    # e.g.
    ifconfig hme0 mtu 1500
    # place in hostname.interface file for persistence

    show patch revisions

    showrev -p
    patchadd -p

    show brief listing of installed packages

    pkginfo

    show long listing of installed packages

    pkginfo -l

    see package info on a package that’s not yet installed

    pkginfo -l -d /path/to/package.pkg

    get package params (may aswell just browse /var/sadm/pkg/PKGname/pkginfo)

    pkgparam SUNWcsr DESC

    open Solaris product registry

    prodreg

    send a nohup to an already running command (Solaris 10)

    nohup -p PID

    define kernel parameters (requires a reboot after changes)

    vi /etc/system

    view current system parameters

    sysdef | grep whatever
    # e.g.
    # sysdef | grep shar
    1572864000   max shared memory segment size
    100           shared memory identifiers (SHMMNI)
    60            maximum time sharing user priority (TSMAXUPRI)
    # grep shmmax /etc/system
    *set shmsys:shminfo_shmmax=1258291200
    set shmsys:shminfo_shmmax=1572864000

    find pid if you know process name

    pgrep some_process_name
    # or the obvious
    ps -ef | grep whatever
    # we can then ptree this
    ptree PID
    # or all in one
    ptree `pgrep process_name`
    
    Another bundle of miscellaneous one-liners (Misc OS's....) 
    
    show process listing for single username
    
    ps -fu username

    print all lines between two search terms (inclusive)

    sed -n '/acd/,/anz/ p' file.dat

    Solaris – show multiple processor statistics

    mpstat 1 10

    remove digits from a string

    echo "abcd01234" | tr -d [0-9]

    view MX record(s) for a domain

    dig MX foo.com

    GNU tar + bzip + exclude

    tar cvpjf backup.tar.bz2 / --exclude /proc /dev /mnt /sys /media

    create iso image

    dd if=/dev/cdrom of=/some/iso.iso bs=512

    # /etc/issue displayed before login
    # /etc/motd display after login

    ls by size in descending order

    ls -la | sort -k5,5rn

    show RPC info on a remote host (probe portmapper)

    # rpcinfo -p remote.ip

    output man page to file

    man something | col -b > man.out

    Add line numbers to a file

    nl -ba < infile > outfile

    Run syslog in Debug mode

    /usr/sbin/syslogd -d

    manual page detailing hosts.allow hosts.deny

    man 5 hosts_access

    display ps forest

    ps -axf

    recursively change permissions on directories only

    find . -type d -exec chmod 755 {} \; -print 2>/dev/null

    list specific users process info

    lsof -u username

    iconv convert between codesets

    iconv -f UTF-8 -t iso85591 somefile

    grab sar stats for specific time range

    sar -A -s 19:40 -e 20:50 -f /var/adm/sa/sa21

    Solaris 10 – checking online services

    $ svcs -xv svc:/network/rpc-100235_1/rpc_ticotsord:default
    svc:/network/rpc-100235_1/rpc_ticotsord:default (100235)
     State: online since Mon Feb 20 12:59:06 2006
    Impact: None.
    $ inetadm | grep enabled
    enabled   online         svc:/network/rpc/meta:default
    enabled   online         svc:/network/rpc-100235_1/rpc_ticotsord:default
    $ svcs -a | grep online | wc -l
          46

    Solaris: pgrep against full argument string

    # sleep 200 &
    5868
    # pgrep sleep
    5868
    # pgrep 200
    # pgrep -f 200
    5868
    #

    recursive copy preserving permissions

    cp -Rp /some/src /dest

    using xargs to copy files

    find /srcdir/ . -name '*.txt.gz' -mtime -2 | xargs -I {} cp {} /trgtdir/

    ntp commands

    # query
    $ /usr/sbin/ntpdate -q somehost
    # update
    # /usr/sbin/ntpdate -u somehost
    # show peers
    $ /usr/sbin/ntpq -p
    # show associations
    $ /usr/sbin/ntpq -c "assoc"
    # show rl vars for particular association
    $ /usr/sbin/ntpq -c "rl assID"
    # trace NTP back to primary source
    # /usr/sbin/ntptrace -dv someserver

    Linux – view failure counts for all users

    # faillog -a

    Linux – show all pam_tally stats (failed login tally) – see Tip 0041

    # pam_tally

    Solaris – view PROM variables

    eeprom | more

    Solaris – echo ignoring backslash-escape sequences

    -bash-3.00$ /usr/ucb/echo "c:\tuser\abc"
    c:\tuser\abc
    -bash-3.00$

    Solaris 10: Is syslog enabled?

    -bash-3.00$ svcs -a | grep system-log

    Linux force NIC speed

    mii-tool -F 100baseTx-FD eth0
    # note - better to use ethtool as mii-tool only supports up to 100/FD
    ethtool -s eth0 speed 100 duplex full autoneg off
    # also, to use 1000/FD you must leave autoneg enabled

    crypt

    crypt < encrypted.file > unencrypted.file
    # crypt will prompt you for your key.

    find the square root of a number

    $ echo "sqrt(4)" | bc
    2

    Solaris 10: to enable tcp tracing on telnet

    inetadm -m svc:/network/telnet:default tcp_trace=TRUE

    Solaris 10: inetadm – list properties for selected instance

    -bash-3.00$ /usr/sbin/inetadm -l svc:/network/login:rlogin

    Solaris 10 – show faults

    # fmadm faulty
    # fmdump -v

    Linux – Change the label on an ext2 filesystem

    e2label labelname

    list available signals

    kill -l

    Linux – check Serial port config

    # setserial -g -a /dev/ttyS0

    set modification date on a file

    touch -t DATE file # where DATE is in format [[CC]YY]MMDDhhmm[.SS]

    octal dump of file

    od -c file
    od -bc file

    set system date on RHEL

    date MMDDhhmm
    hwclock --systohc

    send syslogd a HUP

    killall -1 syslogd	;; linux
    pkill -HUP syslogd	;; solaris

    fsck ext3 filesystem automatically answering Y to questions

    fsck.ext3 -y /dev/hdb1

    Linux – view PCI and USB bus attached devices

    lsusb
    lspci

    Solaris 10 – disable a service

    # view dependencies
    svcs -a | grep gss
    svcs -d svc:/network/rpc/gss:default		;; gss depends on
    svcs -D svc:/network/rpc/gss:default		;; depend on gss
    svcadm -v disable svc:/network/rpc/gss:default
    svcs -xv svc:/network/rpc/gss:default
    svsa -a | grep gss

    Linux – grep a gzipped file

    zgrep "searchterm" foo.gz

    show plain text strings within a binary file

    strings /path/to/binary

    stop and start named

    rndc stop
    /etc/init.d/named start

    strace

    strace -f -o /var/tmp/trace.out -p 554 &

    diff

    diff file1 file2

    using expr with multiplication

    $ expr $a \* $b
    20

    Switch between postfix and sendmail on RHEL

    /usr/sbin/system-switch-mail
    # rpm -qa | egrep -i 'sendmail|postfix|switch-mail'
    system-switch-mail-0.5.25-3
    sendmail-8.13.1-2
    postfix-2.1.5-4.2.RHEL4

    Linux – view PCI devices

    lspci

    Linux – View USB devices

    lsusb

    Linux – Switch to another virtual console

    Ctrl-Alt-F1

    Solaris – display nickname to device translation table for eject

    eject -n

    Display all who information

    who -a

    join all lines in a file using paste

    paste -d ' ' -s file1 > file2

    Remove archived files that are over one day old

    rm -f `find /archive/ -mmin +1440 -print`

    awk substrings

    echo "1234567890abcdefghij" | awk '{print substr($0,3,1) " " substr($0,11,8)}'
    
    Some misc. Solaris one-liners 
    
    print PICL tree gathering temperature sensor info
    
    /usr/sbin/prtpicl -c temperature-sensor -v

    Clean up “dangling” /dev links

    devfsadm -C

    Installation log file

    /var/sadm/system/log/install_log

    detailed package info

    pkginfo -l installed_package_name
    pkginfo -l -d some_unistalled_pkg.pkg

    egrep for two things

    egrep 'THIS|THAT' somefile

    set erase char

    stty erase ^H

    run syslogd in debug mode to check configuration file

    /etc/init.d/syslog stop
    /usr/sbin/syslogd -d
    ^C
    /etc/init.d/syslog start

    pkgchk

    -bash-3.00$ /usr/sbin/pkgchk -lp /usr/bin/man
    NOTE: Couldn't lock the package database.
    Pathname: /usr/bin/man
    Type: linked file
    Source of link: ../../usr/bin/apropos
    Referenced by the following packages:
            SUNWdoc
    Current status: installed

    svcs

    # svcs -xv svc:/network/rpc/meta:default
    svc:/network/rpc/meta:default (SVM remote metaset services)
     State: disabled since Mon Jan 16 12:29:14 2006
    Reason: Disabled by an administrator.
       See: http://sun.com/msg/SMF-8000-05
       See: man -M /usr/share/man -s 1M rpc.metad
    Impact: This service is not running.
    svcs -Dv meta					;; that depend on this
    STATE          NSTATE        STIME    CTID   FMRI
    disabled       -             12:29:09      - svc:/system/mdmonitor:default
    svcs -dv meta					;; this depends on
    STATE          NSTATE        STIME    CTID   FMRI
    online         -             12:29:12     30 svc:/network/rpc/bind:default