26 January, 2011

pgrep command for listing PID's of currently running processes

pgrep is a bash command that looks through the currently running processes and lists the process IDs which matches the selection criteria to stdout.  All the criteria given as parameters to pgrep have to matched.
$ pgrep fi 
         -- List the PID of process names match with "fi".   

$ pgrep -l fi 
         -- Same as above and process name also get 
             listed.  
 
$ pgrep -vl fi 
         -- List all processes, which name not match    
             with "fi".   

$ pgrep -xl fi 
         -- List all processes, which name exactly match  
             with "fi".  
 
$ pgrep -f sbin 
         --List all processes, which are running from  some 
            sbin folder. It check the command line also.  
 
$pgrep -c fi
         --Show the count of matching processes.  
 
$ pgrep -d, fi 
         -- List the matching process id in CSV format.  
 
$ pgrep -t tty1 
         -- List the process controlling the term tty1. 
 
$ pgrep -u root, jo 
         -- List all processes owned by root and jo. 
 
$ pgrep -u jo gnome
         -- List the process called sshd and owned  by jo.  
 
$ pgrep -n fi 
          -- Show only the newest process.  
 
$ pgrep -o fi 
          -- Show only the oldest process.  
Read rest of entry

30 November, 2010

fork bomb explained...

 


Don't try this @ your home ....Injurious to your computer's health, else  you will be...



Defining the fork bomb . . .

                   A fork bomb is simply a line of some characters entered into the command line of a Unix system, and when the enter key is pressed, within seconds the computer will crash... The little program we entered in to the bash shell act as a process & make multiple copies of itself, setting off a chain reaction and thus quickly exhausting the system’s resources. Most computer operating systems can be  simply crashed or at least brought to a coma stagewhen users, even those without superuser privileges, launches this 'logical bomb' that eat up all memory and CPU time. "Forkbomb" does nothing but launch two or more copies of itself upon startup. Since these copies do the same in turn, this sets off a chain reaction with an exponentially growing number of processes. A fork bomb process "explodes" by recursively  spawning copies of itself using the Unix system call fork().




Working of the 'bomb'...
  
              A process begins  execution when it's execution environment and corresponding threads are created. Before  execution the process has to take a room in the process table, which is a data structure for holding  information required by the kernel to run the process such as...

      > Process state
      > Several process IDs
      > User IDs for determining process privileges
      > Pointer to text structure for shared text areas
      > Pointer to page table for memory management
      > Scheduling parameters,  priority values
      > Timers for resource usage etc...


                A fork bomb creates a large number of processes very quickly and begins execution one after the other by seizing the process table. So whenever a free slot occurs in the process table, another copy of the bomb process enters it and start spawning new bombs. When process table becomes saturated, no new programs may start until another process terminates. Even if that happens, it is not likely that a useful program may be started since the instances of the bomb program will each attempt to take any newly-available slot themselves.


                In addition to using space in the process table, each child process of a fork bomb uses further processor-time and memory. As a result of this, the system and existing programs slow down and become much more unresponsive and difficult or even impossible to use.

see the defenition for fork bomb in wikipedia,
                In computing, the fork bomb is a form of denial-of-service attack against a computer system which makes use of the fork operation (or equivalent functionality) whereby a running process can create another running process. Fork bombs count as wabbits: they typically do not spread as worms or viruses. To incapacitate a system, they rely on the (generally valid) assumption that the number of programs and processes which may execute simultaneously on a computer has a limit.




Some bombs that you can try @ your friend's pc


Fork Bomb in windows

 Open up notepad and type the string below and and save
 it as fork.bat :


   %0|%0


 On double clicking this file,it will lead to total CPU jam 
 by opening a large no. of processes of command prompt.




In UNIX C or C++:


 Compile and execute the following C/C++ code snippet
 in Unix to understand (???) the bomb...

#include <unistd.h>
int main(void)
{
    for(;;)      //for(;;) or while(1) makes an infinite loop
    fork();
    return 0;
}


Bash Shell Fork Bomb


Following is the most coolest one i had ever seen. Take the bash terminal and just type in the following code....

   : (){ : |:& };:

This code is the elegant and most beautiful example of a fork bomb.


