Saturday, April 28, 2012

SSH

mkdir ~/.ssh chmod 700 ~/.ssh ssh-keygen -t rsa

You will be prompted for a location to save the keys, and a passphrase for the keys. This passphrase will protect your private key while it's stored on the hard drive and be required to use the keys every time you need to login to a key-based system:

Generating public/private rsa key pair. Enter file in which to save the key (/home/b/.ssh/id_rsa): Enter passphrase (empty for no passphrase): Enter same passphrase again: Your identification has been saved in /home/b/.ssh/id_rsa. Your public key has been saved in /home/b/.ssh/id_rsa.pub.

Your public key is now available as .ssh/id_rsa.pub in your home folder.

Permission problems with SSH

Ssh is very picky about permissions on the ~/.ssh directory and files. Sometimes you may do something to mess up these permissions. Run the following to fix most permissions problems. You may have to do this on both the remote host and local host.
chmod 700 ~/.ssh 
chmod 600 ~/.ssh/id_rsa 
chmod 644 ~/.ssh/id_rsa.pub 
chmod 644 ~/.ssh/authorized_keys 
chmod 644 ~/.ssh/known_hosts


Also no directory above ~/.ssh can have 'group' or 'other' write permissions.

xargs and exec


find . -name H* -exec ls -l {} \; executes the command ls -l on each individual file.

find . -name H* | xargs ls -l constructs an argument list from the output of the find commend and passes it to ls.

consider if the ouput of the find command produced:
H1
H2
H3

the first command would execute
ls -l H1
ls -l H2
ls -l H3

but the second would execute
ls -l H1 H2 H3


As reborg mentioned, the second is faster because xargs will collect file names and execute a command with as long as a length as possible. Often this will be just a single command.  

This is where -exec breaks down and xargs shows its superiority. When you use -exec to do the work you run a separate instance of the called program for each element of input. So if findcomes up with 10,000 results, you run exec 10,000 times. Withxargs, you build up the input into bundles and run them through the command as few times as possible, which is often just once. When dealing with hundreds or thousands of elements this is a big win forxargs.

Positional Parameters $1 and ${10}

$0 is script name or the command execuated
$# is the number of arguments
#! knows the shell
() executed in sub shell
{} executed in current shell only
$@ but with "" = $* = all parameters in single string
$? exit status of last command
$$ PID of current shell
$! PID of last background job





Positional parameters in a shell script are nothing but the command line arguments passed to a shell script. The following are some of the positional parameters used:
$# -  Total number of arguments
$0 - Command or the script name
$1,$2, $3 - First, second and third args respectively.
$* - All the command line arguments starting from $1.


Let us see this with an example:
[root@gpr ~]# cat cmd
#!/usr/bin/ksh

echo "The total no of args are: $#"
echo "The script name is : $0"
echo "The first argument is : $1"
echo "The second argument is: $2"
echo "The total argument list is: $*"
Output:
[root@gpr ~]# ./cmd 1 2 3 4
The total no of args are: 4
The script name is : ./cmd
The first argument is : 1
The second argument is: 2
The total argument list is: 1 2 3 4
[root@gpr ~]#
As shown in the above output,  $# printed 4 which is the total number of arguments, $0 printed the script name.

Similarly, the command line arguments can be accessed using $1, $2 till $9. However, if the number of command line arguments is more than 9, the same notation cannot be used. Instead, it should be used like ${10}, ${11} and so on. Let us see this with an example:
[root@gpr ~]# cat cmd
#!/usr/bin/ksh

echo "The total no of args are: $#"
echo "The script name is : $0"
echo "The first argument is : $1"
echo "The second argument is: $2"
echo "The incorrect 10th arg is : $10"
echo "The correct 10th arg is : ${10}"
[root@gpr ~]#
Output:
[root@gpr ~]# ./cmd a b c d e f g h i j
The total no of args are: 10
The script name is : ./cmd
The first argument is : a
The second argument is: b
The incorrect 10th arg is : a0
The correct 10th arg is : j
[root@gpr ~]#
As shown above, the correct result appeared when we used ${10}. When $10 is used, the shell interprets it as $1 concatenated with 0, and hence you get the result as a0 ($1 is a). The same terminology will be used for all the arguments after the 9th.

