How to Recover your Ubuntu password

First of all, if you forget your admin Ubuntu password, you will need physical access to the PC in order to recover your password.

Usually Ubuntu install in the grub menu this option:

title        Ubuntu 8.10, kernel 2.6.27-7-generic (recovery mode)
uuid        393ac665-f5c2-488d-b601-b59ba1d5675b
kernel        /boot/vmlinuz-2.6.27-7-generic root=UUID=393ac665-f5c2-488d-b601-b59ba1d5675b ro  single
initrd        /boot/initrd.img-2.6.27-7-generic

That text is part of my /boot/grub/menu.lst of my Ubuntu Linux, so first go to the easiest way to recover the password in Ubuntu.

1. Reboot your system
2. When it is starting, press ESC to get the grub menu
3. Select the option that says (recovery mode)
4. In the next dialog select the root prompt, and get access to a console shell
5. type

passwd admin-username

Remember to change the bold text by your username in Ubuntu, the one that has admin rights.

6. reboot your system, and you are done!

Now Going to the not so easy way, in case you do not have the recovery mode option.

Follow the same procedure as above until step 2.

3. Press e to edit
4. Select the line that starts with kernel…
5. Press e again.
6. Go to the end of the line and add single
7. Press ENTER
8. Press b to boot that kernel, with the single option.
9. Change password, and reboot.

Hope it helps.

[Ref: http://www.go2linux.org/how-to-recover-ubuntu-password]

Keep Your Processes Running Despite A Dropped Connection

I guess you all know this: you are connected to your server with SSH and in the middle of compiling some software (e.g. a new kernel) or doing some other task which takes lots of time, and suddenly your connection drops for some reason, and you lose your labor. This can be very annoying, but fortunately there is a small utility called screen which lets you reattach to a previous session so that you can finish your task.

Installing screen
The installation of screen is very easy. On OpenSuse system go to yast >> software management and search for package “screen” click on “accept” and install the software

I guess that for Fedora, CentOS, SuSE, and Mandriva there are also screen packages that you can install with yum/yast/urpmi/…

Using screen
With screen you can create one or more sessions in your current SSH terminal. Just run
screen to start it. This creates a screen session or window (although you don’t see it as such) in your current SSH terminal:

Press Space or Return to get to the command prompt: Looks like your normal SSH terminal, doesn’t it?

Now I’m going to describe the most important screen commands that you need to control screen. These commands begin with CTRL a to distinguish them from normal shell commands.

Ctrl a c – Creates a new screen session so that you can use more than one screen session at once.
Ctrl a n – Switches to the next screen session (if you use more than one).
Ctrl a p – Switches to the previous screen session (if you use more than one).
Ctrl a d – Detaches a screen session (without killing the processes in it – they continue).

To close a screen session where all tasks are finished you can type: exit
Now let’s play around with it a little bit. In our screen window we run the command: top
Now let’s create another screen session by typing: Ctrl a c
A new, blank screen session opens, and there we run: tail -f /var/log/mail.log

Now you can browse your two screen sessions by running: Ctrl a n or Ctrl a p
To detach a screen session and return to your normal SSH terminal, type: Ctrl a d
Back on your normal SSH terminal, you can run: screen -ls to get a list of your current screen sessions:

There are screens on:
2477.pts-0.server1      (Detached)
2522.pts-0.server1      (Detached)
2 Sockets in /var/run/screen/S-root.

To reconnect to one of these sessions, run: screen -r 2477.pts-0.server1
where 2477.pts-0.server1 is the name of one of the sessions from the screen -ls output.

To leave and finish a screen session, finish all current tasks in it (top can be finished by typing q, tail -f /var/log/mail.log can be finished by typing CTRL c) and then type: exit

You will then fall back to another screen session (if you use more than one) or to the normal SSH terminal, if no more screen sessions are open. If you want to learn more about screen, run
man screen

My Connection Dropped – What Can I Do?
Now let’s assume you compile a kernel in a screen session, something which normally takes a long time, and suddenly your connection drops. Thanks to screen your work isn’t lost. Once your connection is back up, log in to your system with SSH again and run: screen -ls

From the results pick one session (e.g. 2477.pts-0.server1) and reattach to it: screen -r 2477.pts-0.server1

If you picked the right session, you should find your kernel still compiling (if it hasn’t finished in the meantime) so that you can continue your work.

How to Create and Configure robot.txt for Apache web server

Robots.txt” is a regular text file that through its name, has special meaning to the majority of “honorable” robots on the web. By defining a few rules in this text file, you can instruct robots to not crawl and index certain files, directories within your site, or at all. For example, you may not want Google to crawl the /images directory of your site, as it’s both meaningless to you and a waste of your site’s bandwidth. “Robots.txt” lets you tell Google just that.

1) Here’s a basic “robots.txt”:

User-agent: *
Disallow: /

With the above declared, all robots (indicated by “*”) are instructed to not index any of your pages (indicated by “/”). Most likely not what you want, but you get the idea.

2) you may not want Google’s Image bot crawling your site’s images and making them searchable online, if just to save bandwidth. The below declaration will do the trick:

User-agent: Googlebot-Image
Disallow: /

3) The following disallows all search engines and robots from crawling select directories and pages:

User-agent: *
Disallow: /cgi-bin/
Disallow: /privatedir/
Disallow: /tutorials/blank.htm

4) You can conditionally target multiple robots in “robots.txt.” Take a look at the below:

User-agent: *
Disallow: /
User-agent: Googlebot
Disallow: /cgi-bin/
Disallow: /privatedir/

This is interesting- here we declare that crawlers in general should not crawl any parts of our site, EXCEPT for Google, which is allowed to crawl the entire site apart from /cgi-bin/ and /privatedir/. So the rules of specificity apply, not inheritance.

5) There is a way to use Disallow: to essentially turn it into “Allow all“, and that is by not entering a value after the colon(:):

User-agent: *
Disallow: /
User-agent: ia_archiver
Disallow:

Here all crawlers should be prohibited from crawling our site, except for Alexa, which is allowed.

6) Finally, some crawlers now support an additional field called “Allow:”, most notably, Google. As its name implies, “Allow:” lets you explicitly dictate what files/folders can be crawled. However, this field is currently not part of the “robots.txt” protocol, so use it only if absolutely needed, as it might confuse some less intelligent crawlers.

Per Google’s FAQs for web-masters, the below is the preferred way to disallow all crawlers from your site EXCEPT Google:

User-agent: *
Disallow: /
User-agent: Googlebot
Allow: /

