Summary of useful Unix commands (For oracle)
Basic
Commands
Intermediate Stuff
Advanced Commands
Differences between DOS and NT
Getting information from the OS
PC XStation Configuration
Using Unix Commands with examples
Administracion
Backups
Administrando Tapes
Cron Jobs
AWK
The Basic Commands
|
env displays your current
environment variables.
env | grep FORMS60_PATH display the
value of FORMS60_PATH.
env | grep CDPATH display your CDPATH
(where 'cd' looks for directories.)
|
cal displays a calendar of
the current year.
|
date displays the date.
|
mkdir Create Directory
mkdir -p /home/biju/work/yday/tday
Create directory down many levels in single pass
|
PS1= Changes your prompt.
PS1="developer_6i:" Change your prompt
to 'developer_6i:'
|
ps show processes local to you.
Useful to show which 'shell' you are in.
ps -eaf | grep ora Check if any oracle
processes are running.
|
csh change to the C shell
The C shell is an irritating, less powerful shell with a weird syntax.
Advice: avoid.
|
bsh change to bourne shell.
The Bourne shell is the standard shell. Most scripts are designed to
work in this shell.
|
ksh change to Korn shell. Very
similar to Bourne but with extra, more powerful commands - recommended.
exec ksh start a new process as a korn
shell.
ksh ./forms60_server run the
forms60_server script using the korn shell.
. ./forms60_server As abovet but
preserve the environmnt variables set within (very useful)
ksh rwbld60 & run the rwbld60
executable in background (allows you to do more stuff at the prompt)
|
exit logout / go back a process.
|
wc =
This utility displays a count
of the number of characters, words and lines in a file. The switches
for this utility are
-l print
line count
-c print character count
-w print word count |
ls do a directory listing.
ls -al | pg do a full directory listing
and prompt to stop stuff whizzing off the page.
ls | wc -l count the files in the
current directory.
ls -lasi list files including unix
inode number (the true 'name' of a file, useful if say you have two
files with the same text name)
ls -alt list files in date order
ls -alt | head -10 as above but only
display the first 10
ls -l
$ORACLE_HOME/reports60/printer/admin/spoolcmd.sh Verify that
the spoolcmd.sh file has execute permissions
ls -s | awk '{if ($1 > 50) print $1 " " $2
}' list all files over 50 blocks in size.
ls -alq List files with hidden
characters. Very useful when you cannot delete a file for an unknown
reason, as sometimes
a file can be created with hidden control characters. (very common when
stty not set properly)
ls -al | grep f60 See what forms
executables have been installed (in bin directory.)
|
stty Set terminal characteristics.
stty -a show all settings
stty erase erase_key : allows the
delete key to work. After typing erase, you type a space, then hit the
delete key and only then press enter to run the command.
stty sane reset terminal to something
useable. Very useful when your terminal or session has locked up for
some reason.
Note: you need to press control-j, then type the above command, then
press control-j again to take effect - do not press return.
|
man display manual information.
man finger Get instructions for the
command 'finger.'
|
who show who is logged on
who -T Shows the IP address of each
connection
who -r Shows when the computer was
last rebooted, run-level
|
uname -a show the machine you are on,
plus sometimes other info like session ipaddress.
|
who am i show who INITIALLY logged in
to this terminal session
|
id show who you REALLY are
(after any su commands, for example.)
|
more filename
display contents of a file. |
cat display / concatenate files.
cat file1 file2 > file3 join file1
to file2 and output to file3.
cat formsweb.cfg | pg display the
contents of the webforms configuration file.
|
file File tells you what kind of
file you are looking at, useful to know whether you can edit it or not.
file f60ctl - have a look what the
forms listener start script is.
|
vi load a file in the VI editor
vi base_jini.html View and Edit the
base jinititator html file.
|
kill Kill processes.
kill -9 34567 Kill the process ID 34567
(determined with ps -eaf | pg ). The -9 force termitation of process.
|
rm delete a file.
rm install.log delete the install.log
file.
rm -rf * delete EVERY file in current
directory and below. Use with caution !!
rmdir myjunk delete the directory
'myjunk.'
|
file Display a files type, e.g.
ascii text, data etc.
file formsweb.cfg Confirm the filetype
of formsweb.cfg.
Note - 'file' is very useful if you are unsure about a file that you
want to edit in VI, as editing / catting a data file / executable will
just throw garbage at you and will likely hang your terminal or
session. Never cat these types of files, and to avoid this pitfall use
'file' if you don't know what a files purpose is.
|
cp Copy a file
cp -i testcopy ./copydir
# Copy the testcopy file into the copydir directory.
cp -r * newloc
# To copy all files and
subdirectories to a new location, use -r, the recursive flag
|
mv Move a directory or file |
tail To see the specified number
of lines from the end of the file
tail -n filename
|
head To see the specified number
of lines from the top of the file
head -n filename
|
mkdir
directory_name
creates a directory
rmdir directory_name
delete a directory
cd directory_name
change to a directory
|
diff file1 file2 = Displays
on standard output the differences between file1 and file2.
Options:
-t = ignore white spaces and tabs
-e =
-h =
-i = ignore 'case' letters (A=a) |
Intermediate
stuff.
alias Creates an alias
to some commands
alias ls='ls -al'
Alias the command ls -al to ls
|
& add & to the end of the
command to run in background
nohup command & no hangup - do not terminate the background
job even if the shell terminates
|
bg to take a job to the
background. Before issuing this command, press ^Z, to suspend the
process and then use bg, to put it in the background
|
fg to bring a background job to
foreground
|
jobs to list the current jobs in
the shell
|
su change user
su - oracle switch user to oracle
(prompts for a password) and set the oracle environment.
su oracle switch user to oracle but
DON'T run the oracle environment script.
su root switch user to root, keep old
environment variables as above.
|
touch create a new file / update
timestamp of existing file.
touch repserver.ora Bring forward the
timestamp on the reports server config file.
touch deleteme Create a new, empty
file called 'deleteme.'
|
echo echo strings to screen
echo $DISPLAY display the contents of
the DISPLAY xwindows setting to screen.
echo "ORACLE_HOME=$"$ORACLE_HOME"; export
ORACLE_HOME > my_env_script create a new file
'my_env_script' with a line of code setting the ORACLE_HOME variable to
whatever it is currently.
echo $FORMS60_PATH >> my_env_script INCLUDE
the value of FORMS60_PATH to the existing specified file.
|
grep search for a specified
string or pattern.
find
Search for a file or directory
ps -eaf | grep oracle Show all
processes owned by oracle.
find . -print | grep file.txt Search
everywhere for the specified file.
find . -exec grep "DISPLAY" {} \; -print | pg search
all files for the text string "DISPLAY" - takes a while to run !
grep -v '^#' /etc/oratab
display only the lines in /etc/oratab where the lines do not (-v
option; negation) start with # character (^ is a special character
indicating beginning of line, similarly $ is end of line).
find /ora0/admin -name "*log" -print
Simple use of find - to list all files whose name end in log
under /ora0/admin and its subdirectories
find . -name "*log" -print -exec rm {} \;
to delete files whose name end in log. If you do not use the
"-print" flag, the file names will not be listed on the screen
|
chmod / chown / chgrp Change permissions /
ownership / group on a file
chmod 777 reports60_server give full
access permissions to the reports server startup script.
chmod 755 forms60_server give owner
full permissions and all others read and execute only on the forms
server startup script, i.e. they can't delete it.
chgrp dba wdbstart Change the webdb
startup scripts's group to dba.
chown oracle rwcli60 change ownership
on the reports webcient to oracle.
find . -exec chown oracle {} \; -print Change
ownership on every single file in current directory and lower
directories to oracle (useful if someone has done an install
erroneously as root.)
|
type / whence / which / alias locate a command / inform
whether you can run it from.
type uncompress inform whether the
uncompress command is known and thus runnable.
whence compress inform whether the
compress command is known and thus runnable.
which ls locate the ls command OR an
'alias.'
alias Display a list of aliases.
Useful if something runs, but you cant find it as a script/ executable
etc.
|
du / df Display hard disk
information. (-k Use 1024 byte blocks instead of the default 512)
du display disk usage for all
directories and subdirectories under the current directory.
du -s displays one ‘grand total’ value
for all the files under your current directory.
df -k display disk space free on each
filesystem. Very useful.
|
ulimit shows / sets the maximum
file size limits for a user.
ulimit show your current file size
limit.
ulimit unlimited Attempt to set your
ulimit to unlimited - may need root access.
- useful to check if forms, reports etc is throwing errors when
generating say a huge log file.
|
ftp Invoke the file transfer
protocol file exchange program
ftp ukp99999.uk.oracle.com ftp to
ukp99999 (it will prompt you for a login.)
- and then, once logged in and at the ftp prompt:
bin Change to binary mode (essential
for moving fmbs, fmx's, data files, executables etc.
ascii Change to
ascii mode
send myfile transfer 'myfile' from
your local machine to ukp9999
get fred transfer file 'fred' from
ukp99999 to your local machine.
mget * transfer all files in current
directory of ukp99999 to your local machine.
!pwd check the directory of your local
machine (if on unix.)
pwd check current directory of
ukp99999.
|
lp file_name general print command.
cat repserv.ora | lp -dJIMBO print the
reports server config file to the 'JIMBO' printer.
lpstat -a | pg display status of print
queues etc.
|
Advanced
commands.
|
make relink an executable.
make -f ins_forms60w.sh install > myoutput
2> myerrors Relink oracle forms, but write the screen output
to the 'myoutput' file, and any errors to 'myerrors.' (Note - the 2>
stderr redirect syntax can vary quite a bit between unix systems. )
|
ln create a link to a file.
ln f60desm my_f60desm make a hard link
called ‘my_fred’ for existing file ‘f60desm.’
ln -s rwbld60 my_rwbld60 make a
symbolic link called ‘my_rwbld60’ for existing file ‘rwbld60.’
|
sort sort a file into
alphanumeric order (by lines.)
sort file1 > file2 sort file1 into
a new file, 'file2.'
sort -u file > file3 sort file2
into a new file, 'file3,' but delete duplicate lines
diff file2 file3 > file4 displays
all duplicate lines in original file 'file1' (from above.)
|
sed Invoke the stream editor.
cat forms60_server | sed 's/ORAKUL/ORACLE/g'
> myNEWfile search for all instances of ORAKUL in the
forms60_server file and replace with ORACLE, writing the output to a
new file, 'myNEWfile.' (How to do a global search and replace on a
file.)
ls | sed 's/$/<br>/g' > my_ls.html Place
the html command <br> at the end of each line of the output of
'ls.' Good for formatting the ouptut of unix commands into html for cgi
scripts.
ls | sed 's/^/<b>/g' > my_ls.html Place
an HTML bold marker at the start of each line of the result of the ls
command.
|
tr Translate Characters.
cat basejini.html | tr -s "[\f]" "[\n]" >
new.html Convert newline (formfeeds) into carriage-returns.
This is very useful for fixing ascii files which have been ftp'd in bin
mode. For example, some editors use carriage-return for the EOL marker,
others use linefeed.
|
strings Extract all printable
strings from a file.
strings -a myfile.fmx | pg hunt for
interesting strings in the myfile.fmx file.
|
awk Invoke the awk scripting
language.
who am i | awk '{print $6}' Display
only the 6th field of the output from 'who am i.' (Field 6 is the IP
address of your own terminal session / PC.) This can be used to
automatically set the DISPLAY environment variable for users' logins to
a developer2000 / forms 6i area.
|
cksum provide a checksum of a file.
Very useful for comparing two files of the same size that you suspect
are different.
cksum g60desm; cksum g60desm_patch Test
whether g60desm and g60desm_patch are actually different from eachother
in some way.
|
split Split up a file into smaller
chunks.
Very useful for emailing big files to customers who have small email
limits. You can email the small files instead. split
-10000 bug123456.z splits 'bug123456' into minifiles of 10000
lines each.
cat aa ab ac ad ae af > new_bug123456.z Join
the small bits back together again.
|
tar Invoke the Tape Archive
utility
tar tvf /dev/mydevice > test_file Just
read the contents of the tape on /dev/mydevice and write the contents
to a test file.
tar xvf /dev/mydevice extract all
files from the tape and write them to the current directory.
tar cvf /dev/mydevice * read all files
in current directory and write them to tape.
tar xvf patch123456.tar extract all
files in archive file patch123456.tar to current directory.
|
mount Allows you to mount a
device. For example to read a CD once
insterted into the CD drive.
The syntax for mount is vastly different between UNIX flavours. See the
'how to get started' booklet that comes inside the mini IDS and IAS CD
packs - this shows examples of mount for many common platforms. On
solaris, the CD may mount automatically if you are running 'volume
manager.'
mount -r -F hsfs /dev/my_cd_device /cdrom Solaris:
mount the CD in the /my_cd_device CD drive and call the virtual CD
directory 'cdrom.'
|
compress / uncompress Compress / uncompress a file
to save space. Compressed files have the suffix .Z on them.
compress patch123456.tar compresses a
tarred patch file to a compressed .Z file.
uncompress newpatch.tar.Z -> uncompresses
and re-creates the newpatch.tar file.
|
at Run a command / script at a
specified time and date.
at 23:00 < ./mybatch runs a command
script 'mybatch' at 11pm
Note: This is similar to the unix 'cron' command but easier to use.
Note NT has the 'at' command as well. Tip: in the 'mybatch' batch
script you could fire up 'at' itself again at the end, to repeat the
process indefinately.
at -l Lists pending 'at' jobs.
at -r 992959200.a delete the 'at' job
with the ID specified (given by the above.)
|
finger lists tons of information on
a specific user.
finger usupport | pg display
information on currect usupport logins.
finger -l | pg gives a fuller listing
for all users.
|
xclock Launch the motif clock
window.
Good for determining if xwindows installed + set up properly. Make sure
your DISPLAY environment variable is set to <your-ip-address>:0.0
|
GUI-based system managers
tools, allowing you to add users, add printers etc.
SOLARIS:
|
admintool
|
HPUX:
|
sam
|
AIX:
|
smit
|
Differences
between DOS and
NT with environment variable syntax, particularly with regard to PATH.
In UNIX, directories are separated by forward-slashes and
directory paths are separated by colons. On DOS/NT, the directory
separator is a BACKSLASH and the directory paths are separated by
SEMICOLONS.
|
Example1: How to add a
hard-coded path :
UNIX: export PATH=$PATH":/usr/mynewdirectory"
DOS/NT: Path %PATH%;L:\csserver\bin
Example2: How to add an environment variable (note the colon in speech
marks) :
UNIX: export PATH=$PATH":"$ORACLE_HOME
DOS/NT: Path %PATH%;%ORACLE_HOME
Example3: How to add your current working directory (again note the
colon in speech marks) :
UNIX: export PATH=$PATH":"`pwd`
Example4: Bringing it all together:
UNIX: export
PATH=$PATH":"$APPLE":/u/freddy/myfiles:"`pwd`
|
Getting
information from
the OS
For Solaris = Download and
install the SE Toolkit in /opt/RICHPse if it is not already installed. The SE Toolkit is located at:
http://www.setoolkit.com
OS
|
patchlevel
|
memory
|
I/O Info
|
CPU Info
|
CPU / Memory
|
OS Kernel
|
Sun Solaris
|
showrev -p
|
sysinfo
vmstat
/usr/sbin/prtconf
for general
information + memory
/usr/sbin/psrinfo -v for CPU info
|
sar -d
iostat
|
/opt/RICHPse/bin/se
/opt/RICHPse/examples/toptool.se
sar -u
/usr/bin/mpstat
|
/opt/RICHPse/bin/se
/opt/RICHPse/examples/toptool.se
top
/etc/swap -l
|
/etc/system
/usr/sbin/sysdef
|
Linux
|
|
vmstat 3 5
free
|
vmstat 3 5
|
sar -u 2 5
sar -b
|
top
sar -W 5 5
|
|
HP-UX
|
swlist
|
sam
|
|
|
vmstat -n 2 200
|
|
AIX/RS-6000
|
instfix -ivqk
|
smit or sar
|
|
|
|
|
Windows NT
|
Explorer - help about
|
NT task manager
|
|
|
NT task manager
|
|
System
Prameters
$ifconfig
–a #Display
network
interface configuration
parameters
$arp
–a #Address
resolution
display and control
$drvconfig #drvconfig
- configure
the /devices directory
$disks #disks - creates
/dev
entries for hard disks
attached to the system
$devlinks #devlinks -
adds /dev
entries for miscellaneous devices and
pseudo-devices
Get
OS File System Block Size
For ext2 and ext3 file systems, the command is
/sbin/tune2fs -l <device_name>,
which returns a whole bunch of info on the file system, including block
size. For example:
/sbin/tune2fs -l /dev/hdb1 | grep 'Block size'
Block
size:
4096
Another way to do it could be to create a file with only 1 character
and then perform:
du -b filename
Another one:
If you are using ext2 filesystem, 'dumpe2fs <device>' will do it
Important
Network UNIX files:
/etc/hosts
127.0.0.1
localhost
localhost.domain.name
/etc/nsswitch.dns
hosts:
dns, files
/etc/resolv.conf
domain
domain_name
nameserver
155.33.222.140
search
domain_name
/etc/defaultrouter
127.0.0.1
#Router IP address.
Important
Network LINUX files:
Making the following gross assumptions:
Your IP is:
192.168.0.1
Your Gateway is: 192.168.0.254
Your netmask is: 255.255.255.0
Your nameservers are: 192.168.0.2, 192.168.0.3, and 192.168.0.4
/etc/sysconfig/network
======================
NETWORKING=yes
HOSTNAME=your_machine_name.saa.senate.gov
GATEWAY=192.168.0.254
/etc/hosts
==========
127.0.0.1
localhost.localdomain
localhost
192.168.0.1 your_machine_name.company.com
your_machine_name
192.168.0.254
your_gateway.company.com
your_gateway
(You don't absolutely *need* your gateway in the hosts file, but I feel
it does sometimes speed up some operations)
/etc/sysconfig/network-scripts/ifcfg-eth0
=========================================
DEVICE=eth0
BOOTPROTO=none
ONBOOT=yes
IPADDR=192.168.0.1
NETMASK=255.255.255.0
/etc/resolv.conf
================
search gateway compay_gateway
nameserver 192.168.0.2
nameserver 192.168.0.3
nameserver 192.168.0.4
(The 'search' line is optional. You can have up to 3 'nameserver'
lines,and they don't need to be inside your network)
PC XStation Configuration
- Download the CygWin setup.exe from http://www.cygwin.com.
- Install, making sure to select all the XFree86 optional packages.
- If you need root access add the following entry into the
/etc/securettys file on each server:
<client-name>:0
- From the command promot on the PC do the following:
set
PATH=PATH;c:\cygwin\bin;c:\cygwin\usr\X11R6\bin
XWin.exe :0
-query <server-name>
- The X environment should start in a new window.
Many Linux distributions do not start XDMCP by default. To allow XDMCP
access from Cygwin edit the "/etc/X11/gdm/gdm.conf" file. Under the
"[xdmcp]" section set "Enable=true".
Also edit the file /etc/X11/xdm/xdm-config and comment the line
DisplayManager.requestPort: 0 as
!DisplayManager.requestPort: 0
If you are starting any X applications during the session you will need
to set the DISPLAY environment variable. Remember, you are acting as an
XStation, not the server itself, so this variable must be set as
follows:
DISPLAY=<client-name>:0.0; export DISPLAY
Using
UNIX Commands
To enable doskey mode in Unix
set -o vi
To see errors from Alert log file
cd alertlogdirectory;
grep ORA- alertSID.log
To see the name of a user from his unix id (Provided your UNIX admin
keeps them!)
grep userid /etc/passwd
To see if port number 1521 is reserved for Oracle
grep 1521 /etc/services
To see the latest 20 lines in the Alert log file:
tail -20 alertSID.log
To see the first 20 lines in the Alert log file:
head -20 alertSID.log
To find a file named "whereare.you" under all sub-directories of
/usr/oracle
find /usr/oracle -name whereare.you -print
To remove all the files under /usr/oracle which end with .tmp
find /usr/oracle -name "*.tmp" -print -exec rm -f {}
\;
To list all files under /usr/oracle which are older than a week.
find /usr/oracle -mtime +7 -print
To list all files under /usr/oracle which are modified within a week.
find /usr/oracle -mtime -7 -print
To compress all files which end with .dmp and are more than 1 MB.
find /usr/oracle -size +1048576c -name "*.dmp"
-print -exec compress {} \;
To see the shared memory segment sizes
ipcs -mb
To see the space used and available on /oracle mount point
df -k /oracle
To convert the contents of a text file to UPPERCASE
tr "[a-z]" "[A-Z]" < filename > newfilename
To convert the contents of a text file to lowercase.
tr "[A-Z]" "[a-z]" < filename > newfilename
To kill a process from Unix.
kill unixid
OR
kill -9 unixid
To see the oracle processes
ps -ef | grep SIDNAME
To change all occurrences of SCOTT with TIGER in a file
sed 's/SCOTT/TIGER/g' filename > newfilename
To see lines 100 to 120 of a file
head -120 filename | tail -20
To truncate a file (for example listener.log file)
rm filename; touch filename
To see the versions of all Oracle products installed on the server.
$ORACLE_HOME/orainst/inspdver
Administracion
Crear
usuario = useradd -u user -g Grupo -G otro_grupo -d
directorio_de_arranque -s
shell -c comentarios; -m username
Opciones del useradd:
-u UID
Define el UID de usuario.
-o Utilizar esta opción con -u
para utilizar UID no unicos en el sistema.
-g grupo
Define un ID de grupo o asigna uno existente.
-d dir
Directorio de conexión del usuario.
-s shell
Del de arranque.
-e expira Fecha en que una
presentación expira.
-f inactivo
Establece el número de diás que la presentación
puede estar inactiva.
Agregar grupo = groupadd -g name
Borrar grupo = groupdel name
Borrar usuario = userdel -r username (la
r borra su directorio de trabajo)
Permiso al comenzar = passwd -f usuario(lo
obligo a cambiar el password)
Desmonto Disco = umount label
/oracle/oracle7
Formateo = format
Monto con opcion en archivo
de arranque = mount -a
Montar tape = mt -f /dev/rmt/0mn
rewind, status
Monto = mount /dev/dsk/...
/nombre_dir_al_que_monto
File vfstab = Es como el
congif.sys
Admintool = Herramienta de
administracion de usuarios
SAM = Herramienta de
Administracion de todo el sistema
Agregar disco =
1- Creo
dirmkdir /oracle.xxxx
2- chown dpafumi new_dir
3- chgrp dba new_dir
4- ls /dev/dsk Veo
todos los controllers
usados y los que no
5- df -k Veo los instalados
6- Tomo uno NUEVO del punto 4 que siga
en secuencia, y lo formateo (en gral es .....s2)
7- format /dev/rdsk/c2t2d0s2(este es el
nombre del controlador)
a.PartitionPrint= veo como esta dividido
miro los Nros; y los arreglo
Por ultimo hacer label para que se grabe
todo
8- Pongo el nuevo file system haciendo:
newfs /dev/dsk/c2t2d0s2
9- Lo agrego en orden en el archivo
vfstab
10- umount /oracle/xxx
11- mount -a
Shutdown = shutdown -g 10 -i 5
Hacer imagen de un file system =
1- Tomo un disco y o
divido igual que el origen
2- volcopy -a -F ufs /name_direct
/source_device - /dest_device_con_mismo_numero
Ej: volcopy -a -F ufs
/home /dev/rdsk/c0t3d0s3 - /dev/rdsk/c1t2d0s3
Recompilar devices = reboot --
-r(previamente hacer touch /reconfigure)
Montando
Discos
more
/etc/mnttab
-> muestra config de discos a
levantar
# df -k
Filesystem
kbytes used
avail capacity Mounted on
/dev/dsk/c0t0d0s0 1016122
163304 791851
18%
/
/dev/dsk/c0t0d0s6 1085515
747925 283315
73%
/usr
/proc
0 0
0 0%
/proc
fd
0 0
0 0%
/dev/fd
mnttab
0 0
0 0%
/etc/mnttab
swap 402992 8
402984 1% /var/run
swap
403312 328
402984 1% /tmp
/dev/dsk/c0t0d0s7 31841217 15001837 16520968 48%
/export/home
/export/home/oracle 31841217 15001837 16520968
48%
/home/oracle
format Veo
la cantidad de discos fisicos que tengo
Ej:
0.
c0t0d0 <SUN36G cyl 24620 alt 2 hd 27 sec 107>
/pci@1f,4000/scsi@3/sd@0,0
1.
c0t1d0 <SUN36G cyl 24620 alt 2 hd 27 sec 107>
/pci@1f,4000/scsi@3/sd@1,0
Dice que
tengo dos discos de 36gb c/u
Format
normally displays 2 lines for each disk. The first line contains the
device
name ( under /dev/dsk, /dev/rdsk ) and the "disk label". The 2nd is
the devpath to the device - of limited interest.
This will
give you a list of all the disks detected since last reconfigured
reboot. The disks are numbered from '0' so
if the
last disk is numbered '1' then you have two disks. Within the format
system,
repeat as necessary the following steps:
enter 'p'
(for partition)
enter 'p'
(for print)
This will
show you the way the disk is sliced.
Each slice should have an entry in your /etc/vfstab file if it
is to be
mounted at boot time. enter 'q' to exit out of each menu. Repeat for
all disks.
En unix
cada disco puede tener varias particiones, slice en el caso de solaris,
en cada
slice se montan los filesystem
Cuando le
hago el print del disco c0t0d0 veo:
Part
Tag Flag
Cylinders
Size
Blocks
0 root
wm 0 - 725
1.00GB (726/0/0) 2097414
1 swap
wu 726 - 1451
1.00GB (726/0/0) 2097414
2 backup
wm 0
- 24619 33.92GB (24620/0/0) 71127180
3
unassigned wm
0
0
(0/0/0)
0
4 unassigned wm
0
0
(0/0/0)
0
5
unassigned wm
0
0
(0/0/0)
0
6 usr
wm 1452 -
2227
1.07GB (776/0/0) 2241864
7 home
wm 2228 - 24619 30.85GB
(22392/0/0) 64690488
O sea que
todo ya esta asignado, fijate:
de 0 a
725 es root
de 726 a
1451 es swap
de 1452 a
2227 es usr
de 2228 a
24619 es home
todo el
disco es de 0 a 24619
la 2 es
la de backp, es todo el disco, no se asigna es por default asi y no se
cambia
Cuando
hago el print del disco c0t1d0 veo:
Part
Tag Flag
Cylinders
Size
Blocks
0 root
wm 0 - 725
1.00GB (726/0/0) 2097414
1 swap
wu 726 - 1451
1.00GB (726/0/0) 2097414
2 backup
wm 0
- 24619 33.92GB (24620/0/0) 71127180
3
unassigned wm
0
0
(0/0/0)
0
4
unassigned wm
0
0 (0/0/0)
0
5
unassigned wm
0
0
(0/0/0)
0
6 usr
wm 1452 -
2129
956.42MB (678/0/0) 1958742
7 home
wm 2130 - 24619 30.98GB (22490/0/0) 64973610
Para este
disco que no esta en uso, cambia el nombre de la particion y crea un
filesystem
nuevo.
primero creo un directorio
/u01 con owner oracle y group dba. y con mkfs crea un file system en el
device
donde este libre
y no uses
el format porque podes hacer desastres si no tenes experiencia o donde
probar
antes
device =
c0t1d0 ?
aja, pero
el slice mas grande usa el del home y tenes 30gb para la base.
Salida
del comando mount
/ on
/dev/dsk/c0t0d0s0
read/write/setuid/intr/largefiles/onerror=panic/dev=80000
0 on Wed Apr 23
15:30:55 2003
/usr on /dev/dsk/c0t0d0s6
read/write/setuid/intr/largefiles/onerror=panic/dev=80
0006 on Wed Apr 23
15:30:56 2003
/proc on /proc
read/write/setuid/dev=4080000 on
Wed Apr 23 15:30:55 2003
/dev/fd on fd
read/write/setuid/dev=4140000 on
Wed Apr 23 15:30:56 2003
/etc/mnttab on
mnttab
read/write/setuid/dev=4240000 on Wed Apr 23 15:30:57 2003
/var/run on swap
read/write/setuid/dev=1 on Wed
Apr 23 15:30:57 2003
/tmp on swap
read/write/setuid/dev=2 on Wed Apr
23 15:30:58 2003
/export/home on
/dev/dsk/c0t0d0s7
read/write/setuid/intr/largefiles/onerror=pani
c/dev=800007 on
Wed Apr 23 15:30:58 2003
/home/oracle on
/export/home/oracle
read/write/setuid/dev=800007 on Wed Apr 23 15:31:21 2003
El mkfs
es como el format creo que era mkfs
/dev/dsk/c0t1d0s3 o algo asi y crea el filesystem en ese device y
despues hacer
un mount /dev/dsk/c0t1d0s6 /u01. Entonces monta ese file system en ese
dir y
tenes que agregar la linea en el mnttab para que cada vez que levante
el equipo
monte ese filesystem. La justa no la tengo ahora pero es eso lo que
tenes que
hacer. Le pones
owner a oralce en el u01 y listo, creas el usuario oracle el grupo dba
e
instalas todo, montas el cd como dice el librito de oracle. Mi miedo es
que
este tomado tambien el otro disco y no nos demos cuenta,pero
aparentemente no
lo esta. jejeje tenete los cds de solaris cerca
df -k
| grep '^/dev/'
This lists all locally mounted
partitions/slices.
If you
find a partition that isn't mounted then add it to you /etc/vfstab file. A typical example looks like:
/dev/dsk/c0t0d0s7 /dev/rdsk/c0t0d0s7 /app
ufs 2 yes
-
Make sure
that you can mount it manually first.
run this:
mkdir /a
mount
/dev/dsk/c0t0d0s7 /a
cd /a
ls -l
Partitioning
Partitioning
is where a physical disk is split into several logical area, possibly
for
different filesystems. Under Solaris one disk can contain upto 7
partitions,
each of which may contain a filesystem. When you select a disk in
format you
will note (after selecting 'p' for partioning,
and 'p'
again for print) that partitions are numbered 0-7. You should NEVER
change
partition #2. This by convention is used to represent the whole disk.
A
"partition" is also known as a "slice" - the slice is the
number after the "s" character in a full disk device specification,
e.g;
/dev/dsk/c0t3d0s4
/dev/rdsk/c0t3d0s4 /var ufs 1 no -
^^ ^^
If you do
re-partition a disk you should not that it is quite possible to create
overlapping partitions. In generally this is a very BAD idea, and will
likely
cause file system corruption and data loss at some point in the future.
Filesystems - "How to mount a disk"
Assuming
you identify one or more disks that have no mounted filesystems, you
will
likely need to create a file system on that disk. This is done with the
newfs(8) command. You are quite at liberty to use slice #2 (the whole
disk) for
this purpose, E.g;
# newfs
/dev/rdsk/c0t1d0s2
Before
adding new filesystem to vfstab you should test mount the filesystem,
and check
that sizes etc are as you expect, E.g;
# mount
/dev/dsk/c0t1d0s2 /mnt
# df /mnt
.....
There is
nothing special about "/mnt" it's just an empty directory. You can
create a new mountpoint simply with "mkdir ..."
Check
Hardware:
/usr/platform/`uname
-i`/sbin/prtdiag -v
Check
Packages
installed:
pkginfo
Check
Routes:
netstat
–rn
How
do u
check for ip assigned to a machine with solaris
1. grep
`hostname` /etc/hosts
2.
ifconfig -a
3. ping
-s `hostname`
4.
netstat -in
Memory:
/usr/sbin/prtconf|grep
Memory
OS
instruction set architecture(64 bit or 32 bit):
isainfo
-b -v
isainfo -kv
select address from v$sql where rownum < 2; -- if we get an
address with 16 characters, then we are running 64 bits
Can not login as 'root', getting 'Not
on system console' error message on solaris.
Comment the CONSOLE entry in the "/etc/default/login" file.
See example below.
# If CONSOLE is set, root can only login on that device.
# Comment this line out to allow remote login by root.
#
#CONSOLE=/dev/console
Processor:
psrinfo
-v (Gives the information about processor or processors and their speed)
Query
Disk space
df -k
disk space in kilobytes
du -sk
disk space summary in kilobytes
Display
System Configuration
sysdef
Show
version of unix
uname -a
Change network, change it's ip, mask, bcast
and gateway.
The
easiest way is to execute sys-unconfig. After the process finishes
power down
the box and move it to the new network. When you boot the box it will
ask the
appropriate questions about the network configuration
Force
the kernel change or re-configuration
touch /reconfigure
reboot
Creating Printers
For
Solaris,
admintool for local printers and printers addressed via remote systems.
Depending on the version of
Solaris, admintool may be able to set up network printers, but the
printer
supplier (e.g. HP, Lexmark) may provide
their own utilities for setting up network printers (which will have a
better
set of print drivers).
Typical
system file on one of our E450 general servers, 2GB main
memory, 4 CPU (450Mhz) using solaris 2.6
set
shmsys:shminfo_shmmax=1073741824
set
shmsys:shminfo_shmmin=1
set
shmsys:shminfo_shmseg=200
set
shmsys:shminfo_shmmni=1024
set
semsys:seminfo_semmap=60
set
semsys:seminfo_semmni=1600
set
semsys:seminfo_semmns=2000
set
semsys:seminfo_semmnu=1600
set
semsys:seminfo_semume=80
set
semsys:seminfo_semmsl=2000
set
semsys:seminfo_semopm=100
set
semsys:seminfo_semvmx=32767
INIT = El sistema tienen un
estado por omisión que se guarda en el archivo /etc/inittab, que
contiene una linea con INITDEFAULT y un numero;
con el INIT por
defecto en arranque (=2 Multiusuario en red local).
Durante la sesión se puede
cambiar el INIT con la orden:
$init nn
El el Shutdown
La opción -i permite establecer el INIT del siguiente arranque
sin tocar el INITDEFAULT
Valores INIT.
- Estado de desconexión o máquina desconectada.
Diagnosticos de hardaware.
- Estado monousuario o administrativo (Anula procesos terminales) .
- Equivalente al 1. Diferencia es que los sistemas de archivos no
estan
montados (No hay ni archivos ni procesos).
- Multiusuario. Modo normal de operación. INIT por defecto.
- Para poder usar el sistema remoto de ficheros. Se puede arrancar
directamente o al añadirse los sistemas RFS (Remote File System).
- Estado definido por el usuario.
- Estado firmware. Para hacer pruebas especiales. Arranque del
sistema
desde diferentes archivos de arranque.
- Estado de parada o arranque.
Cuando la auto
inicialización
no está habilitada, se puede reiniciar
un sistema escribiendo los siguiente comandos:
boot -s
SunOS y Solaris
linux single Linux
Shutdown Orden de
desconexion del sistema y se utilizan tambien para pasar a un estado
más bajo. Por omision sutdown permite 60 segundos entre el
sistema de aviso y el comienzo efectivo de la secuencia de desconexion.
Se puede cambiar este tiempo, con la opcion -g (grace), por ejemplo:.
#shutdown -y -g{tiempo}.
Por omision shutdown lleva la maquina al estado 0, preparando asi la
desactivacion de la potencia del sistema. Sin embargo el argumento -i
permite establecer explicitamente el estado init a uno de los estados
disponibles.
# shutdown -y -g45 -i0
Suspendera el sistema, mientras que:
# shutdown -y0 -i6
Volvera a arrancar la maquina. La mayoria de las versiones de
shutdown solo soportan los estados init 0, 5 y 6. Normalmente el
sistema estara en el estado 2 a menos que se esten utilizando
facilidades de la red, en cuyo caso se encontrara en el estado 3
Backups
A una cinta, puedo ponerle mas de un set
de archivos si agrego la opcion 'n' (no rewind) como parte del nombre
del tape. El tape NO se rebobina luego de que se copian los archivos, y
la proxima vez que se use el tape, los archivos seran escritos al final
de los archivos existentes.
TAR = Se utiliza para comprimir,
descomprimir o ver el contenido de un archivo. Sus opciones son:
Ve
el contenido del archivo = tar tvf tar_file
Extraer
archivos= tar xvf tar_file archi1, archi2
Comprimir
un archivo = tar cvf tar_file archivo o *.sql o file1, file2
Comprimir
varios archivos de distintos directorios =
tar cvf tar_file -c
/dir1/* -c /dir2/* tar cvf tar_file -I file_con_lista_de _dirs
Agregar
al comprimido = tar rvf tar_file file
Opciones:
-r Añade
el fichero nombrado al final del tar.
-x Extrae del archivo tar los
fichero que se indiquen.
-t
Lista los nombres de todos los ficheros del archivo tar.
-c Crea
un
nuevo archivo, empezando la escritura al principio.
-v Activa
el
modo de comentario extenso y veo a medida que se procesan.
-w Activa
modo de conformación.
-u El
archivo indicado se agrega al TAR si no existe o si es mas Nuevo que
el que existe
-m Extrae
el
archivo con fecha y hora original (se usa con x)
-o Extrae
los archivos con owner y group de la persona que corre el
programa
CPIO = Como ventaja tiene que
marca los errores y que utiliza varios tapes.
- Para
copiar = ls *.txt | cpio -oc > /dev/rmt/0(-o = copia los arch,
-c = copia los headers_
- Para
listar = cpio -civt < /dev/rmt/0 (-i = lee el contenido del
tape, -v = muestra como ls-l)
- Para
extraer (ATENCION!! Si se creo con relative patch, entonces los
pone donde esta parado, pero si se creo con absolute path, entonces los
pone en el lugar original y sobreescribe los archivos) = cpio -icv <
/dev/rmt/0
cpio -icvfile <
/dev/rmt/0
Administrando un Tape
Las capacidades de las cintas de formato QIC pueden diferir, las mas
comunes para los sistemas SVR4 son 60 MB (QIC 24) y 150 MB (QIC 150).
Las unidades de cinta de mayor capacidad pueden ser incapaces de
escribir a una capacidad mas baja. Si desea compartir datos, consulte
al vendedor para segurarse que la unidad de cinta sea compatible con
las otras unidades implicadas.
La siguiente es una tabla de nombres de dispositivo para las
diferentes funciones soportadas en las cintas SVR4:
Fichero
disp. |
Tipo |
Comentario |
/dev/rmt/c0s0 |
Continuo |
Rebobina
tras la operacion E/S |
/dev/rmt/c0s0n |
Continuo |
No
rebobina tras la operacion E/S |
/dev/rmt/c0s0r |
Continuo |
Retensiona
la cinta antes de E/S
Rebobina tras la operacion E/S |
/dev/rmt/c0s0nr |
Flexible |
Retensiona
la cinta antes de E/S
No rebobina tras la operacion E/S |
/dev/rmt/f1q80 |
Flexible |
Rebobina
tras la operacion E/S |
/dev/rmt/f1q80m |
Flexible |
No
rebobina tras la operacion E/S |
/dev/rmt/f1q80r |
Flexible |
Retensiona
la cinta antes de E/S
Rebobina tras la operacion E/S |
/dev/rmt/f1q80nr |
Flexible |
Retensiona
la cinta antes de E/S
No rebobina tras la operacion E/S |
Si esta utilizando la cinta entera para un unico archivo,
deseara utilizar el dispositivo con rebobinado para reposicionar la
cinta la comienzo despues que se complete la operacion E/S. Con
unidades de cinta continua se puede utilizar cpio para crear y leer
archivos en cinta del mismo modo que un disco flexible. Por ejemplo:
$ find .-print | cpio -ocvB > /dev/rmt/c0s0
Para archivos grandes, este puede ser un proceso penosamente lento,
pero puede incrementarse el tamaño de bloque que cpio utiliza del modo
siguiente:
$ find .-print | cpio -ocv -C 102400 > /dev/rmt/c0s0
La orden tapecntl suele utilizarse para retensionar o reposicionar
cintas magneticas. Esta orden no lee ni escribe en cinta; solamente
posiciona la cinta para las operaciones normales de lectura y
escritura. Algunas de las opciones usadas con la orden tapecntl son:
-w (wind)
Rebobina la cinta
-r (reinitializa)
Reinicializa la unidad de cinta.
-t (tension)
Retenciona la cinta
-e (erease)
Borra completamente una cinta antigua.
-p (position)
Lleva un numero de fichero como argumento
Observese que si se escribe cualquier fichero en una cinta
multifichero excepto el ultimo, todos los ficheros subsiguientes se
perderan.
La orden tar es una orden adicional a cpio para archivar en cinta
(tape archive). La orden tar fue diseñada para archivar principalmete
en bobinas de cinta de nueve pistas, sin embargo, tar es utilizada
frecuentemente para almacenar archivos en disquetes o cintas casete y
muchos sistemas antiguos soportan tar en vez de cpio.
Mientras cpio no permite reemplazar un fichero de un archivo con una
version mas reciente del fichero, sin recrear completamente el archivo,
tar permite añadir nuevos ficheros al final de un archivo existente y
reemplazar ficheros al final de un archivo existente y reemplazar
ficheros en el archivo. El reemplazamiento se implementa en tar
escribiendo el nuevo fichero al final del archivo. Luego cuando los
ficheros son vueltos a cargar, el ultimo fichero reescribira todos los
anteriores con el mismo nombre.
El programa tar es un poco mas dificil de utilizar que cpio ya que
la gestion del archivo en el medio magnetico la debe de hacer el propio
usuario. Es decir, si un usuario crea un archivo con tres versiones de
fichero, debe tener cuidado en que la ultima version sea siempre la que
desee, ya que tar no puede extraer facilmente ninguna, excepto la
ultima ocurrencia de un fichero. Naturalmente, en copias de seguridad
la ultima version es generalmente la que se desea, ya que es la version
mas reciente.
La orden tar no puede continuar sobre un segundo disco cuando el
primero se llena, por lo que sus archivos estan limitados al tamaño
maximo del medio de almacenamiento. La orden tar toma un nombre de
fichero, con la opcion -f (file) como argumento principal y este es
tratado como el nombre del archivo a crear. Puede ser un fichero normal
o un nombre de dispositivo. Los argumentos a continuacion del nombre
del archivo son tratados como los nombres de los ficheros a archivar. A
diferencia de cpio, tar tomara automaticamente todos los subdirectorios
de los directorios designados. Por ejemplo:
$ cd /
$ tar -cf /dev/rdsk/f03ht home/steve usr/src
Archivara los arboles de directorios home/steve y usr/src, con todos
sus subdirectorios, en un disquete de alta densidad.
Si se utiliza - como nombre de archivo, tar utilizara E/S estandar,
por lo que la redireccion esta permitida.
Algunas de las opciones usadas con la orden tar son:
-c (create)
Crea un archivo. Destruye el contenido anterior de ese archivo.
-x (extract)
Sirve para recuperar el archivo. Por ejemplo:
$ tar -xf /dev/rdsk/f03ht
Tar: blocksize = 20
$
para recuperar el archivo en el directorio actual.
-r (replace)
Reemplazar un fichero en un archivo. Por ejemplo:
$ tar -rf /dev/rdsk/f03ht usr/src/steve/bsplit.c
-t (table)
para visualizar una tabla de contenidos de un archivo. por ejemplo:
$ tar -ft /dev/rdsk/f0q15dt
home/steve/datos1
home/steve/datos2
home/steve/cpio.sal
usr/src/bsplit.c
$
-v (verbose)
Produce una lista de los ficheros escritos o leidos desde un archivo.
-w (what)
Hace que tar pida confirmacion al usuario antes de tomar una accion.
Manejando direccionamientos
La shell emplea 4 tipos de
redireccionamiento :
< Acepta la entrada desde un fichero.
> Envía la
salida estándar a un fichero.
>> Añade
la salida a un archivo existente. Si no existe, se crea.
| El comando a la
derecha toma su entrada del comando de la izquierda. El comando de la
derecha debe estar programado para leer de su entrada; no valen todos.
Por ejemplo, ejecutamos el programa "cal" que
saca unos calendarios muy aparentes. Para imprimir la salida del cal, y
tener a mano un calendario sobre papel, podemos ejecutar los siguientes
comandos :
cal 1996 > /tmp/cosa y luego lp /tmp/cosa
o
cal 1996 | lp
Y la interconexión no está limitada
a dos comandos; se pueden poner varios, tal que así:
cat /etc/passwd | grep -v root | cut -d":" -f2- | fold -80 | lp
(del fichero /etc/passwd sacar por impresora
aquellas líneas que no contengan root desde el segundo campo
hasta el final con un ancho máximo de 80 columnas).
Comandos
a ejecutar en diferido : at, batch y cron.
Estos tres comandos ejecutan comandos en diferido
con las siguientes diferencias :
- 1- AT lanza comandos una
sola vez a una determinada hora.
- 2- BATCH lanza comandos
una sola vez en el momento de llamarlo.
- 3- CRON lanza comandos
varias veces a unas determinadas horas, días ó meses.
Estos comandos
conviene tenerlos muy en cuenta
fundamentalmente cuando es necesario ejecutar regularmente tareas de
administración ó de operación. Ejemplos de
situaciones donde éstos comandos nos pueden ayudar son :
- Necesitamos hacer
una grabacion en cinta de determinados ficheros todos los días a
las diez de la mañana y los viernes una total a las 10 de la
noche = CRON.
- Necesitamos dejar
rodando hoy una reconstrucción de ficheros y apagar la
máquina cuando termine ( sobre las 3 de la mañana ), pero
nos queremos ir a casa (son ya las 8) =AT
- Necesitamos lanzar
una cadena de actualización, pero estan todos los usuarios
sacando listados a la vez y la máquina está tumbada =
BATCH
1-
Comando at <cuando> <comando a
ejecutar>
Ejecuta, a la hora determinada, el
<comando>. Puede ser una shell-script, ó un ejecutable.
Este comando admite la entrada desde un fichero ó bien desde el
teclado. Normalmente, le daremos la entrada usando el "here document"
de la shell. El "cuando" admite formas complejas de tiempo. Ejemplos:
* Ejecutar la shell "salu2.sh" que felicita a
todos los usuarios, pasado mañana a las 4 de la tarde:
# at 4pm + 2 days <<EOF
/usr/yo/salu2.sh
EOF
* Lanzar ahora mismo un listado:
at now + 1 minute <<EOF
"lp -dlaserjet /tmp/balance.txt"
EOF
* Ejecutar una cadena de reindexado de ficheros
larguísima y apagar la máquina:
at now + 3 hours <<EOF
"/usr/cadenas/reind.sh 1>/trazas 2>&1;
shutdown -h now"
EOF
* A las 10 de
la mañana del 28 de
Diciembre mandar un saludo a todos los usuarios :
at 10am Dec 28 <<EOF
wall "Detectado un virus en este ordenador"
EOF
* A la una de la tarde mañana hacer una
salvita :
at 1pm tomorrow <<EOF
/home/Salvas/diario.sh
EOF
De la misma manera que el comando nohup,
éstos comandos de ejecución en diferido mandan su salida
al mail, por lo que hay que ser cuidadoso y redirigir su salida a
ficheros personales de traza en evitación de saturar el
directorio /var/mail.
El comando
"at" asigna un nombre a cada trabajo
encolado, el cual lo podemos usar con opciones para consultar y borrar
trabajos:
at -l = Lista todos los trabajos en cola,
hora y día de lanzamiento de los mismos y usuario.
at -d <trabajo> = Borra
<trabajo> de la cola.
Ya que el uso indiscriminado de éste
comando es potencialmente peligroso, existen dos ficheros que son
inspeccionados por el mismo para limitarlo : at.allow y at.deny.
(Normalmente residen en /usr/spool/atjobs ó en /var/a t).
at.allow:si existe,
solo los usuarios que esten aquí pueden ejecutar el comando "at".
at.deny:si existe,
los usuarios que estén aquí no estan autorizados a
ejecutar "at".
El "truco" que
hay si se desea que todos puedan
usar at sin tener que escribirlos en el fichero, es borrar at.allow y
dejar sólo at.deny pero vacío.
2-
Batch.
Ejecuta el comando
como en "at", pero no se le asigna hora; batch lo ejecutará
cuando detecte que el sistema se halla lo suficientemente libre de
tareas. En caso que no sea así, se esperará hasta que se
libere.
3-Cron.
cron is a unix utility that
allows tasks to be automatically run in the background at regular
intervals by the cron daemon often termed as cron jobs.
Crontab (CRON TABle) is a file which contains the schedule of cron
entries to be run and at specified times.
Restrictions
You can execute crontab if your name appears in the file
/usr/lib/cron/cron.allow.
If that file does not exist, you can use crontab if your name does not
appear in the file /usr/lib/cron/cron.deny.
If only cron.deny exists and is empty, all users can use crontab. If
neither file exists, only the root user can use crontab. The allow/deny
files consist of one user name per line.
Commands
export EDITOR=vi ;to specify a editor
to open crontab file.
crontab -e Edit your crontab file, or create
one if it doesn't already exist.
crontab -l Display your crontab file.
crontab -r Remove your crontab file.
crontab -v Display the last time you
edited your crontab file. (This option is only available on a few
systems.)
Crontab file
syntax :-
A crontab file has five fields for specifying day , date and time
followed by the command to be run at that interval. You can also
specify a range of values.
*
*
* * * command to be executed
- - -
- -
| |
| | |
| |
| | +----- day of week
(1 - 7) (monday = 1)
| |
| +------- month (1 - 12)
| | +--------- day of
month (1 - 31)
| +----------- hour (0 - 23)
+------------- min (0 - 59)
Examples
A line
in
crontab file like below removes the tmp files from
/home/someuser/tmp each day at 6:30 PM.
30
18 *
*
*
rm /home/someuser/tmp/*
Changing the parameter values as below
will
cause this command to run at different time schedule below :
30 |
0 |
1 |
1,6,12 |
* |
-- 00:30 Hrs on 1st of Jan, June
& Dec. |
0 |
20 |
* |
10 |
1-5 |
--8.00 PM every weekday (Mon-Fri) only
in Oct. |
0 |
0 |
1,10,15 |
* |
* |
-- midnight on 1st ,10th & 15th of
month |
5,10 |
0 |
10 |
* |
1 |
-- At 12.05,12.10 every Monday &
on 10th of every month |
# Execute the file save.sh every day at 0.05 and send results to a log
file:
5 0 * * * /home/salvas/save.sh.sh
1>>/home/salvas/log 2>&1
# Execute at 2:15pm the first day of each month and do
not send the results:
15 14 1 * * /home/salvas/mensual.sh
1>/dev/null 2>&1
# Execute from Monday to Friday at 10PM
0 22 * * 1-5 shutdown -h now 1>/dev/null
2>&1
# Execute every minute
* * * * * /home/cosas/espia.sh
Environment
cron invokes the command from the user's HOME directory with the shell,
(/usr/bin/sh).
cron supplies a default environment for every shell, defining:
HOME=user's-home-directory
LOGNAME=user's-login-id
PATH=/usr/bin:/usr/sbin:.
SHELL=/usr/bin/sh
Users who desire to have their .profile executed must explicitly do so
in the crontab entry or in a script called by the entry.
Disable Email
By default cron jobs sends a email to the user account
executing the cronjob. If this is not needed put the following command
At the end of the cron job line
>/dev/null 2>&1
Generate a Log File
To collect the cron execution execution log in a file :
30 18 * * * rm /home/someuser/tmp/* >
/home/someuser/cronlogs/clean_tmp_dir.log
Creating the job
1- Create a file called crontab.txt with all your commands
2- Perform the following command:
crontab /yourpath/crontab.txt
3- Now you can see your crontab file with crontab -l
C Shell
Variables
set [variable=value] = Sets the
values for a variable
history = The history variable is
usually set in the user's .login file. El !! repite el ultimo
comando y el !letra, repite el comando que empiece con esa letra
alias [new name] [command]
= Without options prints out the users current list of command aliases.
With only the new command
name as an option lists the associated command for the aliased name.
unalias user command alias or *
= Removes an alias
env = Displays all the rnvironment
variables
LA
HERRAMIENTA AWK
Es una de las cosas más
fáciles de explicar y con lo que más problemas vamos a
tener.
Es una herramienta de
programación. Se aproxima a la programación funcional.
Se divide en patrones
y acciones.
(Acciones asociadas a patrones)
Awk se encarga de leer la entrada
( normalmente la estándar). La divide en registros. (Cada
registro es una linea Separador de registros)
Para cada registro buscamos
concordancia con algún patrón, si se produce concordancia
ejecuta la acción asociada al patrón sobre el registro.
Awk es un traductor. (La entrada
puede ser una cosa, y la salida otra). La
sintaxis de awk es de dos
tipos :
awk patrón {acción}
; patrón {acción} ;...&[fichero de entrada]
awk -f fich.prog[fichero de
entrada]
-f Indica separador de campo.
-v Asignación de valor.
PATRONES :
Los patrones son los
encargados de resolver la entrada.
Funciona como un gigantesco
CASE.
Si no hay patrón para
una acción se ejecuta sobre todas las líneas de ficheros.
Patrón vacío es
cualquier o ningún registro.
Tipos de patrones :
a. Patrón constante : Son
cadenas de caracteres fijas situadas entre barras ' / ' y para las que
se busca la aparición en cualquier punto del registro.
Ej.
/patata/{print}Busca la
cadena patata en cualquier posición
b. Expresiones regulares : Son
combinaciones de caracteres y operadores de carácter. Los
operadores permitidos son
^ Principio de línea.
$ Fin de línea.
[ ] Clase de caracteres.
| OR
* Cero o más apariciones.
+ Una o más apariciones.
? Cero o una aparición.
. Comodín.(Un carácter)
( ) Agrupación.
- Rango.(Utilizando
caracteres ASCII)
Ej. Localice en el
fichero passwd aquellos usuarios cuyo número de expediente es
impar y pertenecen al grupo 109.
Awk
'^f.....[13579]
:.* :109 {print} [etc/passwd]
c. Comparación de cadenas : Permiten
ejecutar acciones en función de determinados valores del
registro de entrada. Para acceder a partes del registro se definen las
variables$1, $2...$199 que contienen automáticamente el primero,
segundo...etc campo del registro. Los comparadores admitidos son :
~ Identificación :
Comprueba si una cadena se ajusta a
un patrón.
!~ No identificación.
== Igualdad.
!= Desigualdad.
<,>...Comparación.
d. Patrones compuestos : Se
obtienen combinando patrones simples mediante los operadores :
&&AND.
||OR
!NOT.
e. Patrones de rango : Se
forman con dos patrones separados por una coma. Awk ejecuta la
acción sobre todos los registros de la entrada situada entre el
registro que coincide con el primer patrón y el que coincida con
el segundo.
f. Patrones BEGIN y END : Son
dos patrones especiales de awk. La acción asociada al
patrón BEGIN se ejecuta antes de leer ninguna línea de la
entrada. Se utiliza para inicializaciones. La acción asociada a
END se ejecuta después de leer el fin de fichero ; se utiliza
para presentaciones de resultados. Ninguno de los dos utiliza un
registro en una línea para la acción. (No se puede hacer
referencia a $1, $2 ..en BEGIN o END porque no hay registros contenidos)
ACCIONES:
Las acciones en awk son
operaciones en lenguaje C que utilizan los campos del registro que
concuerdan con el patrón.La acción vacía es
equivalente a un print.
Variables :
Awk utiliza la misma
nomenclatura de variables que C, pero no exige que una variable
esté declarada para poder usarla. Para poder operar con una
variable debe tener un valor. Además de las variable
definidas por el usuario, awk puede acceder a todas las variables del
SHELL situándolas entre comillas.
Awk también ofrece un
conjunto de variables predefinido. Las más importantes son :
FS Separador de campo.
NF Número de campos del registro.
NR Número de registros leídos.
FILENAME Contiene el fichero de entrada.
ARGV Array de argumentos de la llamada a awk.
Asignación :
-v
nombe = valor
Operadores
:
Permite operadores sobre
caracteres y sobre enteros.
Los operadores permitidos son
entre otros :
1. Aritméticos : +,
-, *, /, %,^...etc.
2. De asignación : =,
+=, -=, ^=, %=...etc.
3. Operadores de comparación : ==, >, <, >=, <=, !=
4. Funciones : tan,
sen, cos, log, exp, sqrt, rand...etc.
5. Funciones sobre cadena : substr, match, length, split...etc.
6. Operadores lógicos : &&,
||, !
7. Unión de dos cadenas : Se pone una detrás de la otra.
Arrays :
La
definición de matrices en awk es idéntica a su
definición en UNIX ; Un conjunto de valores que no tienen
relación de tipo se encuentran unidos lógicamente por un
elemento base y un conjunto de índices.
Los arrays son
unidimensionales. Los índices pueden ser cualquiera.
Para acceder a un elemento de
array tanto en asignación como en obtención de valor se
hace uso de la sintaxis de C, que es la misma que la de pascal.
Para simplificar la
gestión de arrays awk ofrece las siguientes estructuras :
1. delete <BASE> [<INDICE>]Elimina un elemento del array.
2. <subíndice>
in <BASE> Es cierto si
el subíndice existe.
3. for <VARIABLE> in <BASE> : Realiza una
iteración por índice.
sentencia
Funciones definidas
por el usuario :
La
definición de una
función utiliza la sintaxis de C, pero sin tipo.
Sintaxis :
function <nombre>
(lista de parámetros)
{lista de sentencias}
Aquí no hay tipos, pero
puede devolver un valor con la sentencia return. (Si incluye return es
función , sino es procedimiento).
Sentencias de
control :
Las
sentencias de control de
flujo son :
1. if (condicion) sentencia [else][sentencia]
2. while (condición)
sentencia
3. do (sentencia) while
(condición)
4. for (inicialización ;
test ; incremento) sentencia
5. breakFuerza la salida del
bucle.
6. exit finalización de
la entrada
Web Sites with Help
For
quick
start, have a look at the Solaris FAQs in the following site:
http://www.sun.com/bigadmin/faq/
When you
look for patch, help, go to SunSolve:
http://sunsolve.sun.com/pub-cgi/show.pl?target=home
Downlaod
Sun Manual from the following site, when you want to do things in
details:
(they all free)
http://docs.sun.com/
More Sys
adm stuff:
http://www.introcomp.co.uk/solaris/open_boot.html
My site
also has some good resources, all free of course.
http://www.omnimodo.com
Sun's
Online Documentation:
http://docs.sun.com/
The
Solaris FAQ:
http://www.science.uva.nl/pub/solaris/solaris2/
The Sun
Developer:
http://www.sun.com/developers/
For
setting up sendmail:
http://www.sendmail.org
Unix help
from Edinburgh University:
http://www.mcsr.olemiss.edu/unixhelp/
The
Solaris FAQ:
http://www.solarisfaq.com/
Free
Software for Solaris:
http://www.sunfreeware.com
Kempston
Solaris Info:
http://www.kempston.net/solaris/
Intermediate
Unix Training
http://archive.ncsa.uiuc.edu/General/Training/InterUnix/
Security
Links:
http://darkwing.uoregon.edu/~hak/unix_security_info.html