:()       _  define ':' , like a function call
{         _  beginning of what to do when we say ':'
    :      _  load another copy of the ':' function into
               memory...
    |      _  ...and pipe its output to...
    :      _  ...another copy of ':' function, which has to be
               loaded into memory (therefore, ':|:' simply gets 
               two copies of ':' loaded whenever ':' is called)
    &     _  disown the functions, that is if the first ':' is
               killed, all of the functions that it has started
               should NOT be auto-killed...
}         _  end of the definition of ':'
;          _  Having defined ':', like in structures etc... we
               should now...
:          _  ...call ':', initiating a chain-reaction: each ':' will
               start two more.


Simply the above function is the same as the code below

forkbomb(){ forkbomb|forkbomb & } ; forkbomb



How to get out of the bomb . . .
             One may have to reboot the system to resume its normal operation destroying all running copies of it. Trying to use a program to kill the rogue processes normally requires creating another process — this is  an impossible task if the host machine has no empty slots in its process table, or no space in its memory structures. Furthermore, as the processes of the bomb are terminated (for example, by using the kill command), process slots become free and the remaining fork bomb threads can continue reproducing again, either because there are multiple CPU cores active in the system, and/or because the scheduler moved control away from kill(8) due to the time slice being used up.


A simple solution is that we can stop (“freez”) the bomb's processes, so that a subsequent kill/killall can terminate them without any of the parts re-replicating due to newly available process slots:


killall -STOP bombprocess
killall -KILL  bombprocess



...Bye till the fire and smoke settles...
Read rest of entry

14 October, 2010

How to add sudo to last command typed in bash terminal



Its most common that you might forget to type in the 'sudo' command along with some other commands. I have faced this problem many times and usually end up by typing the entire command with sudo keyword again. Here is a technique that we can use to avoid retyping the command again after typing sudo.

Consider that i have to install a package called blueman system with the apt package manager via the terminal. Here i am not adding the sudo command before the apt command



Then type the following command to avoid rexecuting the command with all permissions

 $ sudo !!


See here the bash automatically retyped the command with sudo. 



Read rest of entry

11 October, 2010

Troubleshooting Network problems in Ubuntu


                Internet connectivity is one of the important means of communication in todays life. So troubleshooting the problems in our own networks or reconfiguring it for the easiness is not to be praised as a "geekness". In my opinion you don't need to be a geek for setting an internet connection or recovering your machine from a network problem.

Before getting into more troubles just checkout wheather the physical network components (cables, NICs, and so on) are connected properly and working. If everything is right then proceed to the following steps



Checking the Connectivity to a Host

The troubleshooting is done in a bottom up manner. So we will troubleshoot the network layer first and then move on to transport layer. Here we will check the connetivity by pinging  to your default gateway. You should have either configured the default gateway in the /etc/network/interfaces file, i have written a post about it in the last month or leave it to the system using service such as DHCP. To check your default gateway in the actual routing table, use the ip command as follows:

$ ip route


The gateway for the default route in this example is  192.168.0.5 To make sure wheather there is internet connectivity to that gateway, use the ping command as follows, passing the address for your default gateway:

$ ping 192.168.0.5

By default, ping continues until you press Ctrl+c. Other important ping options include the following:
$ ping -a 10.0.0.1
            [You can here a buzzer sound @ each pings]
$ ping -c 4 10.0.0.1 
            [Ping 4 times and exit (default in Windows)]
$ ping -q -c 5 10.0.0.1 
            [Show summary of pings (works best with -c)]
$ sudo ping -f 10.0.0.1 
            [Send a flood of pings (must be root)]
$ ping -i 3 10.0.0.1 
            [Send packets in 3-second intervals]
$ sudo ping -I eth0 10.0.0.1  
            [Set source to eth0 (use if multiple NICs)]



Use the ping flood option with caution, if the packet size is larger than usual  it can cause connections to stand out.

Checking Address Resolution Protocol (ARP)


If you’re not able to ping your gateway, you may have an issue at the Ethernet hardware address layer. The Address Resolution Protocol (ARP) can be used to find information at the MAC layer (hardware layer). 

ARP stands for Address Resolution Protocol, which is used to  find  the  media  access control [MAC] address of a network neighbour for a given IP Address.


To view and configure ARP entries, we can use the arp or ip neighbor command. Arp  command displays  the  kernel’s IPv4 network neighbour cache. It can add entries to the table, delete one or display the current content.

$ arp -v    [List ARP cache entries by name]



Above command will show the names of other computers that the local computer’s ARP cache knows about and the associated hardware type and hardware address of each computer’s NIC. You can disable name resolution to see those computers’ IP addresses instead of the hostname by using the following command:

$ arp -vn     [List ARP cache entries by IP address]

          To delete an entry from the ARP cache, use 
          the -d option:
              $ sudo arp -d 10.0.0.50
                   [Delete address 10.0.0.50 from ARP cache]

          Instead of just letting ARP dynamically learn 
          about other systems, you can add static ARP 
          entries to the cache using the -s option:
               $ sudo arp -s 10.0.0.51 00:0B:6A:02:EC:95


To query a subnet to see if an IP is already in use, and to find the MAC address of the device using it, use the arping command. The arping command continuously queries for the address until the command is ended by typing Ctrl+c. Typically, you just want to know if the target is alive, so you can run one of the following commands:

$ arping -f 10.0.0.50 
[Query 10.0.0.50 and stop at the first reply]

                      
$ arping -c 2 10.0.0.51 
[Query 10.0.0.50 and stop after 2 counts]


Tracing Routes to Hosts

After verifying that you can ping your gateway and even reach machines that are outside of your network you can use traceroute (traceroute package should be installed) to find the problem correctly.

$ traceroute  www.mywebsite.com  
[Follow the route taken to a host]
 

If there are lines of asterisks (*) in the end of  the list  it is because of the firewalls inside your office/college network that block traffic to the target. However, if you see several asterisks before the destination, those can indicate congestion or network failures and points to bottleneck issues.

traceroute command options are
$ traceroute -I www.google.com 
                        Use ICMP packets to trace a route
$ traceroute -p 25 www.google.com 
                        Connect to port 25 in trace
$ traceroute -n www.google.com 
                        Disable name resolution in trace
$ tracepath www.google.com 
                        Use UDP to trace the route

Using the ip command...
You can do the same activities with ip command similar to route command. Here are three different ways to show the same basic routing information:

$ ip route show 
[Display basic routing information]

options for adding and deleting routes with ip are as follows:
$ sudo ip r add 192.168.0.0/24 via 10.0.0.100 dev eth0                  - Add route to interface
$ sudo ip r add 192.168.0.0/24 via 10.0.0.100  
                           - Add route no interface
$ sudo ip r del 192.168.0.0/24 
                           - Delete route

To make a new route permanent, edit the /etc/network/interfaces file and place the information about the new route in that file. For example, to add the route added with the ip command above, add the following lines to /etc/network/interfaces:
       iface eth0 inet static
    address 192.168.0.0
    netmask 255.255.255.0
    gateway 10.0.0.100

Read rest of entry

05 October, 2010

dpkg package manager options

The dpkg utility works at a layer lower than the APT utilities do. APT uses dpkg behind the scenes to manage software on your Ubuntu system. APT and dpkg work similar to the way yum and rpm do on Red Hat–based Linux distributions. Usually, APT will have enough functionality to get you through just about anything, but there are times when dpkg will be needed, such as finding out which package is associated with a given file on your system. Following are some of the common dpkg command options and parameters.


dpkg -c <.deb file> 
Lists files which are installed by the .deb file given (.deb file must be path/filename).

dpkg –I <.deb file> 
Lists information about the .deb given file.


dpkg –p <package> 
Lists information about the package.


dkpg –S <filename> 
Lists the packages where the given file name is found. This can be a path, or just the name of a file.

dpkg –l 
Lists installed packages. This will also take options for more specific info.
dpkg -L <package> 
Lists all the files which have been installed from package (package must have been previously installed).


dpkg –s <package> 
Lists the status of the given package. 

sudo dpkg –i <.deb file>  
Installs the given .deb file.


sudo dpkg –r <package> 
Removes the given package from the system, but leaves files behind.


sudo dpkg –P <package> 
Removes package and config files of given package.

sudo dpkg -x <.deb file> <directory>  
Extracts the files contained in the .deb file to a destination directory. This will reset permissions on the target directory.


Read rest of entry

Changing Permissions with chmod

The chmod command lets you change the access permissions of files and directories. shows several chmod command lines and how access to the directory or file changes.

chmod 0700

The directory’s owner can read or write files in that directory as well as change to it. All other users (except root) have no access.

chmod 0711 
Same as for the owner. All others can change to the directory, but not view or change files in the directory. This can be useful for server hardening, where you prevent someone from
listing directory contents, but allow access to a file in the directory if someone already knows it’s there.

chmod go+r

Adding read permission to a directory may not give desired results. Without execute on, others can’t view the contents of any files in that directory.