Finally this file (robot.txt) must be uploaded to the root accessible directory of your site, not a subdirectory (eg. http://www.mysite.com/robot.txt) it is only by following the above rules will search engines interpret the instructions contained in the file.

How to configure Linux as Internet Gateway for small office

This tutorial shows how to set up network-address-translation (NAT) on a Linux system with iptables rules so that the system can act as a gateway and provide internet access to multiple hosts on a local network using a single public IP address. This is achieved by rewriting the source and/or destination addresses of IP packets as they pass through the NAT system.

[Note] The location of the files (ifcfg-ethx, network. etc ..) mentioned below might be different in different distribution, check the manuals of your distribution to edit the correct file.

Step by Step Procedure

Step 1. Add 2 Network cards to the Linux box

Step 2. Verify the Network cards, check if they installed properly or not

Step 3. Configure eth0 for Internet with a Public (External network or Internet)
# cat ifcfg-eth0

DEVICE=eth0
BOOTPROTO=none
BROADCAST=xx.xx.xx.255    # Optional Entry
HWADDR=00:50:BA:88:72:D4    # Optional Entry
IPADDR=xx.xx.xx.xx
NETMASK=255.255.255.0    # Provided by the ISP
NETWORK=xx.xx.xx.0       # Optional
ONBOOT=yes
TYPE=Ethernet
USERCTL=no
IPV6INIT=no
PEERDNS=yes
GATEWAY=xx.xx.xx.1    # Provided by the ISP

Step 4. Configure eth1 for LAN with a Private IP (Internal private network)
# cat ifcfg-eth1

BOOTPROTO=none
PEERDNS=yes
HWADDR=00:50:8B:CF:9C:05    # Optional
TYPE=Ethernet
IPV6INIT=no
DEVICE=eth1
NETMASK=255.255.0.0        # Specify based on your requirement
BROADCAST=””
IPADDR=192.168.1.1        # Gateway of the LAN
NETWORK=192.168.0.0        # Optional
USERCTL=no
ONBOOT=yes

Step 5. Host Configuration    (Optional)
# cat /etc/hosts
127.0.0.1       nat localhost.localdomain   localhost

Step 6. Gateway Configuration
# cat /etc/sysconfig/network

    NETWORKING=yes
HOSTNAME=nat
GATEWAY=xx.xx.xx.1    # Internet Gateway, provided by the ISP

Step 7. DNS Configuration
# cat /etc/resolv.conf

    nameserver 208.67.222.222      # Primary DNS Server provided by the ISP
nameserver 208.67.220.220      # Secondary DNS Server provided by the ISP

Step 8. NAT configuration with IP Tables
First of all you have to flush and delete existing firewall rules. So flush rules by typing in terminal:

iptables -F
iptables -t nat -F
iptables -t mangle -F

Now delete these chains:

iptables -X
iptables -t nat -X
iptables -t mangle -X

# Set up IP FORWARDing and Masquerading

iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE
iptables -A FORWARD -i eth1 -j ACCEPT

# Enables packet forwarding by kernel (save this setting in /etc/sysctl.conf file)

echo 1 > /proc/sys/net/ipv4/ip_forward

#Apply the configuration

service iptables save
service iptables restart

# Check if iptables is set to start during boot up

chkconfig –list iptables

Step 9. Testing
Ping the Gateway of the network from client system: ping 192.168.2.1
Try it on your client systems: ping google.com

Configuring PCs on the network (Clients)
All PC’s on the private office network should set their “gateway” to be the local private network IP address of the Linux gateway computer.
The DNS should be set to that of the ISP on the internet.

Windows 2000, XP,  Configuration:
Select “Start” + Settings” + “Control Panel”
Select the “Network” icon
Select the tab “Configuration” and double click the component “TCP/IP” for the ethernet card. (NOT the TCP/IP -> Dial-Up Adapter)

Select the tabs:
“Gateway”: Use the internal network IP address of the Linux box. (192.168.1.1)
“DNS Configuration”: Use the IP addresses of the ISP Domain Name Servers.
“IP Address”: The IP address (192.168.XXX.XXX – static) and netmask (typically 255.255.0.0 for a small local office network) of the PC can also be set here.

How to logout the user forcefully

The other day a friend of mine was asking me how to stop all users’ processes and then logout him.
Well maybe the first thing you need is to send a message to the user, so he can actually save his work.
to do that you may use the command wall to let your users know you are about to log them out.

Now at the given time end all of your users’ applications, using pkill

sudo pkill -u username

replace username with every username you have in your system, you can also use.

who | awk ‘{ printf (“%s”,$1 “\n”); }’| grep -v root | xargs -I {} -t pkill -u $1{}

This way you can view all all users’ processes, be careful using this.

You can also use the command skill but in its man page it says it is obsolete.

skill -KILL -u username

Use this command carefully, as you may make your users loose their jobs.

[Ref: http://www.go2linux.org/how-to-kill-users-processes]

Linux Filesystem event notification using inotify

inotify is a file change notification system—a kernel feature that allows applications to request the monitoring of a set of files against a list of events. When the event occurs (read, write, create, delete,mount, un-mount, etc ..), the application is notified. To be useful, such a feature must be simple to use, lightweight with little overhead and flexible. It should be easy to add new watches and painless to receive notification of events.

This can be a handy tool if you need to monitor some directory for files update and as soon as it got updated you need to do some operation.

There is a tool called inotify-tools, which is a C library and a set of command-line programs for Linux providing a simple interface to inotify

Installation:

Fedora
inotify-tools is available through the Fedora Extras repository. Just do: yum install inotify-tools

Gentoo
inotify-tools is available in Gentoo’s official portage tree. It may be masked, in which case read the “MASKED PACKAGES” section of the man page for emerge, then unmask it. Then you can simply: emerge inotify-tools

Ubuntu
sudo aptitude install inotify-tools

Othere
you can donload the source code : here and compile and build your binary using following command
./configure –prefix=/usr && make && su -c ‘make install’

Some of the events that can be monitored for are:

IN_ACCESS – read of the file
IN_MODIFY – last modification
IN_ATTRIB – attributes of file change
IN_OPEN and IN_CLOSE – open or close of file
IN_MOVED_FROM and IN_MOVED_TO – when the file is moved or renamed
IN_DELETE – a file/directory deleted
IN_CREATE – a file/directory created
IN_DELETE_SELF – file monitored is deleted

Java api – here

Advantages of IPv6 – The Next Generation Internet

The most important and most visible improvement brought by the new protocol is the enormous expansion of the available address space. An IPv6 address is made up of 128 bit values instead of the traditional 32 bits. This provides for as many as several quadrillion IP addresses.

However, IPv6 addresses are not only different from their predecessors with regard to their length. They also have a different internal structure that may contain more specific information about the systems and the networks to which they belong.

The following is a list of some other advantages of the new protocol:

Autoconfiguration
IPv6 makes the network “plug and play” capable, which means that a newly set up system integrates into the (local) network without any manual configuration. The new host uses its automatic configuration mechanism to derive its own address from the information made available by the neighboring routers, relying on a protocol called the neighbor discovery (ND) protocol. This method does not require any intervention on the administrator’s part and there is no need to maintain a central server for address allocation—an additional advantage over IPv4, where automatic address allocation requires a DHCP server.

Mobility
IPv6 makes it possible to assign several addresses to one network interface at the same time. This allows users to access several networks easily, something that could be compared with the international roaming services offered by mobile phone companies: when you take your mobile phone abroad, the phone automatically logs in to a foreign service as soon as it enters the corresponding area, so you can be reached under the same number everywhere and are able to place an outgoing call just like in your home area.

Secure Communication
With IPv4, network security is an add-on function. IPv6 includes IPsec as one of its core features, allowing systems to communicate over a secure tunnel to avoid eavesdropping by outsiders on the Internet.

Backward Compatibility
Realistically, it would be impossible to switch the entire Internet from IPv4 to IPv6 at one time. Therefore, it is crucial that both protocols are able to coexist not only on the Internet, but also on one system. This is ensured by compatible addresses (IPv4 addresses can easily be translated into IPv6 addresses) and through the use of a number of tunnels. Also, systems can rely on a dual stack IP technique to support both protocols at the same time, meaning that they have two network stacks that are completely separate, such that there is no interference between the two protocol versions.

Custom Tailored Services through Multicasting
With IPv4, some services, such as SMB, need to broadcast their packets to all hosts in the local network. IPv6 allows a much more fine-grained approach by enabling servers to address hosts through multicasting—by addressing a number of hosts as parts of a group (which is different from addressing all hosts through broadcasting or each host individually through unicasting). Which hosts are addressed as a group may depend on the concrete application. There are some predefined groups to address all name servers (the all name servers multicast group), for example, or all routers (the all routers multicast group).

Configuring IPv6 on OpenSuse 11.1
To disable or enable IPv6 on an installed system, use the YaST Network Settings module. On the Global Options tab, check or uncheck the Enable IPv6 option as necessary. To enable IPv6 manually, enter modprobe ipv6 as root.

 

Using vi to Encrypt Text Files

The disadvantage of using encrypted partitions is that while the partition is mounted, at least root can access the data. To prevent this, vi can be used in encrypted mode.

Use vi -x filename to edit a new file. vi prompts you to set a password, after which it encrypts the content of the file. Whenever you access this file, vi requests the correct password.

For even more security, you can place the encrypted text file in an encrypted partition. This is recommended because the encryption used in vi is not very strong.

MyDNS + MyDNSConfig installation and configuration

MyDNS is a free DNS server for UNIX. It was implemented from scratch and is designed to serve records directly from an SQL database (currently either MySQL or PostgreSQL).

Its primary objectives are stability, security, interoperability, and speed, though not necessarily in that order. MyDNS does not include recursive name service, nor a resolver library. It is primarily designed for organizations with many zones and/or resource records who desire the ability to perform real-time dynamic updates on their DNS data via MySQL.

MyDNS starts and is ready to answer questions immediately, no matter how much DNS data you have in the database. It supports a few frills, including round robin DNS, dynamic load balancing, and outgoing AXFR for non-MyDNS nameservers and is licensed under the GNU General Public License.

Installation:
First make sure you have a working setup of Apache and mysql

Download MyDNSConfig:
# wget http://mesh.dl.sourceforge.net/sourceforge/mydnsconfig/MyDNSConfig-1.1.0.tar.gz
# tar xvfz MyDNSConfig-1.1.0.tar.gz
# cd MyDNSConfig-1.1.0
# mkdir /srv/www/htdocs/mydnsconfig
# cp -rf interface/* /srv/www/htdocs/mydnsconfig

Above “/srv/www/htdocs/” is my web directory

Mysql database setup::
# mysql -u root -p

> CREATE DATABASE mydns;
> GRANT SELECT, INSERT, UPDATE, DELETE ON mydns.* TO ‘mydns’@’localhost’ IDENTIFIED BY ‘mydnspassword’;
> GRANT SELECT, INSERT, UPDATE, DELETE ON mydns.* TO ‘mydns’@’localhost.localdomain’ IDENTIFIED BY ‘mydnspassword’;
> FLUSH PRIVILEGES;
> quit;

Replace the word mydnspassword in the above commands with a password of your choice.

Install the MyDNSConfig MySQL Database:

# mysql -u root -p mydns < MyDNSConfig-1.1.0/install/mydnsconfig.sql

Edit the MyDNSConfig configuration; please make sure you fill in the correct database settings:
# vi /srv/www/htdocs/mydnsconfig/lib/config.inc.php

$conf[“db_type”]        = ‘mysql’;
$conf[“db_host”]        = ‘localhost’;
$conf[“db_database”]        = ‘mydns’;
$conf[“db_user”]        = ‘mydns’;
$conf[“db_password”]        = ‘mydnspassword’;

Installing MyDNS
# wget http://mydns.bboy.net/download/mydns-mysql-1.1.0-1.i386.rpm
# rpm -ivh mydns-mysql-1.1.0-1.i386.rpm

Open the MyDNS configuration file /etc/mydns.conf, fill in the correct database details, allow zone transfers by setting allow-axfr to yes, enable TCP (allow-tcp = yes), and specify a recursive resolver (i.e., a valid nameserver, e.g. from your ISP; e.g. recursive = 213.191.92.86) so that MyDNS can answer queries for domains that it isn’t authoritative for:

# vi /etc/mydns.conf

Finally start the mydns server
# /etc/init.d/mydns start

To log in to the MyDNSConfig interface, open a web browser and enter enter the following URL:

http:///mydnsconfig/

Replace with the IP address of your server.

The default username and password of MyDNSConfig are:

Username: admin
Password: admin

Configuring sudo and adding users to Wheel group

If a server needs to be administered by a number of people it is normally not a good idea for them all to use the root account. This is because it becomes difficult to determine exactly who did what, when and where if everyone logs in with the same credentials. The sudo utility was designed to overcome this difficulty.

With sudo (which stands for “superuser do”), you can delegate a limited set of administrative responsibilities to other users, who are strictly limited to the commands you allow them. sudo creates a thorough audit trail, so everything users do gets logged; if users somehow manage to do something they shouldn’t have, you’ll be able to detect it and apply the needed fixes. You can even configure sudo centrally, so its permissions apply to several hosts.

The privileged command you want to run must first begin with the word sudo followed by the command’s regular syntax. When running the command with the sudo prefix, you will be prompted for your regular password before it is executed. You may run other privileged commands using sudo within a five-minute period without being re-prompted for a password. All commands run as sudo are logged in the log file /var/log/messages.

The sudo configuration file is /etc/sudoers. We should never edit this file manually. Instead, use the visudo command:  # visudo

This protects from conflicts (when two admins edit this file at the same time) and guarantees that the right syntax is used (the permission bits are correct). The program uses Vi text editor.

All Access to Specific Users
You can grant users bob and bunny full access to all privileged commands, with this sudoers entry.
user1, user2  ALL=(ALL) ALL
This is generally not a good idea because this allows user1 and user2 to use the su command to grant themselves permanent root privileges thereby bypassing the command logging features of sudo.

Access To Specific Users To Specific Files
This entry allows user1 and all the members of the group operator to gain access to all the program files in the /sbin and /usr/sbin directories, plus the privilege of running the command /usr/apps/check.pl.
user1, %operator ALL= /sbin/, /usr/sbin, /usr/apps/check.pl

Access to Specific Files as Another User
user1 ALL=(accounts) /bin/kill, /usr/bin/kill, /usr/bin/pkill

Access Without Needing Passwords
This example allows all users in the group operator to execute all the commands in the /sbin directory without the need for entering a password.
%operator ALL= NOPASSWD: /sbin/

Adding users to the wheel group
The wheel group is a legacy from UNIX. When a server had to be maintained at a higher level than the day-to-day system administrator, root rights were often required. The ‘wheel’ group was used to create a pool of user accounts that were allowed to get that level of access to the server. If you weren’t in the ‘wheel’ group, you were denied access to root.

Edit the configuration file (/etc/sudoers) with visudo and change these lines:
# Uncomment to allow people in group wheel to run all commands
# %wheel ALL=(ALL) ALL

To this (as recommended):

# Uncomment to allow people in group wheel to run all commands
%wheel ALL=(ALL) ALL

This will allow anyone in the wheel group to execute commands using sudo (rather than having to add each person one by one).

Now finally use the following command to add any user (e.g- user1) to Wheel group
# usermod -G10 user1