command line tips and tricks

Posted: November 21, 2008 in LINUX, SYSTEM UTILITY
Tags: , ,

Welcome to the first in what I hope will be a series of quick tips and tricks collections. These collections will consist of one and two line commands that don’t warrant entire stand-alone tips to be written for them.

These tips are in no particular order….

Watch a log file as its appended to

tail -f logfile

Redirect a man page to a file

man whatever | col -b > whatever.out

Allow a command to continue execution after logout

nohup mycommand &

Extract tarball when tar has no z option

gzip -dc mytarball.tar.gz | tar xvf -

Display one particular line from a file

set linenumber = 8  # tcsh
linenumber=8        # ksh
sed -n "${linenumber}p" filename

Display current runlevel

who -r

Split lines of text into n-char lines

echo "some line of chars" | fold -w 3

Temporary directories

# /tmp gets cleared at boot, whereas /var/tmp does not

Insert spaces at beginning of each line in vi

:5,16s/^/   /    # for lines 5 through 16, for example

Make init re-examine /etc/inittab

init q

Find out MAC address

arp `uname -n`     # as regular user
ifconfig -a        # ethernet address only displayed when run as root

Display last 10 system reboots

last reboot | head

 

Set backspace to do the right thing

stty erase ^H # sometimes ^? - just do stty erase <hit backspace here!>

Linux – display /proc information

procinfo -a

Solaris – display processor information

/usr/sbin/psrinfo -v
/usr/platform/`uname -i`/sbin/prtdiag | sed -n '/CPUs/,/Mem/p' | sed '/==/d'

Solaris – display memory information

/usr/sbin/prtconf | grep "Memory"

Solaris – display system information

/usr/platform/`uname -i`/sbin/prtdiag | more
/usr/sbin/prtconf | more

Solaris – find out whether kernel modules are 32 or 64-bit

/usr/bin/isainfo -kv

Solaris – kill all matching processes – e.g. all “tip” processes

pgrep -l tip         # check output....
pkill -x tip         # -x to kill only full searchterm matched processes
# for linux - man killall

Solaris – get syslogd to re-read config

pkill -HUP syslogd

Solaris – display numeric uid

/usr/xpg4/bin/id -u username

Solaris – crude halt….

sync;sync;sync;halt

These tips are in no particular order.... 

CDE: Start a dtterm and log it

dtterm -l -lf $HOME/logs/`date +%d%m%y`.log &

Truss a process from start of execution

truss -f -wall -rall -vall whatever

Truss an already running process and output to file

ps -ef | grep myprocess   # find pid
truss -f -wall -rall -vall -o outputfile -p pid

Execute command as different user

su - username -c "my;commands;here"

Stop users logging in

# kill user processes; then
touch /etc/nologin

Set correct permissions on /tmp

chmod 1777 /tmp
ls -lad /tmp         # just checking!

View NIS hosts and passwd files

ypcat hosts
ypcat passwd

Editing crontab

Only use crontab -e - signals change to cron daemon

Check which processes are listening on which ports

lsof -i | grep LISTEN

Print range of lines from a file

sed -n '100,200 p' filename

du without mountpoint traversal

du -kd /

tcsh: redirect stderr only – stupid c-based shells!

( command_here >/dev/tty ) >& /dev/null

tcsh: Stop any alias from being evaluated

\rm -rf /    # i.e. preceed with backslash

Move last file modified

mv `ls -1 -t *.txt | head -1` whatever.txt

Get to telnet prompt from a telnet session

Ctrl-]  # usually....

Disable ftp login for a user

echo "banned_username" >> /etc/ftpusers

ksh: Debug a script

ksh -x ./some_ksh_script.ksh

ksh: Set up r alias – see my article on customising your home environment for details (see /etc)

alias r='fc -e -'

ksh: Remove extensions from filenames

for file in *.ext; do
  mv $file ${file%%.*}
done

Bourne-type shells: Find a file’s hard links

inode=`ls -li /path/and/filename | awk '{print $1}'`
find / -inum $inode -exec ls -li {} \;

ksh: Access positional parameters

$1 $2               # and so on, up to and including 9th param
${10} ${11}			# params >= 10

ksh: Substitute old for new in current pwd then cd

cd old new
e.g.
$ pwd
/path/to/foo/here
$ cd foo bar
/path/to/bar/here

Linux: Make image of floppy disk

dd if=/dev/fd0 of=/path/to/my/new.img

Tail the newest file in a directory

tail -f `ls -1rt | tail -1`

Find out which application caused a core dump

file /some/path/to/core

Sybase – Check status of databases

# su - sybase
Password:
> isql -Usa -Ppassword -w200
1> use master
2> go
1> select status, name from sysdatabases
2> go

Convert single column into two columns line by line

$ cat foofile
a
b
c
d
e
f
$ paste -d: - - < foofile
a:b
c:d
e:f

gunzip and untar with one pipe

gzip -dc SOMEFILE.tar.gz | tar xvf -
# or with GNU tar
tar xvzf SOMEFILE.tar.gz

Solaris: Standard UNIX ping

ping -s xxx.xxx.xxx.xxx

Simple command line arithmetic

echo " ( 10 + 20 ) / 15 " | bc

