Sunday, November 25, 2012

How to Mount a Remote Folder using SSH on Ubuntu

Connecting to a server across the internet is much more secure using SSH. There is a way that you can mount a folder on a remove server using the SSHFS service.
There are quite a few steps that you’ll have to follow, so get ready and open a terminal window.
First we’ll install the module:
sudo apt-get install sshfs
Now we will use the modprobe command to load it
sudo modprobe fuse
We’ll need to set up some permissions in order to access the utilities. Replace <username> with your username.
sudo adduser <username> fuse
sudo chown root:fuse /dev/fuse
sudo chmod +x /dev/fusermount
Since we’ve added ourselves to a user group, we need to logout and back in at this point before we continue.
Now we’ll create a directory to mount the remote folder in. I chose to create it in my home directory and call it remoteserv.
mkdir ~/remoteserv
Now we have the command to actually mount it. You’ll be prompted to save the server key and for your remote password.
sshfs <username>@<ipaddress>:/remotepath ~/remoteserv
Now you should be able to cd into the directory and start using it as if it was local.
geek@ubuntuServ:~/remoteserv$ ls -l
total 16
drwxr-xr-x 1 951247 155725 4096 2006-12-13 13:30 howtogeek.com
drwxr-sr-x 1 root root 4096 2006-09-11 06:45 logs
drwx—— 1 951247 155725 4096 2006-08-11 16:09 Maildir
drwxrwxr-x 1 951247 155725 4096 2006-10-29 02:34 scripts

Install Samba Server on Ubuntu

If you want to share files between your Ubuntu and Windows computers, your best option is to use Samba file sharing.
To install, first open a terminal window and enter the following command:
sudo apt-get install samba smbfs
We’ve got samba installed, but now we’ll need to configure it to make it accessible. Run the following command to open the configuration file, substituting your editor of choice:
sudo gedit /etc/samba/smb.conf
Find this section in the file:
####### Authentication #######
# “security = user” is always a good idea. This will require a Unix account
# in this server for every user accessing the server. See
# /usr/share/doc/samba-doc/htmldocs/Samba-HOWTO-Collection/ServerType.html
# in the samba-doc package for details.
;  security = user
Uncomment the security line, and add another line to make it look like this:
security = user
username map = /etc/samba/smbusers
This will set Samba to use the smbusers file for looking up the user list.
Create a Samba User
There are two steps to creating a user. First we’ll run the smbpasswd utility to create a samba password for the user.
sudo smbpasswd -a <username>
Next, we’ll add that username to the smbusers file.
sudo gedit /etc/samba/smbusers
Add in the following line, substituting the username with the one you want to give access to. The format is <ubuntuusername> = “<samba username>”.  You can use a different samba user name to map to an ubuntu account, but that’s not really necessary right now.
<username> = “<username>”
Now you can create samba shares and give access to the users that you listed here.

Create a Samba User on Ubuntu

If you are using Samba Server on your network, you will want to create users that have access to use it. There’s a very simple command structure on how to do so.
I’m assuming that you’ve already installed Samba Server at this point.
There are two steps to creating a user. First we’ll run the smbpasswd utility to create a samba password for the user.
sudo smbpasswd -a <username>
Next, we’ll add that username to the smbusers file.
sudo gedit /etc/samba/smbusers
Add in the following line, substituting the username with the one you want to give access to. The format is <ubuntuusername> = “<samba username>”. You can use a different samba user name to map to an ubuntu account, but that’s not really necessary right now.
<username> = “<username>”
Now you can create samba shares and give access to the users that you listed here.

Change your Network Card MAC Address on Ubuntu

There are a lot of reasons you might want to manually set your MAC address for your network card. I won’t ask you what your reason is.
To change this setting, we’ll need to edit the /etc/network/interfaces file. You can choose to use a different editor if you’d like.
sudo gedit /etc/network/interfaces
You should see the line for your network interface, which is usually eth0. If you have dhcp enabled, it will look like this:
auto eth0
iface eth0 inet dhcp
Just add another line below it to make it look something like this:
auto eth0
iface eth0 inet dhcp
       hwaddress ether 01:02:03:04:05:06
Obviously you would want to choose something else for the MAC address, but it needs to be in the same format.
sudo /etc/init.d/networking restart
You will need to restart networking or reboot to take effect.

Change the GRUB Menu Timeout on Ubuntu

When your Ubuntu system boots, you will see the GRUB menu if you hit the Esc key, or if you’ve enabled the menu to show by default. The only issue with this is that the default timeout is only 3 seconds. You may want to increase this amount… or you may even want to decrease it. Either one is simple.
Open up the /boot/grub/menu.lst file in your favorite text editor. I’m using gedit:
sudo gedit /boot/grub/menu.lst
Now find the section that looks like this:
## timeout sec
# Set a timeout, in SEC seconds, before automatically booting the default entry
# (normally the first entry defined).
timeout 3
The timeout value is in seconds. Save the file, and when you reboot you will have that many seconds to choose the menu item you want.

Change the DHCP IP Address Range for VMware NAT

VMware Workstation includes a network utility that allows you to manage the virtual networks. Typically virtual machines will use NAT (Network Address Translation) to automatically assign a virtual IP address that hides behind your host address, but the default range of 192.168.200.0/24 may not work for everybody.
You can change this address range to anything you like easily. Note that you should not have virtual machines running during this.
First open the Manage Virtual Networks start menu item:

Click the Host Virtual Network Mapping tab, and then click the arrow button next to the VMnet8 dropdown box. VMnet8 is the default NAT adapter for VMware.

Choose the Subnet option, and you will see a dialog where you can change the network range:

Once you have changed the network here, you can click the OK or Apply buttons, and after a few seconds it will update.

Change SSH Welcome Banner on Ubuntu