Running Files at boot time


The rc.d System

NetBSD uses individual scripts for controlling services, similar to what System V and Linux use, but without runlevels. This chapter is an overview of the rc.d system and its configuration.

7.1. Basics

The system startup files reside in the /etc directory. They are:
  • /etc/rc
  • /etc/rc.conf
  • /etc/rc.d/*
  • /etc/rc.lkm
  • /etc/rc.local
  • /etc/rc.shutdown
  • /etc/rc.subr
  • /etc/defaults/*
  • /etc/rc.conf.d/*
First, a look at controlling and supporting scripts (also documented in rc(8)).
  • After the kernel has initialized all devices at startup, it starts init(8), which in turn runs /etc/rc.
  • /etc/rc sorts the scripts in /etc/rc.d using rcorder(8) and then runs them in that order. See the rcorder(8) man page for details of how the order of rc.d scripts is determined.
  • /etc/rc.subr contains common functions used by /etc/rc and various rc.d scripts.
  • When shutting down the system with shutdown(8)/etc/rc.shutdown is run, which runs the scripts in /etc/rc.d in reverse order (as defined by rcorder(8)). Note that if you shut down the system using the halt(8)command, these scripts will not be run.
Additional scripts outside of the rc.d directory:
  • /etc/rc.lkm loads or unloads Loadable Kernel Modules (LKMs). See modload(8) and /etc/rc.d/lkm[123].
  • /etc/rc.local is almost the last script called at boot up. This script can be edited by the administrator to start local daemons that don't fit the rc.d model.
rc.d scripts are controlled by a central configuration file, /etc/rc.conf, which loads its default settings from /etc/defaults/rc.conf. If you want to change a default setting, do not edit /etc/defaults/rc.conf; instead, override the setting in /etc/rc.conf.
It is a good idea to read the rc.conf(5) man page to learn about the services that are available to you.
The following example shows how to enable the SSH daemon, which is disabled by default:
# cd /etc; grep ssh defaults/rc.conf
sshd=NO                 sshd_flags=""
# echo "sshd=YES" >> rc.conf
Now sshd(8) will be started automatically at system startup. The next section describes how to start and stop services at any time.
Last but not least, files can be created in the /etc/rc.conf.d/ directory to override the behavior of a given rc.d script without editing the script itself.

7.2. The rc.d Scripts

The actual scripts that control services are in /etc/rc.d. These scripts are automatically run at boot time, but they can be called manually if necessary. The following example shows how to start the SSH daemon that we enabled in the previous section:
# /etc/rc.d/sshd start
Starting sshd.
Later, if you wish to stop the SSH daemon, run the following command:
# /etc/rc.d/sshd stop
Stopping sshd.
Waiting for PIDS: 123.
The rc.d scripts take one of the following arguments:
  • start
  • stop
  • restart
  • status
Some scripts may support other arguments (e.g., reload), but every script will support at least the above commands.
As an example, after adding a new record to a named(8) database, the daemon can be told to reload its configuration files with the following command:
# /etc/rc.d/named reload
Reloading named config files.
Note that all of the commands discussed above will only take action if the particular service is enabled in /etc/rc.conf. It is possible to bypass this requirement by prepending one to the command, as in:
# /etc/rc.d/httpd onestart
Starting httpd.
The above command will allow you to start the httpd(8) service one time. To stop a service that has been started in this manner, pass onestop to the script.

7.3. The Role of rcorder and rc.d Scripts

The startup system of every Unix system determines, in one way or another, the order in which services are started. On some Unix systems this is done by numbering the files and/or putting them in separate run level directories. Solaris relies on wildcards like /etc/rc[23].d/S* being sorted numerically when expanded. Some simply put all the commands that should be started into a single monolithic script (this is the traditional BSD method, and is what NetBSD did before the rc.d system). On modern NetBSD this is done by the rc.d scripts and their contents. Please note that NetBSD does not have multiple runlevels as found in SysV-style systems like Solaris and Linux.
At the beginning of each rc.d script there is a series of commented out lines that have one of the following items in them:
  • REQUIRE
  • PROVIDE
  • BEFORE
  • KEYWORD
These describe the dependencies of that particular script and allow rcorder to easily work either up or down as the situation requires. As an example, here is the ordering information contained in /etc/rc.d/nfsd:
...
 PROVIDE: nfsd
 REQUIRE: rpcbind mountd
...
Here we can see that this script provides the nfsd service and that it requires rpcbind and mountd to be running first. The rcorder(8) utility is used at system startup time to read through all the rc.d scripts and determine the order in which they should be 

=============================

1.Starting a job at unix startup.


The system startup files are located in /etc/rc2.d. You can add a file to this directory with the commands you want to run at system startup. Suppose you want to delete some temp files at system startup, you could put a file named TempFileDel in your /etc/rc2.d with the commands to delete your temporary files, so it'll run every time system 


usually, startup scripts are located in /etc/rc2.d, but this depends on the UNIX/Linux you run and your system's default run level.
But as always The script name must follow some rules:
- There are two kind of scripts, let's say: kill scripts and start scripts. Both stored in /etc/rcX.d.
- kill scripts are executed first, after that start scripts.
- kill scripts name must start with a "K".
- start sctipts name must start with a "S".
- Following the first letter, there must be a two digit number. This lets "rc" know the order for the execution of the sctrips. rc is the "master" script which calls the others. Have a look at your /etc/inittab.
- Finally, a name of your choice.


when "rc" calls this scripts it adds a parameter: start for "S" scripts and stop for "K" scripts. This allows you to use the same script for both operations, just using links.


Well, the UNIX boot process is a little bit more complicated, but for now that's enough.


In your case, you could create a scritp called TempFileDel (contuinuing with shreenmotor's example) which supports "start" and "stop" operations/parameters. For instance:
Code:
#!/bin/ksh
case $1 in
start)
   echo Removing file...
   rm /tmp/somefile;;
stop)
   echo bye!;;
esac


and then:


Code:
ln -s /path/to/TempFileDel /etc/rc2.d/S10TempFileDel
ln -s /path/to/TempFileDel /etc/rc2.d/K10TempFileDel

Ptree



User Commands                                            ptree(1)

NAME

ptree - print process trees

SYNOPSIS

/usr/bin/ptree [-a] [-c] [-z zone] [pid | user] ...

DESCRIPTION

The ptree utility prints the process trees containing the specified pids or users, with child processes indented from their respective parent processes. An argument of all digits is taken to be a process-ID, otherwise it is assumed to be a user login name. The default is all processes.

OPTIONS

The following options are supported: -a All. Print all processes, including children of process 0. -c Contracts. Print process contract member- ships in addition to parent-child relation- ships. See process(4). This option implies the -a option. -z zone Zones. Print only processes in the specified zone. Each zone ID can be specified as either a zone name or a numerical zone ID. This option is only useful when executed in the global zone.

OPERANDS

The following operands are supported: pid Process-id or a list of process-ids. ptree also accepts /proc/nnn as a process-id, so the shell expansion /proc/* can be used to specify all processes in the system. user Username or list of usernames. Processes whose effective user IDs match those given are displayed. SunOS 5.10 Last change: 11 Oct 2005 1 User Commands ptree(1)

EXAMPLES

Example 1: Using ptree The following example prints the process tree (including children of process 0) for processes which match the command name ssh: $ ptree -a `pgrep ssh` 1 /sbin/init 100909 /usr/lib/ssh/sshd 569150 /usr/lib/ssh/sshd 569157 /usr/lib/ssh/sshd 569159 -ksh 569171 bash 569173 /bin/ksh 569193 bash

EXIT STATUS

The following exit values are returned: 0 Successful operation. non-zero An error has occurred.

FILES

/proc/* process files

ATTRIBUTES

See attributes(5) for descriptions of the following attri- butes: ____________________________________________________________ | ATTRIBUTE TYPE | ATTRIBUTE VALUE | |_____________________________|_____________________________| | Availability | SUNWesu | |_____________________________|_____________________________| | Interface Stability | See below. | |_____________________________|_____________________________| The human readable output is Unstable. The options are Evolving.

PS

Process Status


ps -l
Displays processes including those that are in a wait state, similar to the below example.



ps aux | sort -kr 3,3 | head -n 6




-a

List information about all processes most frequently requested: all those except process group leaders and processes not associated with a terminal.
-AList information for all processes. Identical to -e, below.
-cPrint information in a format that reflects scheduler properties as described in priocntl.
The -c option affects the output of the -f and -l options, as described below.
-dList information about all processes except session leaders.
-eList information about every process now running.
-fGenerate a full listing.
-jPrint session ID and process group ID.
-lGenerate a long listing.
-LPrint information about each light weight process (lwp) in each selected process.
-PPrint the number of the processor to which the process or lwp is bound, if any, under an additional column header, PSR.
-yUnder a long listing (-l), omit the obsolete F and ADDR columns and include an RSS column to report the resident set size of the process. Under the -y option, both RSS and SZ will be reported in units of kilobytes instead of pages.
-g grplistList only process data whose group leader's ID number(s) appears in grplist. (A group leader is a process whose process ID number is identical to its process group ID number.)
-n namelistSpecify the name of an alternative system namelist file in place of the default. This option is accepted for compatibility, but is ignored.
-o formatPrint information according to the format specification given in format. This is fully described in DISPLAY FORMATS. Multiple -o options can be specified; the format specification will be interpreted as the space-character-separated concatenation of all the format option-arguments.
-p proclistList only process data whose process ID numbers are given in proclist.
-s sidlistList information on all session leaders whose IDs appear in sidlist.
-t termList only process data associated with term. Terminal identifiers are specified as a device file name, and an identifier. For example, term/a, or pts/0.
-u uidlistList only process data whose effective user ID number or login name is given in uidlist. In the listing, the numerical user ID will be printed unless you give the -f option, which prints the login name.
-U uidlistList information for processes whose real user ID numbers or login names are given in uidlist. The uidlist must be a single argument in the form of a blank- or comma-separated list.
-G gidlistList information for processes whose real group ID numbers are given in gidlist. The gidlist must be a single argument in the form of a blank- or comma-separated list.

Cron

cron is a time-based job scheduler in Unix-like computer operating systems. cron enables users to schedule jobs (commands or shell scripts) to run periodically at certain times or dates



EntryDescriptionEquivalent To
@yearly (or @annually)Run once a year, midnight, Jan. 1st0 0 1 1 *
@monthlyRun once a month, midnight, first of month0 0 1 * *
@weeklyRun once a week, midnight on Sunday0 0 * * 0
@dailyRun once a day, midnight0 0 * * *
@hourlyRun once an hour, beginning of hour0 * * * *
@rebootRun at startup


*    *    *    *    *  command to be executed
┬    ┬    ┬    ┬    ┬
│    │    │    │    │
│    │    │    │    │
│    │    │    │    └───── day of week (0 - 6) (0 is Sunday, or use names)
│    │    │    └────────── month (1 - 12)
│    │    └─────────────── day of month (1 - 31)
│    └──────────────────── hour (0 - 23)
└───────────────────────── min (0 - 59)
crontab - l = list
crontab -e = edit
crontab -r = removes crontab directory
crontab -u username -l

So in terminal print ‘Hello’ every 5 minutes..

# MIN   HOUR   MDAY  MON  DOW   COMMAND 
   */5     *      *     *    *    echo 'Hello'