Solaris: Mount an ISO image located on NFS share

# mount -F nfs ip_address:/path/to/iso/store /mnt
# lofiadm -a /mnt/my_iso.iso
/dev/lofi/1
# mount -F hsfs /dev/lofi/1 /mnt2
# ls /mnt2
...

Solaris: Set server to automatically boot

# Note - to reverse this either use eeprom or just bust
# out with Stop-A

# init 0
ok printenv                # check auto-boot?
ok setenv auto-boot? true
ok boot

Quickly copy a directory tree with tar

cd /path/to/source
tar cvf - ./* | ( cd /dest; tar xvf - )

Access the local shell from an ftp session

# note - this depends on your ftp client
ftp> !
$ echo "Now in local shell"

Truncate a log file

# note - you might need to restart whichever process is
# writing to the file... kill -HUP some_pid may be appropriate
> /log/file
# or
cat /dev/null > /log/file

Solaris: Non-interactive pkgadd without admin files

pkgadd -d ${PKG_PATH} ${PKG} <<EOF
y
y
EOF
# obviously, your supplied input may need to be adjusted

Solaris: Check loaded kernel modules

modinfo | grep -i "whatever"

Add stuff to beginning or end of every line

sed 's/^/stuff/' file > newfile    # at the beginning
sed 's/$/stuff/' file > newfile    # at the end

Solaris: Screwy vi behaviour when using console

# set TERM properly...
TERM=sun-cmd
export TERM

ksh: Using local environment file

# Ensure that you enter the following in your $HOME/.profile file
ENV=${HOME}/.kshrc
export ENV

Create tar archives where files have absolute paths

tar cvf foo.tar /path/to/files

Create tar archives where files have relative paths

cd /path/to
tar cvf foo.tar ./files

Check if two files are hardlinked

ls -li file1 file2  # are inode numbers the same and the files
                    # residing on the same filesystem?

Recursive grep without GNU grep

find / -type f -name "*foo*" -exec grep "bar" {} /dev/null \; -print

Replace spaces in filenames with underscores

ls | while read file; do
  mv "${file}" `echo "${file}" | tr ' ' '_'`
done

see differences between two files

diff file_1 file_2
# also see
man comm

count processes running on system (-1 to remove header)

echo $((`ps -ef | wc -l` - 1))

recursive wget

cd /where/to/put/files; wget -r http://somewhere.com/somedir

check number of fields on each line (delimited by |)

awk 'BEGIN {FS="|"} {print NF}' somefile

perform verbose nmap scan

nmap -v hostname

perform UDP scan

nmap -sU -v hostname

renice a process to increase priority

renice -10 -p 123

remove all .log files in /tmp that haven’t been modified in over two days

find /tmp -type f -name "*.log" -mtime +2 -exec rm -rf '{}' \;

indent output from a command

my_command | sed 's/^/   /'

Print last four characters in each line

awk '{printf("%s\n",substr($0,length($0)-3))}' foofile

output man page to file

man foo | col -b > outfile

view man page that’s not yet installed

nroff -man man_file | more

show unprintable characters with cat

cat -vET somefile

ls -l sorted by filesize

ls -l | sort -k5,5rn

extract a single file from a tar

tar cvf foo.tar single_file

ksh/bash change to previous directory

cd -

bash / ksh95 variable pattern substitution

$ FOO="bash"
$ echo "${FOO/ba/k}"
ksh

my standard useradd line

useradd -m -d /home/kwaldron -c "Kevin Waldron" -s "/bin/ksh" kwaldron && passwd kwaldron

perform snmpwalk of localhost

snmpwalk -v 1 localhost -c community_string | more

ksh – left pad numbers with zeros

$ typeset -Z8 foo
$ foo=1234
$ echo $foo
00001234

find files larger than 300k

find / -size +300k -ls 2> /dev/null

find two different types of file extensions

find . \( -name "*.c" -o -name "*.c" \) -print

remove the first character from a variable

$ foo=12345
$ echo "${foo#?}"
2345

find what program has caused a core file

file /path/to/core

convert from ebcdic to ascii

dd if=/yourdir/your-ebcdicfile of=/yourdir/your-asciifile conv=ascii

replace current process with another (i.e. don’t fork, just exec)

exec newprocess

display unprintable filenames

ls -lb somedir

correct permissions on /tmp and /var/tmp

chmod 1777 /var/tmp
# or
chmod a=rwx,+t /var/tmp

recover corrupt terminal

stty sane
echo "^O" 	# Ctrl-V Ctrl-O

ring the terminal bell

/usr/bin/echo "\a"

bash substitution in previous command

ls
^l^p
ps

crontab location

/var/spool/cron/crontabs	# solaris
/var/spool/cron			# linux

GNU grep

# show 2 lines either side of match
grep -C 2 "somestring" filename
# show 2 lines after match
grep -A 2 "somestring" filename
# show 2 lines before match
grep -B 2 "somestring" filename

grep for a word

grep "\<something\>" somefile

GNU sed relative addressing

sed -n '/searchstring/,+2 p' filename
# i.e. to print line containing searchstring plus the next two lines

convert dos file to unix (remove carriage returns)

dos2unix < infile.dos > outfile.unix  # dos2ux on HP-UX
tr -d '\r' < infile.dos > outfile.unix
# the unix2dos command (ux2dos) exists for the opposite conversion
# or just ftp the file in ascii mode in the first place, but beware that
# all sftp transfers are binary only

searching for a literal $ in a file

grep '\$' filename
# or fgrep / grep -F
fgrep '$' filename

bash – funky curly brace substitution

ls file{1,3,4}
# to list file1 file3 and file4

ksh – alias r

alias r='fc -e -'
# then
r vi
# will execute last vi command

copy directory tree

cd /src; tar cvf - ./* | ( cd /dest; tar xvpf - )
cd /src; find . -depth -print | cpio -pvdum /dest

show OS and kernel info

uname -a

wc -l without the filename

wc -l < filename
# or
wc -l filename | awk '{print $1}'
# as opposed to
wc -l filename

list mounts

mount		# no arguments
df -k

show my history

history

disregard alias

# rm -r dir
rm: descend into directory `dir'? n
# \rm -r dir

su and inherit user environment

su - [ user ] [ -c "commands ]

set terminal type

export TERM=vt100

ksh – concise tests

[[ -f foo ]] || {
  echo "Foo doesn't exist" >&2
  exit 2
}

traceroute using ICMP

traceroute -I destination

using last argument of previous command in bash

$ echo foohost
foohost
$ ping !$
ping foohost
.
.
.

make an alias global for all users

- add entry to /etc/profile

check for listening ports

netstat -an | grep LISTEN

define sendmail smarthost for relaying in sendmail.cf

DSsomehost.foodomain.com

copy, preserving permissions, ownership and timestamps

cp -p source dest
# recursively too
cp -Rp source dest

create soft link

ln -s file_to_link link_name
# hard link
ln file_to_link link_name

create directories including non-existent parents

mkdir -p /some/lengthy/dir/tree

recursive chown

chown -R user:group /some/dir

recursive chmod

chmod -R 744 somedir

cut the last character from a string

a="somestring"
echo ${a} | cut -c${#a}
# other ways to do this
echo "${a#${a%?}}"
# or
echo "${a}" | sed 's/.*\(.\)/1/'
# or
echo "${a}" | nawk '{print substr($0, length($0))}'
# or
expr "${a}" : '.*\(.\)'
# or
echo "${a}" | tail -2c

truncate log file

cp /dev/null logfile
> logfile
cat /dev/null > logfile
# may need to restart
kill -HUP `cat /var/run/syslog.pid`

the true use of cat – to conCATenate files

cat file1 file2 file3 > finalfile

show subdirectories only in an ls listing

ls -l | grep "^d"
# recursively
find . -type d -exec ls -ld {} \;

show information about directory entry itself (not contents)

ls -ld dir
# show size
ls -ls
# show inode numbers
ls -lia

recursive grep

find . -type f -exec grep "somestring" {} /dev/null \;

sed to replace \ with \\

sed -e 's_\\_\\\\_g'

getent

getent hosts hostname
# using getent with ssh
ssh -l admin `get hosts hostname | awk '{print $1}'`

view available signals

kill -l

search for strings in a binary file

strings binary_name

show current runlevel

who -r
(or on some Linuxen - runlevel)

show uptime and processor run queue averages

uptime
# or with who output
w

stop people logging in

touch /etc/nologin

temporarily change your prompt

PS1='$ '
export PS1

bourne based shells – show current environment variables

env
# show all variables
set
# show shell options
set -o
# current shell options (set via set -x, etc)
echo $-
# bash
shopt
# show current shell
echo $0

filename completion ksh (vi mode)

ESC-\

check for interactive shell

case $- in
  *i*)  echo "Interactive"
        ;;
  *)    echo "Not interactive"
        ;;
esac

find ip address for an interface

/sbin/ifconfig interface | grep inet
# e.g.
/sbin/ifconfig bge0 | grep inet

changing my primary group to one of my secondary groups

$ groups
kwaldron wheel
$ grep kwaldron /etc/group
wheel:x:10:root,kwaldron
kwaldron:x:502:
$ newgrp wheel
$ id
uid=502(kwaldron) gid=10(wheel) groups=10(wheel),502(kwaldron) context=user_u:system_r:unconfined_t

gunzip and untar in one line

gzip -dc foo.tar.gz | tar xvf -

gzip and tar in one line

tar cvf - ./* | gzip -c > foo.tar.gz

with GNU tar this can happen in one command

tar xzvf foo.tar.gz
tar cvzf foo.tar.gz files
tar tvzf foo.tar.gz
etc...

uncompress and untar

zcat foo.tar.Z | tar xvf -

find SUID files

/usr/bin/find / -perm -4000 -exec /usr/bin/ls -ld {} \;

find SGID files

/usr/bin/find / -perm -2000 -exec /usr/bin/ls -ld {} \;

find world writable files

/usr/bin/find / -perm -0777 -exec /usr/bin/ls -ld {} \;
# symbolic links will always be 77 so we can ignore them
/usr/bin/find -perm -0777 ! -type l -exec /usr/bin/ls -ld {} \;

remove files older than one week

/usr/bin/find /some/dir -name "*whatever*" -mtime +7 | xargs rm

find device files located where they shouldn’t be

/usr/bin/find / \( -type b -o -type c \) | egrep -v 'proc|/dev'

remove old core files (see Tip 0001 and Tip 0040)

/usr/bin/find / -name core -mtime +7 -exec rm {} \;

ksh/bash – damn emacs editing mode – turn it off!

set +o emacs
set -o vi

remove duplicate occurrences of characters

# echo "ssoommeetthhiinngg" | tr -s [a-z]
something
## remove all occurrences of characters
# echo "ssoommeetthhiinngg" | tr -d [m-z]
eehhiigg

check whois information for a domain

whois -h whois.opensrs.net foo.com

view dynamically linked library dependencies for a binary

ldd /path/to/some/binary

enable a service

vi /etc/inetd.conf
# then
kill -HUP `cat /var/run/syslog.pid`
# or (Solaris)
kill -HUP `pgrep syslogd`

remove a user, and their homedirectory

userdel -r someuser

check routing table

netstat -rn

check interfaces for collisions and errors, tx/rx packets, etc

netstat -ivn
# check for just one interface
netstat -ivn -I eth0

check NTP status

ntpq -p

perform a verbose trace of NTP

ntptrace -dv

ksh arithmetic – very flexible about variables

$ foo=1
$ bar=20
$ echo $(( foo + bar ))
21
$ echo $(( ${foo} + ${bar} ))
21

output to screen and file

my_command | tee -a /some/file

output to two files

my_command | tee -a /some/file > /some/other/file

append stderr and stdout to a file and then perform further actions

some_command 2>&1 | tee -a some_file | some_other_command > some_other_file

redirect stdout and stderr somewhere (in this case, /dev/null)

some_command >/dev/null 2>&1

place command in background

# either
some_command &
# or
some_command
^Z
bg
# can then view jobs
jobs
# and kill by job number
kill %1

line numbering

nl -ba infile > outfile

create 100kb file

dd if=/dev/zero of=/some/file bs=1 count=100

octal dump (show octal and ascii)

od -bc somefile
# use this to check a directory entry
od -bc somedirectory

show the arp cache

arp -a

view tracked alias cache (bash/ksh)

hash

clear tracked alias cache (bash/ksh)

hash -r

show all stty modes

stty -a

create a core dump

stty intr ^\
# then
launch a process in the foreground and hit Ctrl-\

ksh read-only variables

# typeset -r somevar="something"
# somevar="newval"
ksh: somevar: is read only

using at

at now + 5 min
at> ls
at> ^D
# then show list of jobs
atq	# linux atq output less verbose, but with simpler job identifiers
atrm 1135911587.a	# remove an at jon (Solaris)
atrm 1			# ditto (Linux)

remove crontab

crontab -r

list crontab

crontab -l user	   # solaris
crontab -u user -l # linux

exporting X

display_host# xhost +
application_server# DISPLAY=mybox:0.0
application_server# export DISPLAY
application_server# somexprog &

append a line to a file

echo "new line" >> some_file

apache control

apachectl restart
# or
/etc/init.d/httpd restart
# or
/etc/init.d/httpd stop && /etc/init.d/httpd start

take log of session

script /my/log/file

common vi(m) options

# ignore case
:set ic
# line numbers
:set num
:set nonum
# turn off search highlighting (VIM)
:nohl
# syntax highlight on (VIM)
:sy on
# show unprintable characters
:set list

view kernel message buffer

dmesg

check TCPD rules in /etc/hosts.{allow,deny}

grep -v "^#" /etc/hosts.allow /etc/hosts.deny | grep -v "^[ 	]*$"

disable HTTP TRACE in apache

# vi /etc/httpd/conf/httpd.conf
# grep Rewrite /etc/httpd/conf/httpd.conf
RewriteEngine On
RewriteCond %{REQUEST_METHOD} ^TRACE
RewriteRule .* - [F]
# apachectl restart

get postfix to reload configuration

postfix reload

change user foo’s login name to bar

usermod -l bar foo

view Group membership

$ id -Gn -- anyuser
anyuser wheel

tcpdump port 123 (ntp)

tcpdump port 123

disable SELinux protection for syslogd

# setsebool -P syslogd_disable_trans 1        ;; -P to make change permanent
# getsebool -a | grep sys
syslogd_disable_trans --> active
# getsebool syslogd_disable_trans
syslogd_disable_trans --> active

Display SELinux context in ls listings

ls -lZ /some/dir

Show all SELinux booleans

getsebool -a

is SELinux enabled?

selinuxenabled && echo Yes
# or
# getenforce
Enforcing

view usb infomation

lsusb
cat /proc/bus/usb/devices

submit a job for printing

lp -d destination filename

print cups status information

lpstat

xorg.conf

/etc/X11/xorg.conf
xorgconfig

show partition table

/sbin/fdisk -l /dev/cciss/c0d0p1

check mouse is operational

cat /dev/mouse       # then move the mouse

perform a reverse DNS lookup

host xxx.xxx.xxx.xxx dns_server_ip

Linux screenshots

# see http://www.troubleshooters.com/linux/index.htm
import -window root -display servername:0 myfile01.pcx
import -window root -geometry 640:480 -display servername:0 myfile01.pcx
xwd -display servername:0 -root > myfile.dmp
# can view with
xwd | xwud

show inode information for all files in a directory

find . -type f -exec stat {} \;

root .profile under Linux

Most recent Linux distributions use a home directory for root of /root

You can check this with
# awk -vFS=':' '/^root/ {print $6}' /etc/passwd
/root

Again, most Linux distributions have root set up to use bash
# awk -vFS=':' '/^root/ {print $7}' /etc/passwd
/bin/bash

If you look in roots home directory, you'll see .bash_profile
# ls -la $HOME/.bash_profile
-rw-r--r-- 1 root root 234 Jul 6 2001 /root/.bash_profile

show multiple processor usage statistic

mpstat 1 10 	# for ten iterations with 1 second interval

make a file immutable

chattr +i somefile

shutdown your system

init 0
shutdown -h now
# reboot
init 6
shutdown -r now

grub – boot in single user mode

# Hit the a key at the grub menu, then append 'single' to the list of
# kernel arguments

add a log entry via syslog (will be directed as dictated by rules in /etc/syslog.conf)

# logger -p kern.error Test message
# tail -1 /var/log/messages
Dec 28 11:31:09 somehost root: Test message

get account password summary for a user

passwd -S username
# e.g.
# passwd -S kwaldron
Password set, MD5 crypt
# passwd -S ntop
Password locked.

Vixie cron – increments

*/5 * * * * command (would mean every five minutes)
# Vixie cron - ranges
10 0-5 * * * command (10 minutes past each hour from 00:10 'til 05:10)

set global library path

echo "/some/lib/path" >> /etc/ld.so.conf
# then run....
ldconfig
# can also do this on a session/user basis with
export LD_LIBRARY_PATH=${LD_LIBRARY_PATH}:/some/lib/path

chfn – change finger information

# e.g.
/usr/sbin/useradd bob
/usr/bin/chfn -f "Bob Smith" bob	# could also use usermod -c "Bob Smith"
# set the encrypted password...
/usr/sbin/usermon -p 'abcd$01834HFB1a' bob

chsh can be used to change login shell

chsh -l 	# will list shells available in /etc/shells

curses based runlevel management

ntsysv

view CPU information

cat /proc/cpuinfo

view memory information

cat /proc/meminfo

check nic info

cat /proc/net/nicinfo/eth0.info

find out what type file is

file filename

module configuration file

# RHEL3
/etc/modules.conf
# RHEL4
/etc/modprobe.conf

module commands

lsmod
insmod
rmmod
depmod
modprobe

remount a filesystem (e.g. mount read-only FS read-write)

mount -o rw,remount /some/mountpoint

mount an iso image

mount -t iso9660 -o ro,loop /some/foo.iso /mnt

grab last 10 lines of messages file

su - root -c "tail /var/log/messages"

use mii-tool on interface to gather link speed and duplex

mii-tool eth0

use ethtool for further information

ethtool eth0

set interface speed and duplex using ethtool

ethtool -s eth0 speed 100 duplex full autoneg off

display iptables policy

iptables -L

RHEL – display init.d scripts configured with chkconfig

chkconfig --list
# set script to start in runlevels 2, 3, 4 and 5
chkconfig --level 2345 foosvc on
# start the service
service foosvc start

display filehandle usage

lsof

show current runlevel

runlevel

show /proc info for HBA

cat /proc/scsi/qla2300/0

show top processes ignoring inactive and zombie (i.e. running on CPU only)

top -i
# run at highest priority with no delay
top -q -i
# using top in a script - batch mode
top -b -n 1

pstree – kind-of equivalent to ptree

$ pstree -c -p -a -G PID
# e.g. pstree of current shell process
$ pstree -c -p -a -G $$
bash,24195
  +-pstree,24858 -c -p -a -G 24195

show filesystem types in df output

df -kT

define kernel parameters

vi /etc/sysctl.conf
man sysctl
e.g.
# /sbin/sysctl -a | grep shmmax
kernel.shmmax = 33554432

set hardware clock to system clock date and time

hwclock --systohc

display memory usage (in megabytes)

free -m

ssh as different user than currently logged in user

ssh -l username hostname
# or
ssh username@hostname

basic scp syntax

scp /src/files user@host:/dest/path

List users accessing mounted filesystem

fuser -u /mnt

Kill all processes accessing this filesystem

fuser -km /mnt

A big heap of (mostly) Solaris specific one-liners 

copy ACL from one file to another

getfacl file_one | setfacl -f - file_two

Print all lp status information

lpstat -t

view the files that make up a Solaris package

/usr/sbin/pkgchk -l SUNWcsr | grep Pathname | sed 's/Pathname: \(.*\)/\1/'

check which package a file belongs to

/usr/sbin/pkgchk -lp somefile

snoop an interface for icmp

snoop -d eri0 | grep -i icmp

view a NIS+ map

niscat passwd.org_dir
# for NIS
ypcat passwd

backup to tape

tar cvf /dev/rmt/0n /some/crap
mt rew
tar tvf /dev/rmt/0n
mt rew
tar xvf /dev/rmt/0n single_file

Solaris 10 – list current zones

/usr/sbin/zoneadm list -cv

Solaris 10 – list current service state

svcs -a

Show extended information about a Solaris 10 service

svcs -xv svc:/network/nfs/client

Display all available information about a service

svcs -l svc:/network/nfs/status:default

List the services on which a Solaris 10 service depends

svcs -d svc:/network/nfs/client

List the services which depend on this Solaris 10 service

svcs -D svc:/network/nfs/client

View Solaris 10 inet services

inetadm

Convert new inetd.conf entries to new SMF format

inetconf

list users belonging to a group

listusers -g groupname

share a filesystem

share /some/fs
# then on another system
mount -F nfs some_ip:/some/fs /some/mnt
# when we're done
umount /some/mnt
# then back on original system
unshare /some/fs

find filesystem type

fstyp /dev/dsk/c0t0d0s0

set auto-boot to false

ok setenv auto-boot? false
# or
eeprom 'auto-boot?=false'

eject cdrom

umount /cdrom/cdrom0
eject cdrom
# or if vold isn't running
umount /mnt
eject /dev/dsk/c0t6d0s0		(get this info from iostat -En)

Solaris DHCP configuration table management utility

dhtadm

DHCP Graphical interface

/usr/sadm/admin/bin/dhcpmgr

solaris print manager

/usr/sadm/admin/bin/printmgr

solaris graphical configuration

man fbconfig
man m64config
man kdmconfig		# ia86

administer system controller

/usr/platform/`uname -i`/sbin/scadm

create windex with nohup -p

# catman &
[1] 2345
# jobs
[1] + Running    catman &
# nohup -p 2345
# exit

boot Solaris 10 in verbose mode

ok boot -m verbose

view disabled services on Solaris 10

svcs -a | grep disabled

disable / enable telnet

# disable telnet
inetadm -d telnet
# re-enable telnet
inetadm -e telnet
# or
svcadm disable telnet
svcadm -v enable -r telnet
(-v verbose, -r recursively enable dependencies)
# example
# svcadm -v disable telnet
svc:/network/telnet:default disabled.
# svcadm -v enable -r svc:/network/ftp:default

shutdown your system

init 5
shutdown -y -g0 -i5
# reboot
init 6
shutdown -y -g0 -i6

dynamically adding solaris interface

ifconfig hme0 plumb
ifconfig hme0 192.168.0.2 netmask 255.255.255.0 broadcast + up
route add default 192.168.0.1
# to make this permanent
echo "hostname" > /etc/hostname.hme0
echo "192.168.0.2" >> /etc/inet/hosts # on Solaris 10 - ensure you modify /etc/inet/ipnodes too
echo "192.168.0.0 255.255.255.0" >> /etc/inet/netmasks
echo "192.168.0.1" > /etc/defaultrouter
init 6

display tape drive status

mt -f /dev/rmt/0 status

find installed physical memory

/usr/sbin/prtconf | grep Mem

standard single user mode boot

ok boot -s
# or
init s
# or
reboot -- -s

power off

init 5
# or
init 0
power-off
# or
shutdown -y -i5 -g0

single user mode cdrom boot

stop-A
# or
init 0
# then
ok boot cdrom -s
# on intel
b -s (insert CD first, it will attempt to boot then give you a prompt)

show configuration information (controllers)

$ /usr/sbin/cfgadm
Ap_Id                          Type         Receptacle   Occupant     Condition
c0                             scsi-bus     connected    configured   unknown
c1                             scsi-bus     connected    configured   unknown
c2                             scsi-bus     connected    unconfigured unknown
usb0/1                         unknown      empty        unconfigured ok
usb0/2                         unknown      empty        unconfigured ok

burning cd’s under Solaris (see Solaris 10 Devices and Filesystems guide on docs.sun.com )

man cdrw
man mkisofs

truss a process that’s already running (see strace on Linux)

truss -f -wall -rall -vall -o /some/outfile.out -p PID &

show kernel parameters for an interface ( <= Solaris 9 only )

netstat -k interface
# e.g.
netstat -k hme0

ping using alternative interface

ping -i bge1 somehost

ping 5 x 64 byte packets

ping -s somehost 64 5

Just added a new device to the system?

devfsadm   # pre Solaris 8 this was tapes, disks, drvconfig
# or
touch /reconfigure
init 6
# or
reboot -- -rs
# or
init 0
ok boot -rs

mount an iso

# lofiadm -a /path/to/foo.iso
/dev/lofi/1
# mount -F hsfs /dev/lofi/1 /mnt
# umount /mnt
# lofiadm -d /dev/lofi/1

show uname information in SCO format

uname -X

grab system diagnostics information and variables

/usr/platform/`uname -i`/sbin/prtdiag -v
/usr/platform/`uname -i`/sbin/eeprom
prtconf -D
isainfo -kv			# show kernel module version
pagesize 			# show pagesize
psrinfo -v			# verbose processor information

Show loaded kernel modules

modinfo
# other module commands
modload
modunload

Finding network parameters of bge interfaces

ndd -get /dev/bge0 link_status
ndd -get /dev/bge0 link_speed
ndd -get /dev/bge0 link_duplex

check metadbs

metadb

check metastat

metastat
# view brief config snapshot
metastat -p

view swap information

swap -l
swap -s
sar -r
# view info n 5 samples at 5 second intervals
sar -r 5 5

make 100M swap file to temporarily fix swap issues

mkfile 100m /export/swapfile
swap -a /foo/swapfile
swap -l
swap -s
# problem fixed - dodgy application patched or removed
swap -d /foo/swapfile
rm /foo/swapfile
# if it needs to be made persistent, then add it to /etc/vfstab

wide ps listing

/usr/ucb/ps auwwwx

get CLOSE_WAIT interval

/usr/sbin/ndd -get /dev/tcp tcp_close_wait_interval

see if IP Forwarding is enabled

/usr/sbin/ndd -get /dev/tcp ip_forwarding

view information on signals

man -s3HEAD signal

fsck (on RAW device)

fsck /dev/rdsk/c1t1d0s0

view errors on devices (an easy way to find out device name of CD/DVD drives)

iostat -En

display inode to filename mapping

ff /dev/dsk/c1t1d0s0

display which processes have a file open (also works on some Linux distros)

fuser filename

display which files a process has open

pfiles PID
pfiles `pgrep process_name`

Solaris 9 and above – reap zombie process

preap PID

show who is doing what

/usr/sbin/whodo

iostat

iostat interval iterations
# e.g.
iostat 1 10
# same can be done with prstat and vmstat

ptree – show parent/child process relationship

ptree PID
# e.g. for current shell
ptree `pgrep $( echo $0 | tr -d '-' )`
# or
ptree `pgrep $( echo $0 | sed 's/-//' )`

view current eeprom settings

/usr/platform/`uname -i`/sbin/eeprom

set MTU value for an interface

ifconfig interface mtu n
# e.g.
ifconfig hme0 mtu 1500
# place in hostname.interface file for persistence

show patch revisions

showrev -p
patchadd -p

show brief listing of installed packages

pkginfo

show long listing of installed packages

pkginfo -l

see package info on a package that’s not yet installed

pkginfo -l -d /path/to/package.pkg

get package params (may aswell just browse /var/sadm/pkg/PKGname/pkginfo)

pkgparam SUNWcsr DESC

open Solaris product registry

prodreg

send a nohup to an already running command (Solaris 10)

nohup -p PID

define kernel parameters (requires a reboot after changes)

vi /etc/system

view current system parameters

sysdef | grep whatever
# e.g.
# sysdef | grep shar
1572864000   max shared memory segment size
100           shared memory identifiers (SHMMNI)
60            maximum time sharing user priority (TSMAXUPRI)
# grep shmmax /etc/system
*set shmsys:shminfo_shmmax=1258291200
set shmsys:shminfo_shmmax=1572864000

find pid if you know process name

pgrep some_process_name
# or the obvious
ps -ef | grep whatever
# we can then ptree this
ptree PID
# or all in one
ptree `pgrep process_name`

Another bundle of miscellaneous one-liners (Misc OS's....) 

show process listing for single username

ps -fu username

print all lines between two search terms (inclusive)

sed -n '/acd/,/anz/ p' file.dat

Solaris – show multiple processor statistics

mpstat 1 10

remove digits from a string

echo "abcd01234" | tr -d [0-9]

view MX record(s) for a domain

dig MX foo.com

GNU tar + bzip + exclude

tar cvpjf backup.tar.bz2 / --exclude /proc /dev /mnt /sys /media

create iso image

dd if=/dev/cdrom of=/some/iso.iso bs=512

# /etc/issue displayed before login
# /etc/motd display after login

ls by size in descending order

ls -la | sort -k5,5rn

show RPC info on a remote host (probe portmapper)

# rpcinfo -p remote.ip

output man page to file

man something | col -b > man.out

Add line numbers to a file

nl -ba < infile > outfile

Run syslog in Debug mode

/usr/sbin/syslogd -d

manual page detailing hosts.allow hosts.deny

man 5 hosts_access

display ps forest

ps -axf

recursively change permissions on directories only

find . -type d -exec chmod 755 {} \; -print 2>/dev/null

list specific users process info

lsof -u username

iconv convert between codesets

iconv -f UTF-8 -t iso85591 somefile

grab sar stats for specific time range

sar -A -s 19:40 -e 20:50 -f /var/adm/sa/sa21

Solaris 10 – checking online services

$ svcs -xv svc:/network/rpc-100235_1/rpc_ticotsord:default
svc:/network/rpc-100235_1/rpc_ticotsord:default (100235)
 State: online since Mon Feb 20 12:59:06 2006
Impact: None.
$ inetadm | grep enabled
enabled   online         svc:/network/rpc/meta:default
enabled   online         svc:/network/rpc-100235_1/rpc_ticotsord:default
$ svcs -a | grep online | wc -l
      46

Solaris: pgrep against full argument string

# sleep 200 &
5868
# pgrep sleep
5868
# pgrep 200
# pgrep -f 200
5868
#

recursive copy preserving permissions

cp -Rp /some/src /dest

using xargs to copy files

find /srcdir/ . -name '*.txt.gz' -mtime -2 | xargs -I {} cp {} /trgtdir/

ntp commands

# query
$ /usr/sbin/ntpdate -q somehost
# update
# /usr/sbin/ntpdate -u somehost
# show peers
$ /usr/sbin/ntpq -p
# show associations
$ /usr/sbin/ntpq -c "assoc"
# show rl vars for particular association
$ /usr/sbin/ntpq -c "rl assID"
# trace NTP back to primary source
# /usr/sbin/ntptrace -dv someserver

Linux – view failure counts for all users

# faillog -a

Linux – show all pam_tally stats (failed login tally) – see Tip 0041

# pam_tally

Solaris – view PROM variables

eeprom | more

Solaris – echo ignoring backslash-escape sequences

-bash-3.00$ /usr/ucb/echo "c:\tuser\abc"
c:\tuser\abc
-bash-3.00$

Solaris 10: Is syslog enabled?

-bash-3.00$ svcs -a | grep system-log

Linux force NIC speed

mii-tool -F 100baseTx-FD eth0
# note - better to use ethtool as mii-tool only supports up to 100/FD
ethtool -s eth0 speed 100 duplex full autoneg off
# also, to use 1000/FD you must leave autoneg enabled

crypt

crypt < encrypted.file > unencrypted.file
# crypt will prompt you for your key.

find the square root of a number

$ echo "sqrt(4)" | bc
2

Solaris 10: to enable tcp tracing on telnet

inetadm -m svc:/network/telnet:default tcp_trace=TRUE

Solaris 10: inetadm – list properties for selected instance

-bash-3.00$ /usr/sbin/inetadm -l svc:/network/login:rlogin

Solaris 10 – show faults

# fmadm faulty
# fmdump -v

Linux – Change the label on an ext2 filesystem

e2label labelname

list available signals

kill -l

Linux – check Serial port config

# setserial -g -a /dev/ttyS0

set modification date on a file

touch -t DATE file # where DATE is in format [[CC]YY]MMDDhhmm[.SS]

octal dump of file

od -c file
od -bc file

set system date on RHEL

date MMDDhhmm
hwclock --systohc

send syslogd a HUP

killall -1 syslogd	;; linux
pkill -HUP syslogd	;; solaris

fsck ext3 filesystem automatically answering Y to questions

fsck.ext3 -y /dev/hdb1

Linux – view PCI and USB bus attached devices

lsusb
lspci

Solaris 10 – disable a service

# view dependencies
svcs -a | grep gss
svcs -d svc:/network/rpc/gss:default		;; gss depends on
svcs -D svc:/network/rpc/gss:default		;; depend on gss
svcadm -v disable svc:/network/rpc/gss:default
svcs -xv svc:/network/rpc/gss:default
svsa -a | grep gss

Linux – grep a gzipped file

zgrep "searchterm" foo.gz

show plain text strings within a binary file

strings /path/to/binary

stop and start named

rndc stop
/etc/init.d/named start

strace

strace -f -o /var/tmp/trace.out -p 554 &

diff

diff file1 file2

using expr with multiplication

$ expr $a \* $b
20

Switch between postfix and sendmail on RHEL

/usr/sbin/system-switch-mail
# rpm -qa | egrep -i 'sendmail|postfix|switch-mail'
system-switch-mail-0.5.25-3
sendmail-8.13.1-2
postfix-2.1.5-4.2.RHEL4

Linux – view PCI devices

lspci

Linux – View USB devices

lsusb

Linux – Switch to another virtual console

Ctrl-Alt-F1

Solaris – display nickname to device translation table for eject

eject -n

Display all who information

who -a

join all lines in a file using paste

paste -d ' ' -s file1 > file2

Remove archived files that are over one day old

rm -f `find /archive/ -mmin +1440 -print`

awk substrings

echo "1234567890abcdefghij" | awk '{print substr($0,3,1) " " substr($0,11,8)}'

Some misc. Solaris one-liners 

print PICL tree gathering temperature sensor info

/usr/sbin/prtpicl -c temperature-sensor -v

Clean up “dangling” /dev links

devfsadm -C

Installation log file

/var/sadm/system/log/install_log

detailed package info

pkginfo -l installed_package_name
pkginfo -l -d some_unistalled_pkg.pkg

egrep for two things

egrep 'THIS|THAT' somefile

set erase char

stty erase ^H

run syslogd in debug mode to check configuration file

/etc/init.d/syslog stop
/usr/sbin/syslogd -d
^C
/etc/init.d/syslog start

pkgchk

-bash-3.00$ /usr/sbin/pkgchk -lp /usr/bin/man
NOTE: Couldn't lock the package database.
Pathname: /usr/bin/man
Type: linked file
Source of link: ../../usr/bin/apropos
Referenced by the following packages:
        SUNWdoc
Current status: installed

svcs

# svcs -xv svc:/network/rpc/meta:default
svc:/network/rpc/meta:default (SVM remote metaset services)
 State: disabled since Mon Jan 16 12:29:14 2006
Reason: Disabled by an administrator.
   See: http://sun.com/msg/SMF-8000-05
   See: man -M /usr/share/man -s 1M rpc.metad
Impact: This service is not running.
svcs -Dv meta					;; that depend on this
STATE          NSTATE        STIME    CTID   FMRI
disabled       -             12:29:09      - svc:/system/mdmonitor:default
svcs -dv meta					;; this depends on
STATE          NSTATE        STIME    CTID   FMRI
online         -             12:29:12     30 svc:/network/rpc/bind:default

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s