Every time I connect to my Ubuntu development server through my ssh client, I receive the same message and I’m getting tired of seeing it, so I decided to change the message to something else.
Here’s the message that I get every time:
Linux superfast 2.6.20-16-generic #2 SMP Thu Jun 7 19:00:28 UTC 2007 x86_64
The programs included with the Ubuntu system are free software;
the exact distribution terms for each program are described in the
individual files in /usr/share/doc/*/copyright.
Ubuntu comes with ABSOLUTELY NO WARRANTY, to the extent permitted by
applicable law.
Last login: Mon Aug 13 01:05:46 2007 from ipaddress removed
geek@superfast:~$
Changing this message requires editing two different files. The first three sections can be modified by editing the following file:
/etc/motd
This file contains the linux build number as well as the Ubuntu warranty message. I don’t find this particularly useful, so I removed all of it and replaced it with my own message.
To disable the last login message (which I don’t recommend doing), you will need to edit the following file in sudo mode:
/etc/ssh/sshd_config
Find this line in the file and change the yes to no as shown:
PrintLastLog no
Now when you login, you’ll get a blank prompt, although I wouldn’t necessarily recommend it because it’s useful to see the last login to the system for security reasons. This is my prompt now:
This is a superfast system. Please max out the cpu accordingly.
Last login: Mon Aug 13 01:24:14 2007 from ipaddress removed
geek@superfast:~$
Linux is really great.

Change or set the MySQL root password

For every database, you should set the root or sa passwords to something other than the default, unless you want to get hacked. For mysql, the system administrator user is called root. You will use the mysqladmin utility from a command line to set the new password. Notice that there are two commands to be run.
Syntax:
mysqladmin -u root password “newpassword”
mysqladmin -u root -h host_name password “newpassword”
Example:
mysqladmin -u root password ws8dr8as3
mysqladmin -u root -h localhost password ws8dr8as3
You will also want to restart the database server after running this command
sudo /etc/init.d/mysql restart

Boot from a USB drive even if your BIOS Won’t Let You

You’ve always got a trusty bootable USB flash drive with you to solve computer problems, but what if a PC’s BIOS won’t let you boot from USB? We’ll show you how to make a CD or floppy disk that will let you boot from your USB drive.
sshot-1
This boot menu, like many created before USB drives became cheap and commonplace, does not include an option to boot from a USB drive.
A piece of freeware called PLoP Boot Manager solves this problem, offering an image that can burned to a CD or put on a floppy disk, and enables you to boot to a variety of devices, including USB drives.
Put PLoP on a CD
PLoP comes as a zip file, which includes a variety of files. To put PLoP on a CD, you will need either plpbt.iso or plpbtnoemul.iso from that zip file. Either disc image should work on most computers, though if in doubt plpbtnoemul.iso should work “everywhere,” according to the readme included with PLoP Boot Manager.
Burn plpbtnoemul.iso or plpbt.iso to a CD and then skip to the “booting PLoP Boot Manager” section.
Put PLoP on a Floppy Disk
If your computer is old enough to still have a floppy drive, then you will need to put the contents of the plpbt.img image file found in PLoP’s zip file on a floppy disk.
To do this, we’ll use a freeware utility called RawWrite for Windows.
sshot-6
We aren’t fortunate enough to have a floppy drive installed, but if you do it should be listed in the Floppy drive drop-down box. Select your floppy drive, then click on the “…” button and browse to plpbt.img. Press the Write button to write PLoP boot manager to your floppy disk.
sshot-7
Booting PLoP Boot Manager
To boot PLoP, you will need to have your CD or floppy drive boot with higher precedence than your hard drive. In many cases, especially with floppy disks, this is done by default.
If the CD or floppy drive is not set to boot first, then you will need to access your BIOS’s boot menu, or the setup menu. The exact steps to do this vary depending on your BIOS – to get a detailed description of the process, search for your motherboard’s manual (or your laptop’s manual if you’re working with a laptop).
In general, however, as the computer boots up, some important keyboard strokes are noted somewhere prominent on the screen. In our case, they are at the bottom of the screen.
sshot-18
Press Escape to bring up the Boot Menu. Previously, we burned a CD with PLoP Boot Manager on it, so we will select the CD-ROM Drive option and hit Enter.
sshot-2
If your BIOS does not have a Boot Menu, then you will need to access the Setup menu and change the boot order to give the floppy disk or CD-ROM Drive higher precedence than the hard drive. Usually this setting is found in the “Boot” or “Advanced” section of the Setup menu.
sshot-17
If done correctly, PLoP Boot Manager will load up, giving a number of boot options.
sshot-3
Highlight USB and press Enter.
sshot-4
PLoP begins loading from the USB drive.
sshot-5
Despite our BIOS not having the option, we’re now booting using the USB drive, which in our case holds an Ubuntu Live CD!
sshot-8
This is a pretty geeky way to get your PC to boot from a USB…provided your computer still has a floppy drive. Of course if your BIOS won’t boot from a USB it probably has one…or you really need to update it.

Backup MySQL Database to a file

Backing up your database is a very important system administration task, and should generally be run from a cron job at scheduled intervals. We will use the mysqldump utility included with mysql to dump the contents of the database to a text file that can be easily re-imported.
Syntax:
mysqldump -h localhost -u root -pmypassword databasename > dumpfile.sql
Example:
mysqldump -h localhost -u root -p2Uad7as9 database01 > dumpfile.sql
This will give you a text file containing all the commands required to recreate the database.

Allow Remote Control To Your Desktop On Ubuntu

Enabling remote desktop mode is extremely easy on Ubuntu since Dapper. You can allow other users to access your desktop using the VNC Viewer utility that is bundled with Ubuntu, or offered as a free download for Windows.
Note that enabling remote control of your desktop is never a safe thing to do unless you have a firewall installed and configured correctly, and even then is still a potential security problem. Now that you’ve been warned of the risks, let’s move on.
Navigate to the System \ Preferences \ Remote Desktop on the Gnome top menu.
You’ll see this window:

The first two checkboxes need to be checked in order for remote desktop to be enabled.
The Security section is important: If you select the “Ask you for confirmation” code, then you will need to be at the computer in order to allow the other person to access your desktop. If you are trying to remotely access one of your own computers, you will want to uncheck this box.
The second checkbox should always be checked, and you should enter a secure password. You will be prompted for this password when you try to log on.

Installing PHP5 and Apache on Ubuntu

If you are doing any kind of PHP development, you’ll almost always be using Apache along with it. Here’s the quick and easy way to get PHP up and running on your Ubuntu box.
First, you’ll want to add the extra repositories to Ubuntu’s sources.list file.
From a command shell, you will run the following commands:
sudo apt-get install apache2
sudo apt-get install php5
sudo apt-get install libapache2-mod-php5
sudo /etc/init.d/apache2 restart
Note that if apache is already installed you can omit the first line. Your web files will now be found in /var/www/

How to install Apache on Linux

The installation, care, and feeding of an Apache Web server is not terribly difficult, but can seem so if you haven't ventured into those particular waters before. This quick-start guide will help you get your feet wet with Apache on a Linux server. You'll find it's relatively simple to get the Web server set up and running on your Linux of choice. We'll also install PHP and MySQL, though we won't be digging into MySQL configurations, as that deserves a quick start all its own.
The method of installing the Apache packages on a Linux server varies from distribution to distribution. We'll cover how to do this on Fedora and CentOS, as well as on Ubuntu. This is a server-centric walkthrough, so we'll use the command line exclusively. Naturally, you'll need root-level privileges. Open the terminal window and type:
su -
[ Prove your expertise with the free OS in InfoWorld's Linux admin IQ test round 1 and round 2. | Track the latest trends in open source with InfoWorld's Open Sources blog and Technology: Open Source newsletter. ]
Then enter the root password. Now we can get started.
First we'll install the packages themselves. For Fedora and CentOS, this is a simple step involving Yum, the package installer and updater. To install the basic Apache and PHP packages, run the following command:
yum install httpd php mysql mysql-server
Follow the prompts, as this tool will locate and install a base set of Apache and PHP packages.
For Ubuntu 10.04 servers and newer, you can install the whole LAMP (Apache, MySQL, and PHP) stack with two commands:
sudo apt-get install tasksel
sudo tasksel install lamp-server
While this guide does not cover MySQL, the above commands are a quick way to get all the necessary packages required for LAMP applications. Once the installation is complete, we can begin configuring the server.
For all file editing, on Fedora, CentOS, or Ubuntu, you may want to use nano:
nano /etc/httpd/conf/httpd.conf
This command will open the Apache configuration file in a basic editor. You can save the file with Ctrl-O and exit the editor with Ctrl-X.
Apache on Linux: Initial configuration
While the Apache and PHP packages are essentially the same across the different distributions, there are differences in how they are actually installed on the file system. We'll start with Fedora and CentOS.
Fedora and CentOS. After installation, you'll find a new directory: /etc/httpd. Within this directory are all the Apache configuration files. The important subdirectories for our purposes are /etc/httpd/conf and /etc/httpd/conf.d. Within /etc/httpd you'll find the main Apache configuration file, httpd.conf. In /etc/httpd/conf.d you will find includes, or supplemental files that are included in the main configuration file.
Includes are a way to break out complex configurations into separate files for easy organization and management. For instance, if you have an Apache server that has 20 virtual hosts, then each virtual host should have a separate file in /etc/httpd/conf.d/ that contains its specific configuration parameters. In this way, you can easily add or remove virtual hosts without editing the main Apache configuration file.
In order for files to be included in the Apache configuration, they must have a filename that ends with .conf. If we have a virtual host named www.test.com, all the configuration elements for that virtual host would reside in a file named test.conf or test.com.conf.
You can see how these files are included in the main configuration file by looking at /etc/httpd/conf/httpd.conf. Press Ctrl-W to search for "Include conf.d" and you'll find this line:
Include conf.d/*.conf

Create tab on Facebook page (updated)

CUSTOM FACEBOOK TAB
As usual Facebook keep changing, improving and driving nuts many developers and users.
How to have however a new tab into your page on Facebook and in personal profile
1. Go to your https://developers.facebook.com/apps (if you have not account there just create one, it is fast and free – follow the instructions)
2. Create an app , take care , name of the app is very relevant, for example is your new tab will be a contact form the name it Contact. It is not just about name of tab, it can be changed but it is about page title when user will click on the icon of your app. The icon can be setup later. Let’s have the tab working.
See image below as sample and fill in with your details
You can setup and use the application (tab) but you must have SSL installed on your website!
  • If your page (tab) will be browsed by a user who is not log into facebook then the facebook url is http://facebook.com/YOUR_FACEBOOK_PAGE. All good and your tab will be displayed okay.
  • If your page (tab) will be browsed by a user who is log into facebook  then the facebook url is https://facebook.com/YOUR_FACEBOOK_PAGE. Your page (TAB) will try to load your content on https:// and if you have not SSL installed then an error will be displayed.
If you have not SSL installed on the website where you bring content into Facebook tab is not 100% relevant. The filed “Secure page tab url” is compulsory. Just replace http with https.
As far as I see if you are developer of the app and you try to see your result (tab content) you will get error generated by the missing SSL. If you open a new browser and access the same tab (login in facebook or not) there will be no error.
facebook tab howto
Save and wait a few minutes/hours or no need to wait. Why? Because it depends of Facebook “mood”. Try next steps once you finish this one. If it works means you are luck, does not work yet: check all above and it means “bad luck”. Keep trying, never give up.
3. make sure you have your in your website setup the path specified above, I mean: http://www.sydneywebs.com.au/facebook/about/ folder and that a file named index.php or index.html does exist into that folder
What will be in that page (index.php) will be displayed into your new tab on facebook
4. When you consider, login in Facebook, into that account that is admin for the page in which you wish to add the tab and write in browser :
  • To display tab in your page (personal): call in a browser:  https://www.facebook.com/dialog/oauth?client_id=YOUR_APP_ID&redirect_uri=YOUR_CANVAS_PAGE
  • To display tab in business page: call in a browser: https://www.facebook.com/dialog/pagetab?app_id=YOUR_APP_ID&next=YOUR_CANVAS_PAGE
replace YOUR_APP_ID and YOUR_CANVAS_PAGE with what you write above
For page, you will be asked to chose the page where you wish to be displayed this tab. To that page into applications area will be added your app.
More tabs you need then more apps you need to setup. One tab you wish to have = one apps like this you will add.

Create rounded corners with CSS

Rounded corners for Safari/Chrome, Opera and IE9:
#example {
border-radius: 15px;
}
Rounded corners to be supported by Firefox as well:
#example {
-moz-border-radius: 15px;
border-radius: 15px;
}
border-radius
The border-radius shorthand property can be used to define all four corners simultaneously. The property accepts either one or two sets of values, each consisting of one to four lengths or percentages.
Example:
border-radius: 5px 10px 5px 10px / 10px 5px 10px 5px;
border-radius: 5px;
border-radius: 5px 10px / 10px;
The first set of (1-4) values define the horizontal radii for all four corners. An optional second set of values, preceded by a ‘/’, define the vertical radii for all four corners. If only one set of values are supplied, these are used to determine both the vertical and horizontal equally.
If all four values are supplied, these represent the top-left, top-right, bottom-right and bottom-left radii respectively. If bottom-left is omitted it is the same as top-right, if bottom-right is omitted it is the same as top-left, and if only one value is supplied it is used to set all four radii equally.

Basic examples that should work in current versions of Firefox, Safari/Chrome, Opera and even IE9:
#Example_A {
height: 65px;
width:160px;
-moz-border-radius-bottomright: 50px;
border-bottom-right-radius: 50px;
}
#Example_B {
height: 65px;
width:160px;
-moz-border-radius-bottomright: 50px 25px;
border-bottom-right-radius: 50px 25px;
}
#Example_C {
height: 65px;
width:160px;
-moz-border-radius-bottomright: 25px 50px;
border-bottom-right-radius: 25px 50px;
}
#Example_D {
height: 5em;
width: 12em;
-moz-border-radius: 1em 4em 1em 4em;
border-radius: 1em 4em 1em 4em;
}
#Example_E {
height: 65px;
width:160px;
-moz-border-radius: 25px 10px / 10px 25px;
border-radius: 25px 10px / 10px 25px;
}
#Example_F {
height: 70px;
width: 70px;
-moz-border-radius: 35px;
border-radius: 35px;
}
Another opinion in considering most of the browsers when create rounded conners through CSS:
Since each of the browsers still has its own unique idiosyncrasies, they apply prefixes such as -moz and -webkit.
-moz-border-radius is for Firefox, -webkit-border-radius is for Chrome/Safari and -khtml-border-radius is for older Konquerer browsers.
rounded-corners {
-moz-border-radius: 20px;
-webkit-border-radius: 20px;
-khtml-border-radius: 20px;
border-radius: 20px; }

CSS Box Shadow

Syntax

box-shadow: h-shadow v-shadow blur spread color inset;
JavaScript syntax:
object.style.boxShadow="10px 10px 5px #888888"
Note: The box-shadow property attaches one or more drop-shadows to the box. The property is a comma-separated list of shadows, each specified by 2-4 length values, an optional color, and an optional inset keyword. Omitted lengths are 0.
VALUE
DESCRIPTION
h-shadow
Required. The position of the horizontal shadow. Negative values are allowed
v-shadow
Required. The position of the vertical shadow. Negative values are allowed
blur
Optional. The blur distance
spread
Optional. The size of shadow
color
Optional. The color of the shadow.
inset
Optional. Changes the shadow from an outer shadow (outset) to an inner shadow


Box Shadow for Firefox, Safari/Chrome, Opera and IE9:
CSS Box Shadow
.Example_A {
  -moz-box-shadow:    3px 3px 5px 6px #ccc;
  -webkit-box-shadow: 3px 3px 5px 6px #ccc;
  box-shadow:         3px 3px 5px 6px #ccc;
}
Inner Shadow for Firefox, Safari/Chrome, Opera and IE9:
CSS Box Inner Shadow
.Example_B {
   -moz-box-shadow:    inset 0 0 10px #000000;
   -webkit-box-shadow: inset 0 0 10px #000000;
   box-shadow:         inset 0 0 10px #000000;
}
One Side Box Shadow for Firefox, Safari/Chrome, Opera and IE9:
CSS Box One-Side Shadow
.Example_C {
 -webkit-box-shadow: 0 8px 6px -6px black;
    -moz-box-shadow: 0 8px 6px -6px black;
         box-shadow: 0 8px 6px -6px black;
}

CSS Text Shadow

Syntax

text-shadow: h-shadow v-shadow blur color;
JavaScript syntax:
object.style.textShadow="2px 2px #ff0000"
Note: The text-shadow property attaches one or more shadows to text. The property is a comma-separated list of shadows, each specified by 2 or 3 length values and an optional color. Omitted lengths are 0.
VALUE
DESCRIPTION
h-shadow
Required. The position of the horizontal shadow. Negative values are allowed
v-shadow
Required. The position of the vertical shadow. Negative values are allowed
blur
Optional. The blur distance
color
Optional. The color of the shadow
Text shadows:
Text shadows
h3 {text-shadow: 0.1em 0.1em #333}
Fuzzy text shadow:
Fuzzy text shadow
h3.a {text-shadow: 0.1em 0.1em 0.05em #333}
h3.b {text-shadow: 0.1em 0.1em 0.2em black}
Readable white text:
Readable white text
h3 {color: white}
h3.a {color: white; text-shadow: black 0.1em 0.1em 0.2em}
Multiple shadows:
Text multiple shadows
h3 {text-shadow: 0.2em 0.5em 0.1em #600,
      -0.3em 0.1em 0.1em #060,
      0.4em -0.3em 0.1em #006}
Emboss effect: Raised Emboss & Inset Emboss
Emboss effect
h3.a {text-shadow: -1px -1px white, 1px 1px #333}
h3.b {text-shadow: 1px 1px white, -1px -1px #444}
Drawing letters as outlines:
Drawing letters as outlines
h3 {text-shadow: -1px 0 black, 0 1px black,
      1px 0 black, 0 -1px black}
Neon glow:
Neon glow
h3.a {text-shadow: 0 0 0.2em #8F7}
h3.b {text-shadow: 0 0 0.2em #F87, 0 0 0.2em #F87}
h3.c {text-shadow: 0 0 0.2em #87F, 0 0 0.2em #87F,
        0 0 0.2em #87F}

How to setup VLAN on CISCO routers

It is assumed that:
- you are into router as user with full rights – level 15 – ssh, telnet or console
- You just want to route a specific range of IPs through one interface
- You will not use STP / Trunks on that VLAN
- Physical interface is FastEthernet 4
a1) Setup VLAN
cisco1#configure terminal
cisco1(config)#interface vlan4
cisco1(config-if)# ip address 192.168.1.1 255.255.255.0
cisco1(config-if)#exit
cisco1(config)#exit
cisco1#write
a2) Link VLAN and physical interface
cisco1#configure terminal
cisco1(config)#interface FastEthernet4
cisco1(config-if)#speed 100
cisco1(config-if)#no cdp enable
cisco1(config-if)#spanning-tree portfast
cisco1(config-if)#switchport access vlan 4
(Will you receive error the see b), solve the issue and come back )
cisco1(config-if)#exit
cisco1(config)#exit
cisco1#write
a3) Create route
cisco1#configure terminal
cisco1(config)ip route 192.168.1.0 255.255.255.0 vlan4
cisco1(config)#exit
cisco1#write
a4) Create access list
Use by your own access-list command
b) Error when try to add vlan4
It is possible to get this error :
“..Access VLAN 4 does not exist. Please add it to vlan database”
It may help to fix this problem:
It is assumed that:
-you are into router as user with full rights – level 15 – ssh, telnet or console
-do not go to configure menu
cisco1#vlan database
cisco1(vlan)#vlan 4
VLAN 4 added
….
….
cisco1(vlan)#write

How to Create and Delete VLAN on Cisco Catalyst Switch

One of the typical configuration activities you’ll perform on a Cisco Switch is to manipulate VLANs.
VLAN stands for Virtual Local Area Network.
In one physical cisco switch, you can create multiple VLANs that connects to different network.
For example, a VLAN for 10.10.191.0 network, a VLAN for 10.10.192.0 network, and a VLAN for 10.10.193.0 network. All three of these can be configured in the same physical switch.

While these commands were tested on a cisco catalyst switch 3750 series, similar commands (may be with slight variation to the port number format) should work on all cisco switches.

Create VLAN on Cisco Switch

If you are planning to have only one network in your whole switch (for example, 10.10.192.0). i.e All the ports in the switch will be connected to the 10.10.192.0 network, then you don’t need to create a VLAN, just use the default VLAN 1.
Every switch comes with the default VLAN 1 as shown below. In this example, all the ports in this switch ( from 1 through 8 ) are part of the default VLAN 1.

#show vlan VLAN Name Status Ports ---- -------------------------------- --------- ------------ 1 default active Gi1/0/1, Gi1/0/2, Gi1/0/3, Gi1/0/4 Gi1/0/5, Gi1/0/6, Gi1/0/7, Gi1/0/8
In the following example, we are creating 192 VLAN network (for 10.10.192.0 network). While creating a VLAN you also need to specify the range of ports from the switch that needs to be part of this VLAN network.
In this example, ports 3 through 6 are configured as part of 192 VLAN network.
config t
vlan 192
interface range gigabitEthernet 1/0/3-6
switchport access vlan 192
exit
In the above commands:
  • config t – Goes into the configuration mode
  • vlan 192 – Creates VLAN 192
  • interface range gigabitEthernet 1/0/3-6 – Indicates that the port numbers 3 through 6 are assigned to this VLAN
  • swithport access vlan 192 – Indicates that the access to the vlan 192 is enabled
Apart from providing the access to the vlan 192 for the port numbers 3 through 6, you can also specify the following additional switchport configuration parameters (for example, nonegotiate and mode access)
config t
interface range gigabitEthernet 1/0/3-6
switchport mode access
switchport nonegotiate
exit
Once you’ve created a VLAN verify it as shown below,
#show vlan

VLAN Name       Status    Ports
---- -------------------------------- --------- ------------
1    default    active    Gi1/0/1, Gi1/0/2, Gi1/0/7, Gi1/0/8
192  VLAN0192   active    Gi1/0/3, Gi1/0/4, Gi1/0/5, Gi1/0/6
On a side note, it is always recommended that you upgrade ISO image on your cisco switch to the latest version.

Delete VLAN on Cisco Switch

You might want to delete a VLAN, if you are planning to switch the ports assigned to VLAN 192 to a different VLAN. Or, you might want to delete a VLAN, just because you’ve created it by mistake.
Let us assume that you want to delete the VLAN 192 (ports 3 though 6) that you just created.
Deleting a VLAN is as simple as assigning the default VLAN 1 to the ports that are part of the VLAN you want to delete, and delete the VLAN.
i.e If you want to delete VLAN 192, assign VLAN 1 to the ports 3 through 6, and just delete the VLAN 192.
First, assign the default VLAN 1 to ports 3 though 6 as shown below.
interface range gigabitEThernet 1/0/3-6
switchport access vlan 1
exit
Next, delete the vlan itself as shown below.
no vlan 192
Finally, verify that the VLAN 192 got deleted as shown below.
#show vlan

VLAN Name       Status    Ports
---- -------------------------------- --------- ------------
1    default    active    Gi1/0/1, Gi1/0/2, Gi1/0/3, Gi1/0/4
                          Gi1/0/5, Gi1/0/6, Gi1/0/7, Gi1/0/8
As a final note, if you don’t know what you are doing, do not execute any of the above commands on production switch, as you might bring down your network. Do this only on a test system, where you can play around and learn how to manipulate VLANs on cisco switch.

Linux Install Google Chrome Browser [ Ubuntu, Suse, Debian, Fedora ]

How do I install Google Chrome browser under Linux operating systems? How do I install google-chrome-beta_current_amd64.deb or google-chrome-beta_current_x86_64.rpm file under Linux?

Google Chrome is another web browser which runs web pages and applications with lightning speed due to its superior JavaScript rendering engine.

Step #1: Download Chrome Browser

Visit this url and download the package for Linux desktop.
Fig.01: Please select your download package format
Fig.01: Please select your download package format
Save .deb or .rpm package at /tmp directory.

Step #2: Install Google Chrome Browser

Open the terminal and type the following command to install the same under Debian or Ubuntu Linux:
cd /tmp
sudo dpkg -i google-chrome-beta_current_amd64.deb
If you are using Suse or Fedora Linux, enter:
 
rpm -ivh google-chrome-beta_current_x86_64.rpm

How Do I Run Google Chrome Browser?

You can launch Google Chrome browser by visiting the Application > Internet > Google Chrome. Or type the following command at a bash prompt:
google-chrome &
Fig.02: Linux Google Chrome In Action
Fig.02: Linux Google Chrome In Action

Removing a Directory In Linux

How do I remove a directory in Linux using the shell prompt?

You can use the following commands:
[a] rmdir command : remove empty directories.
[b] rm command : remove files or directories.

Linux Delete a Directory Command Examples

The syntax is as follows:
 
rmdir dirName
 
Login using the ssh client or open a command-line terminal (select Applications > Accessories > Terminal under Gnome desktop), than type the following command to delete empty directory called foo:
 
rmdir foo
 
By default, the rm command does not remove directories. Use the --recursive (-r or -R) option to remove each listed directory, too, along with all of its contents including all files and subdirectories:
 
rm -r documents
 
You can also specifiy the full path:
 
rm -r /data/dir1
rm -r /home/vivek/dir2
rmdir $HOME/mp3
 

Find: Ram Size in Linux

How do I find out my RAM size under Linux operating systems?

You can use the following commands to find out actual RAM size under Linux operating systems.

/proc/meminfo file

Type the following command to view total installed ram and used ram, enter:
$ less /proc/meminfo
OR
$ cat /proc/meminfo
Sample outputs:
MemTotal:      8177444 kB
MemFree:       1528304 kB
Buffers:        353152 kB
Cached:        2301132 kB
SwapCached:          0 kB
Active:        5250532 kB
Inactive:       983832 kB
HighTotal:           0 kB
HighFree:            0 kB
LowTotal:      8177444 kB
LowFree:       1528304 kB
SwapTotal:     1052248 kB
SwapFree:      1052248 kB
Dirty:            1796 kB
Writeback:           0 kB
AnonPages:     3579784 kB
Mapped:         106548 kB
Slab:           295500 kB
PageTables:      82956 kB
NFS_Unstable:        0 kB
Bounce:              0 kB
CommitLimit:   5140968 kB
Committed_AS:  4959796 kB
VmallocTotal: 34359738367 kB
VmallocUsed:    263900 kB
VmallocChunk: 34359473347 kB
HugePages_Total:     0
HugePages_Free:      0
HugePages_Rsvd:      0
Hugepagesize:     2048 kB

free Command

The free command displays the total amount of free and used physical and swap memory in the system, as well as the buffers used by the kernel:
$ free -m
OR
$ free -g
Sample outputs:
             total       used       free     shared    buffers     cached
Mem:          7985       6466       1519          0        344       2249
-/+ buffers/cache:       3871       4114
Swap:         1027          0       1027

Options

From the man page:
       The -b switch displays the amount of memory in bytes; the -k switch (set by default) displays it in kilobytes; the -m switch displays it in megabytes.
       The -t switch displays a line containing the totals.
       The -o switch disables the display of a "buffer adjusted" line.  If the -o option is not specified, free subtracts buffer memory from the used memory and adds it to the free memory reported.
       The -s switch activates continuous polling delay seconds apart. You may actually specify any floating point number for delay, usleep(3) is used for microsecond resolution delay times.

vmstat command

The vmstat command can display memory statistics including additional information about processes, paging, block IO, traps, and cpu activity. Type the following command:
$ vmstat -s
Sample outputs:
      8177444  total memory
      6655064  used memory
      5251360  active memory
       989748  inactive memory
      1522380  free memory
       353316  buffer memory
      2308588  swap cache
      1052248  total swap
            0  used swap
      1052248  free swap
     38412570 non-nice user cpu ticks
       100117 nice user cpu ticks
      5153239 system cpu ticks
    271927635 idle cpu ticks
        45717 IO-wait cpu ticks
        63003 IRQ cpu ticks
       564561 softirq cpu ticks
            0 stolen cpu ticks
      1846153 pages paged in
    158053429 pages paged out
            0 pages swapped in
            0 pages swapped out
   1226003322 interrupts
    740976858 CPU context switches
   1295805340 boot time
       659452 forks

top Command

The top command provides a dynamic real-time view of a running system including a quick summary information about RAM, CPU as well as a list of tasks currently being managed by the Linux kernel. Type the following command:
$ top
Sample outputs:
Fig.01: Display Linux RAM Size with the top commad
Fig.01: Display Linux RAM Size with the top commad

GUI System Information Tool

The System Monitor Gnome application enables you to display basic system information and monitor system processes, usage of system resources, and file systems. You can start System Monitor in the following ways:
Click on System menu > Choose Administration > System Monitor
Or type the following command:
$ gnome-system-monitor
Sample outputs:
Fig.02: Linux view installed memory with the System Monitor application
Fig.02: Linux view installed memory with the System Monitor application

dmidecode Command

The dmidecode command is used for dumping a computer's DMI (some say SMBIOS) table contents in a human-readable format. This table contains a description of the system's hardware components, as well as other useful pieces of information such as serial numbers and BIOS revision. Thanks to this table, you can retrieve this information without having to probe for the actual hardware. To see complete information about memory, enter:
$ sudo dmidecode --type memory
Sample outputs:
# dmidecode 2.9
SMBIOS 2.6 present.
Handle 0x1000, DMI type 16, 15 bytes
Physical Memory Array
 Location: System Board Or Motherboard
 Use: System Memory
 Error Correction Type: None
 Maximum Capacity: 16 GB
 Error Information Handle: Not Provided
 Number Of Devices: 4
Handle 0x1100, DMI type 17, 28 bytes
Memory Device
 Array Handle: 0x1000
 Error Information Handle: Not Provided
 Total Width: 64 bits
 Data Width: 64 bits
 Size: 4096 MB
 Form Factor: DIMM
 Set: None
 Locator: DIMM_A
 Bank Locator: Not Specified
 Type: 
 Type Detail: Synchronous
 Speed: 1333 MHz (0.8 ns)
 Manufacturer: 80CE000080CE
 Serial Number: 45AAFB60
 Asset Tag: 01101800
 Part Number: M471B5273CH0-CH9
Handle 0x1101, DMI type 17, 28 bytes
Memory Device
 Array Handle: 0x1000
 Error Information Handle: Not Provided
 Total Width: 64 bits
 Data Width: 64 bits
 Size: 4096 MB
 Form Factor: DIMM
 Set: None
 Locator: DIMM_B
 Bank Locator: Not Specified
 Type: 
 Type Detail: Synchronous
 Speed: 1333 MHz (0.8 ns)
 Manufacturer: 80CE000080CE
 Serial Number: 45AAFDAD
 Asset Tag: 01101800
 Part Number: M471B5273CH0-CH9
Handle 0x1102, DMI type 17, 28 bytes
Memory Device
 Array Handle: 0x1000
 Error Information Handle: Not Provided
 Total Width: 64 bits
 Data Width: 64 bits
 Size: No Module Installed
 Form Factor: DIMM
 Set: None
 Locator: DIMM_C
 Bank Locator: Not Specified
 Type: 
 Type Detail: Synchronous
 Speed: Unknown
 Manufacturer:
 Serial Number:
 Asset Tag:
 Part Number:
Handle 0x1103, DMI type 17, 28 bytes
Memory Device
 Array Handle: 0x1000
 Error Information Handle: Not Provided
 Total Width: 64 bits
 Data Width: 64 bits
 Size: No Module Installed
 Form Factor: DIMM
 Set: None
 Locator: DIMM_D
 Bank Locator: Not Specified
 Type: 
 Type Detail: Synchronous
 Speed: Unknown
 Manufacturer:
 Serial Number:
 Asset Tag:
 Part Number:

Shutdown Linux Server

How do I shutdown my Linux server or computer using command line options?

The shutdown command bring the Linux based system or server down. Only the superuser (root user) can shut the system down. Open a command-line terminal (select Applications > Accessories > Terminal), or login to remote server using the ssh command, and then type the following command to shutdown the Linux server immediately:
# shutdown -h now
The shutdown command arranges for the system to be brought down in a safe way i.e. it will remove power from a servers's main components in a controlled way. All logged-in users are notified that the system is going down and, within the last five minutes of TIME, new logins are prevented. TIME may have different formats, the most common is simply the word now which will bring the system down immediately. Other valid formats are +m, where m is the number of minutes to wait until shutting down and hh:mm which specifies the time on the 24hr clock format. In this example, shutdown the system in 5 minutes:
# shutdown -h +5
Sample outputs:
Broadcast message from vivek@vivek-laptop
 (/dev/pts/0) at 16:57 ...
The system is going down for halt in 5 minutes!

-h (halt) option

The -h option requests that the system be either halted or powered off after it has been brought down, with the choice as to which left up to the system:
# shutdown -h 6:30
OR
# shutdown -h 20:00
The above will turn the server off at 8:00 PM.

-H option

The -H option requests that the system be halted after it has been brought down:
# shutdown -H +10

-P (power off) option

The -P option requests that the system be powered off after it has been brought down:
# shutdown -P +10
Sample outputs:
Broadcast message from vivek@vivek-laptop
 (/dev/pts/1) at 17:00 ...
The system is going down for power off in 10 minutes!
You can type the poweroff command:
# poweroff

How do I Cancel The System Shutdown?

You can press [CTRL+C] or type the following command to cancel a running shutdown:
# shutdown -c
Sample output (the command was issued on tty01):
shutdown -h +10
Broadcast message from vivek@vivek-laptop
 (/dev/pts/1) at 17:04 ...
The system is going down for halt in 10 minutes!
shutdown: Shutdown cancelled

How Do I Display Custom Shutdown Message?

Use the following syntax:
# shudown -h TIME "YOUR-MESSAGE-HERE"
In this example, shutdown the server for hard disk replacement:
# shutdown -h +5 "The server is going down for 'harddisk replacement'"
Sample outputs:
Broadcast message from vivek@vivek-laptop
 (/dev/pts/0) at 17:11 ...
The system is going down for halt in 5 minutes!
The server is going down for 'harddisk replacement' 

Linux Server Shutdown and Log Files

The following two files are updates when the system goes down for the poweroff / halt or reboot operations:
  1. /var/run/utmp - Where the current runlevel will be read from; this file will also be updated with the runlevel record being replaced by a shutdown time record.
  2. /var/log/wtmp - A new runlevel record for the shutdown time will be appended to this file.

How Do I Display the System Shutdown Time?

Use the last command as follows:
# last -x shutdown
Sample outputs:
shutdown system down  2.6.18-238.el5   Sat Jan 22 06:40 - 05:51 (10+23:10)
shutdown system down  2.6.18-194.32.1. Sun Jan 16 13:26 - 06:40 (5+17:14)
shutdown system down  2.6.18-194.26.1. Sat Jan  8 04:17 - 13:25 (8+09:08)
shutdown system down  2.6.18-194.26.1. Mon Nov 15 16:46 - 04:16 (53+11:30)
shutdown system down  2.6.18-194.17.1. Wed Oct 27 01:00 - 02:00 (18+02:00)
shutdown system down  2.6.18-194.8.1.e Thu Aug 12 00:18 - 09:02 (20+08:43)
shutdown system down  2.6.18-194.8.1.e Wed Jul 14 14:07 - 16:19 (5+02:12)
shutdown system down  2.6.18-194.8.1.e Tue Jul 13 20:21 - 14:06  (17:45)
shutdown system down  2.6.18-194.8.1.e Tue Jul 13 12:13 - 20:20  (08:07)
shutdown system down  2.6.18-194.8.1.e Tue Jul 13 11:48 - 12:13  (00:24)
shutdown system down  2.6.18-194.8.1.e Tue Jul 13 10:38 - 11:48  (01:09)
shutdown system down  2.6.18-194.el5   Tue Jul 13 10:32 - 10:38  (00:05)
wtmp begins Tue Jul 13 10:26:19 2010

Show Linux Partitions Command

How do I display or show a list of all hard disk drive partitions under Linux operating systems?

Your PC or x86 Linux server hard disk drive can be divided into one or more logical disks called partitions. This division is described in the partition table found in sector 0 of the disk. The fdisk command can be used to view the list of the partition tables for the specified devices. Open a command-line terminal (select Applications > Accessories > Terminal), and then type:
$ sudo fdisk -l
OR
# fdisk -l
Sample outputs:
Disk /dev/sda: 73.2 GB, 73284976640 bytes
255 heads, 63 sectors/track, 8909 cylinders
Units = cylinders of 16065 * 512 = 8225280 bytes
   Device Boot      Start         End      Blocks   Id  System
/dev/sda1   *           1          13      104391   83  Linux
/dev/sda2              14        1580    12586927+  83  Linux
/dev/sda3            1581        8778    57817935   fd  Linux raid autodetect
/dev/sda4            8779        8909     1052257+   5  Extended
/dev/sda5            8779        8909     1052226   82  Linux swap / Solaris
Disk /dev/sdb: 73.2 GB, 73284976640 bytes
255 heads, 63 sectors/track, 8909 cylinders
Units = cylinders of 16065 * 512 = 8225280 bytes
   Device Boot      Start         End      Blocks   Id  System
/dev/sdb1               1        7052    56645158+  fd  Linux raid autodetect
Disk /dev/md0: 58.0 GB, 58004537344 bytes
2 heads, 4 sectors/track, 14161264 cylinders
Units = cylinders of 8 * 512 = 4096 bytes
Disk /dev/md0 doesn't contain a valid partition table
No devices are given, those mentioned in /proc/partitions (if that exists) are used. But you can specify device as follows:
$ sudo fdisk -l /dev/sda
You can also see the list of paritions by typing the following command:
$ cat /proc/partitions
Sample outputs:
major minor  #blocks  name
   8     0   71567360 sda
   8     1     104391 sda1
   8     2   12586927 sda2
   8     3   57817935 sda3
   8     4          1 sda4
   8     5    1052226 sda5
   8    16   71567360 sdb
   8    17   56645158 sdb1
   9     0   56645056 md0

HowTo: Use cat Command In Linux / UNIX

How do I use cat command in Linux? How do I use cat command in UNIX? How can I use cat command in UNIX or Linux shell scripts?

The cat command is considered as one of the most frequently used commands on Linux or UNIX like operating systems.
It can be used for the following purposes under UNIX or Linux:
  • Display text files on screen.
  • Copy text files.
  • Combine text files.
  • Create new text files.

cat command Syntax

The syntax is as follows:
 
cat filename
cat options filename
cat file1 file2
cat file1 file2 > newcombinedfile
 

Displaying The Contents of Files

To read or read the contents of files, enter:
$ cat /etc/passwd
The above command will display the contents of a file named /etc/passwd. By default cat will send output to the monitor screen. But, you can redirect from the screen to another command or file using redirection operator as follows:
$ cat /etc/passwd > /tmp/test.txt
In the above example, the output from cat command is written to /tmp/text.txt file instead of being displayed on the monitor screen. You can view /tmp/text.txt using cat command itself:
$ cat /tmp/test.txt

Concatenate files

Concatenation means putting multiple file contents together. The original file or files are not modified or deleted. In this example, cat will concatenate copies of the contents of the three files /etc/hosts, /etc/resolv.conf, and /etc/fstab:
$ cat /etc/hosts /etc/resolv.conf /etc/fstab
You can redirect the output as follows using shell standard output redirection:
$ cat /etc/hosts /etc/resolv.conf /etc/fstab > /tmp/outputs.txt
$ cat /tmp/outputs.txt

You can also use a pipe to filter data. In this example send output of cat to the less command using a shell pipe as the file is too large for all of the text to fit on the screen at a time:
$ cat /etc/passwd | less

How Do I Create a File?

You can use cat command for file creation. To create a file called foo.txt, enter:
$ cat > foo.txt
Sample outputs:
This is a test.
To save and exit press the CONTROL and d keys (CTRL+D). Please note that if a file named foo.txt already exists, it will be overwritten. You can append the output to the same file using >> operator:
$ cat >> bar.txt
The existing bar.txt file is preserved, and any new text is added to the end of the existing file called bar.txt. To save and exit press the CONTROL and d keys (CTRL+D).

How Do I Copy File?

The cat command can also be used to create a new file and transfer to it the data from an existing file. To make copy of
$ cat oldfile.txt > newfile.txt
To output file1's contents, then standard input, then file2's contents, enter:
$ cat file1 - file2
A hyphen indicates that input is taken from the keyboard. In this example, to create a new file file2 that consists of text typed in from the keyboard followed by the contents of file1, enter:
$ cat - file1 > file2

cat command options

To number non-blank output lines, enter (only works with GNU cat command version):
$ cat -b /etc/passwd
Sample outputs:
     1 root:x:0:0:root:/root:/bin/bash
     2 daemon:x:1:1:daemon:/usr/sbin:/bin/sh
     3 bin:x:2:2:bin:/bin:/bin/sh
     4 sys:x:3:3:sys:/dev:/bin/sh
     5 sync:x:4:65534:sync:/bin:/bin/sync
     6 games:x:5:60:games:/usr/games:/bin/sh
     7 man:x:6:12:man:/var/cache/man:/bin/sh
     8 lp:x:7:7:lp:/var/spool/lpd:/bin/sh
     9 mail:x:8:8:mail:/var/mail:/bin/sh
    10 news:x:9:9:news:/var/spool/news:/bin/sh
To number all output lines, enter (GNU cat version only):
$ cat -n /etc/passwd
To squeeze multiple adjacent blank lines, enter (GNU cat version only):
$ cat -s /etc/passwd
To display all nonprinting characters as if they were visible, except for tabs and the end of line character, enter (GNU cat version only):
$ cat -v filename

cat Command Abuse

The main purpose of cat is to catenate files. If it's only one file, concatenating it with nothing at all is a waste of time, and costs you a process. For example,
$ cat /proc/cpuinfo | grep model
Can be used as follows:
$ grep model /proc/cpuinfo
Another example,
cat filename | sed -e 'commands' -e 'commands2'
Can be used as follows which is cheaper:
sed sed -e 'commands' -e 'commands2' filename

Linux: Howto Make a Directory Command

How do I make directory under Linux operating systems using the command prompt (bash shell)?

You need to use the mkdir command to create new folders or directories under Linux operating systems.

mkdir command Syntax

mkdir command has the following syntax:
 
mkdir dirname
mkdir dirname1 dirname2
mkdir -p dir1/dir2/dir3
 

Examples

The following command would create a directory called foo:
$ mkdir foo
To list directories, enter:
$ ls
$ ls -l

The following command would create two directories within the current directory:
$ mkdir tom jerry
$ ls -l

The -p option allows you to create parent directories as needed (if parent do not already exits). For example, you can create the following directory structure:
$ mkdir -p ~/public_html/images/trip

Transfer Files From One UNIX Server To Another Server Using Windows / Linux Desktop

How do I securely transfer files from one UNIX / Linux server to another UNIX server using Windows or Linux desktop clients without using ftp client?

You need to use secure sftp or scp client for Windows XP / Vista / 7. Under Linux or Apple Mac OS X desktop you can use regular OpenSSH scp / sftp client to transfer files.

Windows SSH Client

You can use free SFTP, FTP and SCP client for Windows called putty or winscp.
Windows Winscp transfer files from one UNIX / Linux server to another
Fig.01: Winscp transfer files from one UNIX server to another (image credit Winscp website)

Linux / UNIX / OS X SSH scp Client Examples

Use the following command from the server to which you want the files to go. In this example, transfer all files (/var/www/html) from remote server called server1 to local directory called /backup:
scp -r user@server1:/var/www/html/ /backup
In the following example, transfer all files (/var/www/html) from remote server called server1 to another server called server2:
scp -r user@server1:/var/www/html/ user@server2:/var/www/html/

Say hello to rsync

I recommend using rsync command which will only push or download updated files. It can copy locally, to/from another host over any remote shell, or to/from a remote rsync daemon. In this example, copy files from remote server called server1 into /backup directory:
rsync -avz -e ssh user@server1:/var/www/html /backup

HowTo: Linux Rename Files

How do I rename a file under Linux operating systems using command line (bash shell prompt)?

You need to use the mv command to rename files or directories under Linux operating systems. The same command is also used to move files to different directories.

The mv Command Syntax

The syntax is as follows:
 
mv  source target
 
mv [Options]  source target
 

Take: Rename a File Under Linux

Rename a file called curriculum-vitae.txt as resume.txt, enter:
$ mv curriculum-vitae.txt resume.txt
If the target file (resume.txt) is located in the same directory as the source file (curriculum-vitae.txt), then the source file (curriculum-vitae.txt) can only be renamed.

Rename / Move Confirmation (Interactive) Option

You can force to display prompt before overwriting files. The -i option enables interactive option. So if file or directories with the same name already exists in the destination directory, mv will prompt the user:
$ mv -i file2.txt /tmp/
Sample outputs:
mv: overwrite `/tmp/file2.txt'? 

Move / Rename Verbose Option

Pass the -v option to display the name of each file before renaming and/or moving it:
$ mv -v file3.txt /tmp/
Sample outputs:
`file3.txt' -> `/tmp/file3.txt'
To rename file3.txt as file10.bak, enter:
$ mv -v file3.txt file10.bak
Sample outputs:
`file3.txt' -> `file10.bak'

Backup a File

To make a backup of each existing destination file pass the -b option. This option will tell mv to make a backup copy of each file that may be overwritten or removed:
$ touch file10.txt
$ mv -v -b file10.txt /tmp

Sample outputs:
`file10.txt' -> `/tmp/file10.txt'
To view a backup file called file10.bak, enter:
$ ls
Sample outputs:
file10.bak

Moving A file

In this example, move a file called file1.txt to /tmp/ directory, enter:
$ mv file1.txt /tmp/

Wildcards

In this example, move all files and directories, including all the contents of those directories, from the current directory to the directory /home/newdir:
# cd /home/olddir/
# mv * /home/newdir/

Please note that the asterisk (symbol) is nothing but a shell wildcard character that represents all files.

Other mv Command Options

From the mv command man page:
       --backup[=CONTROL]
              make a backup of each existing destination file
      -f, --force
              do not prompt before overwriting
       -i, --interactive
              prompt before overwrite
       -n, --no-clobber
              do not overwrite an existing file
       If you specify more than one of -i, -f, -n, only the final one takes effect.
       --strip-trailing-slashes
              remove any trailing slashes from each SOURCE argument
       -S, --suffix=SUFFIX
              override the usual backup suffix
       -t, --target-directory=DIRECTORY
              move all SOURCE arguments into DIRECTORY
       -T, --no-target-directory
              treat DEST as a normal file
       -u, --update
              move only when the SOURCE file is newer than the destination file or when the destination file is missing
       -v, --verbose
              explain what is being done
       --help display this help and exit
       --version
              output version information and exit

Linux: Set OR Change The Library Path

I've compile and installed a library at /usr/local/lib/libapp2.so -> libapp2.so.1.4.3. How do I set the Library path under Linux operating systems?

You need to use ldconfig config file and ldconfig command which creates the necessary links and cache to the most recent shared libraries found in the directories specified on the command line, in the file /etc/ld.so.conf, and in the trusted directories such as /lib64 or /usr/lib64 (/lib or /usr/lib on 32 bit systems). The /etc/ld.so.conf contains lib settings which can be used to add or delete paths. However, you need to simply drop your config file in /etc/ld.so.conf.d/ directory and it will be used by /sbin/ldconfig to configure dynamic linker run time bindings.

Add Your Path

Create a file called /etc/ld.so.conf.d/myapp.conf:
# vi /etc/ld.so.conf.d/myapp.conf
Add the following path:
/usr/local/lib
Save and close the file.

Activate Your Library Path

You must run the following command to activate path:
# ldconfig

Verify Your New Library Path

# ldconfig -v | less
OR
# ldconfig -v | grep /usr/local/lib
Sample outputs:
/usr/local/lib:
        libGeoIP.so.1 -> libGeoIP.so.1.4.6
        libGeoIPUpdate.so.0 -> libGeoIPUpdate.so.0.0.0
/usr/lib64/mysql:
        libmysqlclient_r.so.15 -> libmysqlclient_r.so.15.0.0
        libmysqlclient.so.15 -> libmysqlclient.so.15.0.0
/lib:
        libutil.so.1 -> libutil-2.5.so

How Do I Delete The Library Path?

Simply, delete the file:
# rm /etc/ld.so.conf.d/myapp.conf
# ldconfig

How Do I Edit The Library Path?

Simply edit the file and reload the changes:
# vi /etc/ld.so.conf.d/myapp.conf
# ldconfig

How Do I Compile Program With Shared Libs And GNU GCC?

You can use the following gcc
$ gcc -Wl,-R/path/to/lib -I/path/to/include -L/path/to/lib -o myAppName mycode.c -llibapp2
See gcc man page for further details.

Further readings:

man ldconfig
man ld
man gcc

Linux: Setup SSH To Tunnel VNC Traffic Though Internet

I have UNIX workstation and Linux server at work and Ubuntu desktop at home. It is recommended that I use ssh tunnel the VNC protocol for secure communication. How do I access my UNIX workstation desktop here at home over the Internet using ssh?

VNC can be accessed over the Internet using ssh protocol. This will improve security as traffic will be encrypted.

Sample Setup

                                       pc22.nixcraft.in
 +----------------+                   +-----------------+
 | Laptop @ Home  |---> Internet ---> | UNIX PC @ Work  |
 +----------------+                   +-----------------+
                                       vncserver port 5901
OR
 +----------------+                   +-----------------+
 | Laptop @ Home  |---> Internet ---> | Router/firewall |
 +----------------+                   | port forwarding |
                                      +-----------------+
                                            | fw.nixcraft.in ssh/tcp22
                                            |
                                          ///\\\
                                          //   \\
                                          /      \
                                       +-----------------+
                                       | UNIX/Linux /OS X|
                                       | at work         |
                                       +-----------------+
                                       pc22.nixcraft.in
                                       vncserver @ port 5901
Your work pc may be directly connected to the Internet. Otherwise most offices have a router and firewall installed. You need to make sure your firewall allows port forwarding for TCP port 22 to your UNIX / OS X / workstation or server called pc22.nixcraft.in. It works as follows:
 +------------+
 | SSH Client |-------> Internet ssh connection with encryption
 | with       |                         |
 | vncviewer  |                         |
 +------------+                         |
                                       \|/
                             +------------------------+
                             | SSH server at port 22  |
                             | Vncserver at port 5501 |
                             +------------------------+
You connect from your local ssh client (localhost) to your ssh server (pc22.nixcraft.in) installed at your work UNIX pc with port forwarding at router / firewall level. I'm assuming that port forwarding is correctly configured at your office. Now, open the terminal and type the following command:
ssh  -N -f -L 5000:localhost:5901 vivek@pc22.nixcraft.i
The above command will start an ssh connection to pc22.nixcraft.in and also listen on port 5000 on localhost and forward vnc connection to port 5901 on pc22.nixcraft.in. Usaully local and remote port numbers are same to avoid confusion:
ssh  -N -f -L 5901:localhost:5901 vivek@pc22.nixcraft.i
Now, you can use vncviewer at your home as follows:
vncviewer localhost:5901
You can also use GUI tool and set VNC server location to localhost:5901
Fig.01: Setup ssh to tunnel VNC traffic over the Internet
Fig.01: Setup ssh to tunnel VNC traffic over the Internet

Once connected you will get desktop login windows or last session window as follows:
Fig.02: VNC in action and more secure using SSH
Fig.02: VNC in action and more secure using SSH

HowTo: UNIX / Linux Open TCP / UDP Ports

How do I open the TCP or UDP ports under UNIX / Linux like operating systems?

A port is an application-specific or process-specific software construct serving as a communications endpoint and it is identified by its number such as TCP port number 80 . It is used by TCP and UDP of the Internet Protocol Suite. A port number is a 16-bit unsigned integer, thus ranging from 0 to 65535.
        UNIX / Linux
    +------------------+
    | Networking stack |
    |      eth0        |
    +------------------+
           |
    +------------------+
    |  Apache process  |--> Binding port 80 @ 202.54.1.1 IP
    +------------------+
In the above example Apache process associates its input and output channel file descriptors (fd) with a port number 80 and an IP address 202.54.1.1. This is known as binding. It is used to send and receive web pages via UNIX / Linux operating system's networking stack (software). In other words communication is done using application ports. When you start the Apache you open port 80 for communication. Common services such as web, mail, pop3 et all use use specifically reserved, well-known port numbers for receiving service requests from client hosts. The well-known ports are defined the Internet Assigned Numbers Authority (IANA). Type the following command to see list well-known of TCP and UDP port numbers:
$ less /etc/services
grep -w 80 /etc/services

Sample outputs:
www  80/tcp  http  # WorldWideWeb HTTP
www  80/udp    # HyperText Transfer Protocol

Privileged Ports

Typically port number less than 1024 are used by well know network servers such as Apache. Under UNIX and Linux like oses root (super user) privileges are required to open privileged ports. Almost all clients uses a high port numbers for short term use. This is also known as an ephemeral port. For example Apache use TCP port 80
  Server                         Client w/ Firefox
 +----------+                    +----------------+
 | Apache   |                    | connects using |
 | TCP Port |                    | an ephemeral   |
 | 80 @     |<-----> eth0 <----> | port #         |
 |202.54.1.2|                    | 46025          |
 +----------+                    +----------------+
The port numbers are divided into three ranges:
  1. Well Known Ports: those from 0 through 1023.
  2. Registered Ports: those from 1024 through 49151
  3. Dynamic and/or Private Ports: those from 49152 through 65535
You can increase local port range by typing the following command (Linux specific example):
# echo 1024 65535 > /proc/sys/net/ipv4/ip_local_port_range
You can also increase or decrease socket timeout (Linux specific example):
# echo 2000 > /proc/sys/net/ipv4/tcp_keepalive_time

Common Well Known Port Numbers

The following are used by UNIX / Windows / Linux / BSD / OS X and all other server operating systems or network devices (see /etc/services file):
  • 21: FTP Server
  • 22: SSH Server (remote login)
  • 25: SMTP (mail server)
  • 53: Domain Name System (Bind 9 server)
  • 80: World Wide Web (HTTPD server)
  • 110: POP3 mail server
  • 143: IMAP mail server
  • 443: HTTP over Transport Layer Security/Secure Sockets Layer (HTTPDS server)
  • 445: microsoft-ds, Server Message Block over TCP

How Do I See Open Ports and Socket Information Under UNIX or Linux?

You can use the netstat command:
# netstat -tulpn
FreeBSD specific example:
# sockstat -l
To list open IPv4 connections use the lsof command:
# lsof -Pnl +M -i4
The ss command is used to dump socket statistics. It allows showing information similar to netstat command. It can display more TCP and state information than other tools
# ss -s
# ss -l
# ss -pl
# ss -o state established '( dport = :smtp or sport = :smtp )'

Examples

Each TCP or UDP port is opened using a UNIX service or daemon such as Apache web server. You can also write a program using C, C++, Perl, Shell or Bash to open any port. You can also use utilities such as nc command .

Apache Server Example (open TCP port 80)

Start the Apache web server under FreeBSD as follows to open TCP port 80:
# /usr/local/etc/rc.d/apache22 forcestart
OR
# /usr/local/etc/rc.d/apache22 start
To displays listening sockets (open ports) under FreeBSD, enter:
# sockstat -l
OR
# netstat -nat | grep LISTEN
You should see port 80 opened under FreeBSD. Under CentOS or Redhat (RHEL) Linux, you can open port 80 using the following commands:
# service httpd start
# chkconfig httpd on
# netstat -tulpn | grep :80

Firewall Configuration

All port numbers are encoded in the transport protocol packet header, and they can be read by other components of the network stack such as firewall. Firewall can be used for port forwarding or denying access to open port. For example, block an abusing IP address called 1.2.3.4 using UNIX firewall. In other words, Apache port is open but it may be blocked by UNIX (pf) or Linux (iptables) firewall. You also need to open port at firewall level. In this example, open tcp port 80 using Linux iptables firewall tool:
# /sbin/iptables -A INPUT -m state --state NEW -m tcp -p tcp --dport 80 -j ACCEPT
# service iptables save

See also:

  1. CentOS / Redhat Linux Iptables Firewall Configuration Tutorial
  2. Redhat / CentOS / Fedora Linux Open Port
  3. FreeBSD Setting up Firewall using IPFW
  4. OpenBSD PF Firewall Script – /etc/pf.conf File

nc Command Example

The nc (or netcat utility) is used for just about anything under the sun involving TCP or UDP. It can open TCP connections, send UDP packets, listen on arbitrary TCP and UDP ports, do port scanning, and deal with both IPv4 and IPv6. In this example, open port 5000 using nc command:
$ nc -l 5000
On a second console or from a second UNIX / Linux machine, connect to the machine and port being listened on:
$ nc localhost 5000
OR
$ nc unix.system.ip.here 5000
In this example, send data from one computer to another:
$ nc -l 5555 > output.txt
Using a second machine, connect to the listening nc process (@ port 5555), feeding it the file which is to be transferred:
$ nc your.unix.systems.ip.here 5555 < input.txt
You can run netstat command to view open ports:
$ netstat -a
$ netstat -nat | grep LISTEN

Sample outputs:
tcp4       0      0  *.5555                 *.*                    LISTEN
tcp4       0      0  10.1.3.29.53           *.*                    LISTEN
tcp4       0      0  192.168.56.1.53        *.*                    LISTEN
tcp4       0      0  115.242.47.238.53      *.*                    LISTEN
tcp4       0      0  127.0.0.1.953          *.*                    LISTEN
tcp4       0      0  127.0.0.1.53           *.*                    LISTEN
tcp4       0      0  127.0.0.1.631          *.*                    LISTEN
tcp6       0      0  ::1.631                *.*                    LISTEN

Python Example

Create a file called echo_server.py:
#!/usr/bin/python
 
# Demo server to open port 8888
# Modified from Python tutorial docs
import socket
 
HOST = '127.0.0.1'       # Hostname to bind
PORT = 8888              # Open non-privileged port 8888
 
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
s.listen(1)
conn, addr = s.accept()
print 'Connected by', addr
while 1:
    data = conn.recv(1024)
    if not data: break
    conn.send(data)
conn.close()
 
Create a file called echo_client.py:
#!/usr/bin/python
 
# Demo client program
# Modified from Python tutorial docs
import socket
 
HOST = '127.0.0.1'     # Set the remote host, for testing it is localhost
PORT = 8000            # The same port as used by the server
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))
s.send('Where there is love there is life')
data = s.recv(1024)
s.close()
print 'Received', repr(data)
 
Save and close the file. Run it as follows:
$ chmod +x *.py
Start server, enter:
$ ./echo_server.py
$ netstat -nat | grep LISTEN

On a second console connect to the localhost and port being listened on using echo_client.py:
$ ./echo_client.py