chmod 0777

All permissions are wide open.

chmod 0000

All permissions are closed. Good to protect a directory from errant changes. However, backup programs that run as non-root may fail to back up the directory’s contents.

chmod 666

Open read/write permissions completely on a file.

chmod go-rw Don’t let anyone except the owner view, change, or delete the file.

chmod 644

Only the owner can change or delete the file, but all can view it.
Read rest of entry

27 September, 2010

How to wipeout your hard disk perfectly in Ubuntu


Here is a command shread which can be used to in bash terminal of Ubuntu to wipeout your harddisk completely without leaving any chances for further recovery. Please dont try it unless otherwise you dont have no other use with your current system...

$ shread -v -n 1 -z /dev/hda


Options


-f, --force
       change permissions to allow writing if necessary

       -n, --iterations=N
       Overwrite N times instead of the default (25)

       -s, --size=N
       shred this many bytes (suffixes like K, M, G accepted)

       -u, --remove
       truncate and remove file after overwriting

       -v, --verbose
       show progress

       -x, --exact
       do not round file sizes up to the next full block;

       this is the default for non-regular files

       -z, --zero
       add a final overwrite with zeros to hide shredding
Read rest of entry

25 September, 2010

How to assign an IP address in Ubuntu using command line

Computers may be assiged a static IP address or assigned one dynamically. Typically servers and institutions will use a static IP which will not change each time u get connected. Workstation will use Dynamic Host Configuration Protocol (DHCP) for IP address assignment. It is more easily to find a system if the IP address does not change and is static.


Use the Command Line:

    /sbin/ifconfig eth0 192.168.10.12 netmask 255.255.255.0 broadcast 192.168.10.255                  
 
The ifconfig command does NOT store this information permanently. Upon reboot this information is lost. Manually add the network configuration to /etc/network/interfaces  as shown in my next post .
Read rest of entry

IP Configuration in Ubuntu

Here is a howto about the configuring ip using networking related files in Ubuntu / Debian systems.

File: /etc/network/interfaces
    This file contains network interface configuration information  for the ifup and ifdown commands. This is where you configure how your system is connected to the network.

Three important Interfaces are:
        # lo: Loopback interface (it is an internal 
            networking mechanism. It is used to
            test applications...)
        # eth0: First ethernet interface card
        # wlan0: First wireless network interface


Use following command to edit the interfaces file

$ sudo gedit /etc/network/interfaces

Add one or more of the stanzas below 

    Static IP example:
    auto lo
    iface lo inet loopback

    auto eth0
    iface eth0 inet static
            address 208.88.34.106
            netmask 255.255.255.248
            broadcast 208.88.34.111
            network 208.88.34.104
            gateway 208.88.34.110
                   

    Dynamic IP (DHCP) example:
    auto lo
    iface lo inet loopback

    auto eth0
    iface eth0 inet dhcp

    auto eth1
    iface eth1 inet dhcp

    auto eth2
    iface eth2 inet dhcp

    auto ath0
    iface ath0 inet dhcp

    auto wlan0
    iface wlan0 inet dhcp
                   
    Lines  beginning with the word "auto" in the interfaces file are used to identify the physical interfaces to be brought up when ifup is run with the -a option.  (This option  is  used by the system boot scripts.)  Physical interface names should follow the word "auto" on the same line.

GUI Network Tools:

    * NetworkManager or wicd can be used as the GUI tools for the network management. Better use wicd network manager if you have to rely more upon the wireless internet than the wired ones
.
Read rest of entry

24 September, 2010

How to install finch in Ubuntu 10.04


Finch is a text/console-based, modular instant messaging client capable of using AIM/ICQ, Yahoo!, MSN, IRC, Jabber, Napster, Zephyr, Gadu-Gadu, Bonjour, Groupwise, Sametime, SILC, and SIMPLE all at once. Terminal acts as the GUI for the finch... And you might fell in love with it only if you are comfortable with the bash terminal also...

Installing finch in Ubuntu 10.04

take the gnome terminal and type in as follows :

$ sudo apt-get install finch


You can install it also using the Synaptic Package manager also.





Read rest of entry

28 June, 2010

important bash commands for system administration


As you know the terminal is the power tool that every linux user may have to come in contact even once in their computer life. Here is a post about controlling and managing your system using the gnome terminal.

How to shut down the system
 

$shutdown -h now

The word 'now' is enough to shutdown the system at this instant itself. You must be sudo before executing this command. You can specify the time instead of the word 'now' so that the system will shut after that time limit. 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.

       -r     reboots the system after shutdown

       -h    Requests  that  the system be either halted

              or powered off after it has been brought 
              down

       -c    Cancels  a  running  shutdown.   TIME is not 

              specified with this option, the first     
              argument is MESSAGE.

       -k    Only send out the warning messages and 

              disable  logins,  do  not actually bring the 
              system down.

How to take the root shell prompt
 

You can take the root shell prompt using the root password as follows

$ sudo su
 

How to switch between virtual consoles

In most debian based systems there are six switchable VT100-like character consoles available to start the command shell directly on the Linux host. Unless you are in a GUI environment, you can switch between the virtual consoles by pressing the Ctrl - Alt keys and one of the F1 --- F6 keys simultaneously. Each character console allows independent login to the account and offers the multiuser environment. You can get back to the X Window System, normally running on the virtual console 7, by pressing Ctrl - Alt - F7

Alternatively we can use the command chvt to  switch between virtual consoles from the command line
 

$ chvt  3        (switches to 3rd console )

 

How to quit the terminal

Press Ctrl + D to terminate the shell activity.



To create a new user account 


To create a new user account from the terminal type in as follows...


$ adduser carbon


This will add the user with name 'carbon'.  You can remove this user and it's home directory by using the following command.

$ deluser --remove-home carbon
 



Read rest of entry

02 May, 2010

Hacking the cd command

                                                                                                               
The cd command is a bash command in linux is meant for changing the directory in a terminal environment. This post is about a hacking the cd comment.

There is an environment variable called PATH related to the cd command. When you type a command, your system looks through all the directories defined in the PATH environment variable until it finds the command. If it doesn't find the command by the time, it tells you it can't find the file. There's a similar environment variable called CDPATH. Let's use the CDPATH for the tweak.

The basic syntax of cd command is


$ cd somewhere

We can use this CDPATH to avoid typing an entire path of the frequently accessed directories..
Here's how it works.

/home/blogger/Documents/nw/folder1
/home/blogger/Documents/nw/folder2
/home/blogger/Documents/nw/folder3
Here's what you want to do. You want to be able to jump right to the folder2 directory without having to type the entire path. Here's how to set the CDPATH environment variable so that you can do that:

$ export CDPATH=:.:/home/blogger/Documents/nw

This command does not include any of the chapter directories in the CDPATH. That's because you want the CDPATH to define the directory immediately above the directory you want to find. Remember, the system searches the directories listed in the path for the contents you specify on the command line. The argument folder2 is what you're looking for. folder2 exists in the directory /home/blogger/Documents/nw, so that is the directory you want to include in your search CDPATH.

If you need to access the directory folder2, you only need to type this


 $ cd folder2

The command should take you immediately to the directory /home/blogger/Documents/nw/folder1

The problem ???

Suppose you also created the following directories according to the same pattern mentioned earlier:

/home/blogger/Documents/internet/folder1
/home/blogger/Documents/internet/folder2
/home/blogger/Documents/internet/folder3

Naturally, you have to add a new path to your CDPATH environment variable:


$ export CDPATH=:.:/home/blogger/Documents/nw:/home/blogger    
                                                                                           /Documents/internet  

As with the PATH environment variable, you separate different search paths with a colon. The system searches through each path from left to right.

Now issue this command:

$ cd folder2

The problem is that, it puts you in the same place as before, /docs/pub//home/blogger/Documents/nw/folder3. That is not what you expected or desired. But it happened because the cd command searches the CDPATH environment variable paths from left to right. It searched the linuxhacks location first and found folder2. So, that's where it assumed you wanted to go. 

The Solution

One way to avoid the problem described earlier is to define the CDPATH in this way:

$ export CDPATH=:.:/home/blogger/Documents/

If you want to get to folder of internet, you simply type the following:

$ cd internet/folder2


Another cd Trick
This is one among the simplest of all tricks for cd, yet few people know of it. Suppose you are working in the directory /home/blogger/Documents/nw and then you change to the directory /usr/X11R6/lib/X11/fonts/TrueType. You can jump back to the previous directory simply by typing the following:

$ cd  -

This simple command returns you to the last directory you were using before you changed to the current one.

Read rest of entry
 

Terminal Diary | techblog Copyright © 2009 Gadget Blog is Designed by jintu jacob Powered by Blogger