Showing posts with label Unix. Show all posts
Showing posts with label Unix. Show all posts

Wednesday, January 16, 2013

Best AWK Commands

AWK is a data driven programming language designed for processing text-based data, either in files or data streams. It is an example of a programming language that extensively uses the string datatype, associative arrays (that is, arrays indexed by key strings), and regular expressions. WIKI



1)  List of commands you use most often

history | awk ‘{a[$2]++}END{for(i in a){print a[i] ” ” i}}’ | sort -rn | head

2) Display a block of text with AWK

awk ‘/start_pattern/,/stop_pattern/’ file.txt
I find this terribly useful for grepping through a file, looking for just a block of text. There’s “grep -A # pattern file.txt” to see a specific number of lines following your pattern, but what if you want to see the whole block? Say, the output of “dmidecode” (as root):
dmidecode | awk '/Battery/,/^$/'Will show me everything following the battery block up to the next block of text. Again, I find this extremely useful when I want to see whole blocks of text based on a pattern, and I don’t care to see the rest of the data in output. This could be used against the ‘/etc/securetty/user’ file on Unix to find the block of a specific user. It could be used against VirtualHosts or Directories on Apache to find specific definitions. The scenarios go on for any text formatted in a block fashion. Very handy.

3) Graph # of connections for each hosts.

netstat -an | grep ESTABLISHED | awk ‘{print $5}’ | awk -F: ‘{print $1}’ | sort | uniq -c | awk ‘{ printf(“%s\t%s\t”,$2,$1) ; for (i = 0; i < $1; i++) {printf(“*”)}; print “” }’
Written for linux, the real example is how to produce ascii text graphs based on a numeric value (anything where uniq -c is useful is a good candidate).

4) Check your unread Gmail from the command line

curl -u username:password –silent “https://mail.google.com/mail/feed/atom” | tr -d ‘\n’ | awk -F ” ‘{for (i=2; i<=NF; i++) {print $i}}’ | sed -n “s/\(.*\)<\/title.*name>\(.*\)<\/name>.*/\2 – \1/p”
Checks the Gmail ATOM feed for your account, parses it and outputs a list of unread messages.
For some reason sed gets stuck on OS X, so here’s a Perl version for the Mac:
curl -u username:password --silent "https://mail.google.com/mail/feed/atom" | tr -d '\n' | awk -F '' '{for (i=2; i<=NF; i++) {print $i}}' | perl -pe 's/^(.*)<\/title>.*<name>(.*)<\/name>.*$/$2 - $1/'</code></b>If you want to see the name of the last person, who added a message to the conversation, change the greediness of the operators like this:</p> </div> <div> <b><code>curl -u username:password --silent "https://mail.google.com/mail/feed/atom" | tr -d '\n' | awk -F '<entry>' '{for (i=2; i<=NF; i++) {print $i}}' | perl -pe 's/^<title>(.*)<\/title>.*?<name>(.*?)<\/name>.*$/$2 - $1/'</code></b></div> <h3> 5) Remove duplicate entries in a file without sorting.</h3> <p> <b>awk ‘!x[$0]++’ <file></b></p> <p> Using awk, find duplicates in a file without sorting, which reorders the contents. awk will not reorder them, and still find and remove duplicates which you can then redirect into another file.</p> <h3> 6) find geographical location of an ip address</h3> <p> <b>lynx -dump http://www.ip-adress.com/ip_tracer/?QRY=$1|grep address|egrep ‘city|state|country’|awk ‘{print $3,$4,$5,$6,$7,$8}’|sed ‘s\ip address flag \\’|sed ‘s\My\\’</b></p> <div> <p> I save this to bin/iptrace and run “iptrace ipaddress” to get the Country, City and State of an ip address using the <a rel="nofollow" href="http://ipadress.com/">http://ipadress.com</a> service.</p> <p> I add the following to my script to get a tinyurl of the map as well:</p> <p> URL=`lynx -dump <a rel="nofollow" href="http://www.ip-adress.com/ip_tracer/?QRY=$1%7Cgrep">http://www.ip-adress.com/ip_tracer/?QRY=$1|grep</a> details|awk ‘{print $2}’`</p> <p> lynx -dump <a rel="nofollow" href="http://tinyurl.com/create.php?url=$URL%7Cgrep">http://tinyurl.com/create.php?url=$URL|grep</a> tinyurl|grep “19. http”|awk ‘{print $2}’</p> <h3> 7) Block known dirty hosts from reaching your machine</h3> <p> <b>wget -qO – http://infiltrated.net/blacklisted|awk ‘!/#|[a-z]/&&/./{print “iptables -A INPUT -s “$1″ -j DROP”}’</b></p> <p> Blacklisted is a compiled list of all known dirty hosts (botnets, spammers, bruteforcers, etc.) which is updated on an hourly basis. This command will get the list and create the rules for you, if you want them automatically blocked, append |sh to the end of the command line. It’s a more practical solution to block all and allow in specifics however, there are many who don’t or can’t do this which is where this script will come in handy. For those using ipfw, a quick fix would be {print “add deny ip from “$1″ to any}. Posted in the sample output are the top two entries. Be advised the blacklisted file itself filters out RFC1918 addresses (10.x.x.x, 172.16-31.x.x, 192.168.x.x) however, it is advisable you check/parse the list before you implement the rules</p> <h3> 8) Display a list of committers sorted by the frequency of commits</h3> <p> <b>svn log -q|grep “|”|awk “{print \$3}”|sort|uniq -c|sort -nr</b></p> <p> Use this command to find out a list of committers sorted by the frequency of commits.</p> <h3> 9) List the number and type of active network connections</h3> <p> <b>netstat -ant | awk ‘{print $NF}’ | grep -v ‘[a-z]‘ | sort | uniq -c</b></p> <h3> <b>10) </b>View facebook friend list [hidden or not hidden]</h3> <p> <b>lynx -useragent=Opera -dump ‘http://www.facebook.com/ajax/typeahead_friends.php?u=4&__a=1′ |gawk -F’\”t\”:\”‘ -v RS=’\”,’ ‘RT{print $NF}’ |grep -v ‘\”n\”:\”‘ |cut -d, -f2</b></p> <div> <p> There’s no need to be logged in facebook. I could do more JSON filtering but you get the idea…</p> <p> Replace u=4 (Mark Zuckerberg, Facebook creator) with desired uid.</p> <p> Hidden or not hidden… Scary, don’t you?</p> <h3> 11) List recorded formular fields of Firefox</h3> <p> <b>cd ~/.mozilla/firefox/ && sqlite3 `cat profiles.ini | grep Path | awk -F= ‘{print $2}’`/formhistory.sqlite “select * from moz_formhistory” && cd – > /dev/null</b></p> <p> When you fill a formular with Firefox, you see things you entered in previous formulars with same field names. This command list everything Firefox has registered. Using a “delete from”, you can remove anoying Google queries, for example ;-)</p> <h3> 12) Brute force discover</h3> <p> <b>sudo zcat /var/log/auth.log.*.gz | awk ‘/Failed password/&&!/for invalid user/{a[$9]++}/Failed password for invalid user/{a["*" $11]++}END{for (i in a) printf “%6s\t%s\n”, a[i], i|”sort -n”}’</b></p> <p> Show the number of failed tries of login per account. If the user does not exist it is marked with *.</p> <h3> 13) Show biggest files/directories, biggest first with ‘k,m,g’ eyecandy</h3> <p> <b>du –max-depth=1 | sort -r -n | awk ‘{split(“k m g”,v); s=1; while($1>1024){$1/=1024; s++} print int($1)” “v[s]“\t”$2}’</b></p> <p> I use this on debian testing, works like the other sorted du variants, but i like small numbers and suffixes :)</p> <h3> 14) Analyse an Apache access log for the most common IP addresses</h3> <div title="Click to select this command"> <div> <b>tail -10000 access_log | awk ‘{print $1}’ | sort | uniq -c | sort -n | tail</b></div> <div> <b><br> </b></div> <div> This uses awk to grab the IP address from each request and then sorts and summarises the top 10</div> <h3> 15) copy working directory and compress it on-the-fly while showing progress</h3> <p> <b>tar -cf – . | pv -s $(du -sb . | awk ‘{print $1}’) | gzip > out.tgz</b></p> <div> <p> What happens here is we tell tar to create “-c” an archive of all files in current dir “.” (recursively) and output the data to stdout “-f -”. Next we specify the size “-s” to pv of all files in current dir. The “du -sb . | awk ?{print $1}?” returns number of bytes in current dir, and it gets fed as “-s” parameter to pv. Next we gzip the whole content and output the result to out.tgz file. This way “pv” knows how much data is still left to be processed and shows us that it will take yet another 4 mins 49 secs to finish.</p> <p> Credit: Peteris Krumins <a rel="nofollow" href="http://www.catonmat.net/blog/unix-utilities-pipe-viewer/">http://www.catonmat.net/blog/unix-utilities-pipe-viewer/</a></p> <h3> 16) List of commands you use most often</h3> <p> <b>history | awk ‘{print $2}’ | sort | uniq -c | sort -rn | head</b></p> <h3> <b>17) </b>Identify long lines in a file</h3> <p> <b>awk ‘length>72′ file</b></p> <p> This command displays a list of lines that are longer than 72 characters. I use this command to identify those lines in my scripts and cut them short the way I like it.</p> <h3> 18) Makes you look busy</h3> <p> <b>alias busy=’my_file=$(find /usr/include -type f | sort -R | head -n 1); my_len=$(wc -l $my_file | awk “{print $1}”); let “r = $RANDOM % $my_len” 2>/dev/null; vim +$r $my_file’</b></p> <p> This makes an alias for a command named ‘busy’. The ‘busy’ command opens a random file in /usr/include to a random line with vim. Drop this in your .bash_aliases and make sure that file is initialized in your .bashrc.</p> <h3> 19) Show me a histogram of the busiest minutes in a log file:</h3> <p> <b>cat /var/log/secure.log | awk ‘{print substr($0,0,12)}’ | uniq -c | sort -nr | awk ‘{printf(“\n%s “,$0) ; for (i = 0; i<$1 ; i++) {printf(“*”)};}’</b></p> <h3> <b>20) </b>Analyze awk fields</h3> <p> <b>awk ‘{print NR”: “$0; for(i=1;i<=NF;++i)print “\t”i”: “$i}’</b></p> <p> Breaks down and numbers each line and it’s fields. This is really useful when you are going to parse something with awk but aren’t sure exactly where to start.</p> <h3> 21) Browse system RAM in a human readable form</h3> <p> <b>sudo cat /proc/kcore | strings | awk ‘length > 20′ | less</b></p> <p> This command lets you see and scroll through all of the strings that are stored in the RAM at any given time. Press space bar to scroll through to see more pages (or use the arrow keys etc).</p> <p> Sometimes if you don’t save that file that you were working on or want to get back something you closed it can be found floating around in here!</p> <p> The awk command only shows lines that are longer than 20 characters (to avoid seeing lots of junk that probably isn’t “human readable”).</p> <p> If you want to dump the whole thing to a file replace the final ‘| less’ with ‘> memorydump’. This is great for searching through many times (and with the added bonus that it doesn’t overwrite any memory…).</p> <p> Here’s a neat example to show up conversations that were had in pidgin (will probably work after it has been closed)…</p> <p> <b><code>sudo cat /proc/kcore | strings | grep '([0-9]\{2\}:[0-9]\{2\}:[0-9]\{2\})'</code></b>(depending on sudo settings it might be best to run</p> <p> <b><code>sudo su</code></b>first to get to a # prompt)</p> <h3> 22) Monitor open connections for httpd including listen, count and sort it per IP</h3> <p> <b>watch “netstat -plan|grep :80|awk {‘print \$5′} | cut -d: -f 1 | sort | uniq -c | sort -nk 1″</b></p> <div> <p> It’s not my code, but I found it useful to know how many open connections per request I have on a machine to debug connections without opening another http connection for it.</p> <p> You can also decide to sort things out differently then the way it appears in here.</p> <h3> 23) Purge configuration files of removed packages on debian based systems</h3> <p> <b>sudo aptitude purge `dpkg –get-selections | grep deinstall | awk ‘{print $1}’`</b></p> <div> <p> Purge all configuration files of removed packages</p> <h3> 24) Quick glance at who’s been using your system recently</h3> <p> <b>last  | grep -v “^$” | awk ‘{ print $1 }’ | sort -nr | uniq -c</b></p> <p> This command takes the output of the ‘last’ command, removes empty lines, gets just the first field ($USERNAME), sort the $USERNAMES in reverse order and then gives a summary count of unique matches.</p> <h3> 25) Number of open connections per ip.</h3> <p> <b>netstat -ntu | awk ‘{print $5}’ | cut -d: -f1 | sort | uniq -c | sort -n</b></p> <div> <p> Here is a command line to run on your server if you think your server is under attack. It prints our a list of open connections to your server and sorts them by amount.</p> <p> BSD Version:</p> </div> <div> <b><code>netstat -na |awk '{print $5}' |cut -d "." -f1,2,3,4 |sort |uniq -c |sort -nr</code></b></div> <div> And there you have it killer awk usages. Now I know you might be thinking these are NOT awk commands. Maybe not, but awk was used to filter out data.</div> <div> Did I make a mistake?,</div> <div> did I leave something cool behind?</div> <div> Please feel free to comment.</div> </div> </div> </div> </div> </div> </div> </div>

Tuesday, October 9, 2012

Unix script to monitor TCP port statistics

One simple and very useful indicator of process health and load is its TCP activity. The following script takes a set of ports and summarizes how many TCP sockets are established, opening, and closing for each port. It has been tested on Linux and AIX. Example output:




$ portstats.sh 80 443

PORT ESTABLISHED OPENING CLOSING

80 3 0 0

443 10 0 2

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

Total 13 0 2 portstats.sh:



#!/bin/sh



usage() {

echo "usage: portstats.sh PORT_1 PORT_2 ... PORT_N"

echo " Summarize network connection statistics coming into a set of ports."

echo ""

echo " OPENING represents SYN_SENT and SYN_RECV states."

echo " CLOSING represents FIN_WAIT1, FIN_WAIT2, TIME_WAIT, CLOSED, CLOSE_WAIT,"

echo " LAST_ACK, CLOSING, and UNKNOWN states."

echo ""

exit;

}



NUM_PORTS=0

OS=`uname`



for c in $*

do

case $c in

-help)

usage;

;;

--help)

usage;

;;

-usage)

usage;

;;

--usage)

usage;

;;

-h)

usage;

;;

-?)

usage;

;;

*)

PORTS[$NUM_PORTS]=$c

NUM_PORTS=$((NUM_PORTS + 1));

;;

esac

done



if [ "$NUM_PORTS" -gt "0" ]; then

date

NETSTAT=`netstat -an
grep tcp`

i=0

for PORT in ${PORTS[@]}

do

if [ "$OS" = "AIX" ]; then

PORT="\.$PORT\$"

else

PORT=":$PORT\$"

fi

ESTABLISHED[$i]=`echo "$NETSTAT"
grep ESTABLISHED
awk '{print $4}'
grep "$PORT"
wc -l`

OPENING[$i]=`echo "$NETSTAT"
grep SYN_
awk '{print $4}'
grep "$PORT"
wc -l`

WAITFORCLOSE[$i]=`echo "$NETSTAT"
grep WAIT
awk '{print $4}'
grep "$PORT"
wc -l`

WAITFORCLOSE[$i]=$((${WAITFORCLOSE[$i]} + `echo "$NETSTAT"
grep CLOSED
awk '{print $4}'
grep "$PORT"
wc -l`));

WAITFORCLOSE[$i]=$((${WAITFORCLOSE[$i]} + `echo "$NETSTAT"
grep CLOSING
awk '{print $4}'
grep "$PORT"
wc -l`));

WAITFORCLOSE[$i]=$((${WAITFORCLOSE[$i]} + `echo "$NETSTAT"
grep LAST_ACK
awk '{print $4}'
grep "$PORT"
wc -l`));

WAITFORCLOSE[$i]=$((${WAITFORCLOSE[$i]} + `echo "$NETSTAT"
grep UNKNOWN
awk '{print $4}'
grep "$PORT"
wc -l`));



TOTESTABLISHED=0

TOTOPENING=0

TOTCLOSING=0

i=$((i + 1));

done



printf '%-6s %-12s %-8s %-8s\n' PORT ESTABLISHED OPENING CLOSING

i=0

for PORT in ${PORTS[@]}

do

printf '%-6s %-12s %-8s %-8s\n' $PORT ${ESTABLISHED[$i]} ${OPENING[$i]} ${WAITFORCLOSE[$i]}

TOTESTABLISHED=$(($TOTESTABLISHED + ${ESTABLISHED[$i]}));

TOTOPENING=$(($TOTOPENING + ${OPENING[$i]}));

TOTCLOSING=$(($TOTCLOSING + ${WAITFORCLOSE[$i]}));

i=$((i + 1));

done



printf '%36s\n'
tr " " "="

printf '%-6s %-12s %-8s %-8s\n' Total $TOTESTABLISHED $TOTOPENING $TOTCLOSING



else

usage;

fi

To automatically read the ports for IHS, use:



$ portstats.sh `grep Listen /opt/IBM/HTTPServer/conf/httpd.conf
grep -v "\#"
awk '{print $2}'
tr '\n' ' '`It should also be possible to extract WAS ports from .../WebSphere/AppServer/profiles/*/config/cells/*/nodes/*/serverindex.xml.

Thursday, April 8, 2010

Memory-CPU in unix

Task I - Identifying a memory DOS and responding
In this task, you will start a memory denial of service against yourself and then add
swap on the fly to attempt to buy more time. If you were the client from the module 4
exercise, you will have to create the memory DOS script (step 16) from the module 4 lab.
1) Open 3 seperate terminal windows. In the first terminal, start a vmstat with an interval of one second.
[1] # vmstat 1
procs memory page disk faults cpu
r b w swap free re mf pi po fr de sr dd f0 s5 s1 in sy cs us sy id
0 0 25 811888 326896 3 11 8 5 5 0 5 2 0 0 0 311 564 89 2 1 97
0 0 25 781816 264256 13 8 680 0 0 0 0 119 0 0 0 634 6097 360 1 21 78
0 1 25 781816 263288 20 0 896 0 0 0 0 135 0 0 0 742 3591 421 2 12 86

2) In the second terminal, invoke the "hog" script in the /export/home/guest directory.
[2] # cd /export/home/guest
[2] # ./hog
3) In the third terminal window, create an 128mb swap file and add it on the fly.
[3] # mkfile 128m /export/swapfile
[3] # swap -a /export/swapfile
4) Observer the vmstat output in terminal 1. Did the "swap" column grow?
procs memory page disk faults cpu
r b w swap free re mf pi po fr de sr dd f0 s5 s1 in sy cs us sy id
1 1 25 1560 8584 612 6607 624 8 8 200 0 69 0 0 0 514 7979 1086 27 72 1
1 1 25 1280 7680 534 2471 4536 3656 3744 40 439 145 0 0 0 841 3537 671 14 40
0 1 25 127608 8232 415 513 4640 5648 5688 0 202 100 0 0 0 546 615 245 1 11 88
0 3 25 123104 8464 449 558 5008 5080 5080 0 0 113 0 0 0 557 974 322 2 13 85
5) Observe the hog output in terminal 2. It appears that the script continued to run
even though /tmp was full. As soon as the swap space was added, the script started writing
files into the /tmp space.
cat: write error: No space left on device <---script still running even though /tmp is full
+ let x=x+1
+ [ 1805 -eq 100000 ]
+ cat /var/sadm/install/contents
+ 1>> /tmp/file.1805
cat: write error: No space left on device <---script still running even though /tmp is full
+ let x=x+1
+ [ 1806 -eq 100000 ]
+ cat /var/sadm/install/contents <---script appears to resume writing to /tmp
+ 1>> /tmp/file.1806
+ let x=x+1
6) Stop the script by issuing a ^C in terminal 2. Clean up the /tmp directory.
[3] # cd /tmp
[3] # rm -r /tmp/file*
7) Stop the vmstat by issuing a ^C in terminal 1.
Task II - Limiting the size of /tmp in the /etc/vfstab
In this exercise, you will limit the size of the /tmp filesystem and then run a memory DOS
against yourself to see if the filesystem limit worked.
1) Observer the size of the /tmp file system with the df command.
# df -k /tmp
Filesystem kbytes used avail capacity Mounted on
swap 900360 16 900344 1% /tmp
2) Edit the /etc/vfstab and configure /tmp to have a maximum size of 128m
# vi /etc/vfstab
swap - /tmp tmpfs - yes size=128m
3) Since /tmp cannot unmount. You will have to reboot the workstation
# init 6
4) After the workstation has rebooted, check the size of /tmp again.
Notice that it is much smaller than the previous size.
# df -k /tmp
Filesystem kbytes used avail capacity Mounted on
swap 131072 344 130728 1% /tmp
5) Open 3 terminal windows. In the first window, start a vmstat at 1 second
intervals.
[1] # vmstat 1
procs memory page disk faults cpu
r b w swap free re mf pi po fr de sr dd f0 s5 s1 in sy cs us sy id
0 0 0 856456 426696 29 122 134 0 0 0 0 19 0 0 0 363 662 157 3 8 89
0 0 0 878352 414024 0 8 0 0 0 0 0 0 0 0 0 356 171 91 0 0 100
6) In a second terminal window, start the hog script.
[2] # cd /export/home/guest
[2] # ./hog
7) Notice in terminal 2 that the hog script will error out more quickly with a "No space left on
device" while in terminal 1, the vmstat reports plenty of virtual memory in the "swap"
column. Since the /tmp file system has been limited, the workstation is now protected
against a /tmp DOS. However, the /tmp fiilesystem is still full. Any applications
that need to write to the /tmp space will be unable to do so.
Task III - Identifying a CPU DOS and responding to it.
The following task teaches how to detect a CPU DOS and prevent future CPU DOS.
The task requires you to fork bomb your own system. This may cause the system
to stop responding. Be sure to save all of your work.
1) Open 4 terminal windows. In the first terminal window, use the sar command to monitor
the process table size. Have sar monitor every second for 1000 seconds. Notice the proc-sz
value.
[1] # sar -v 1 1000
19:40:20 proc-sz ov inod-sz ov file-sz ov lock-sz
19:40:21 63/7914 0 1955/33952 0 392/392 0 0/0
19:40:22 63/7914 0 1955/33952 0 392/392 0 0/0
19:40:23 63/7914 0 1955/33952 0 392/392 0 0/0
19:40:24 63/7914 0 1955/33952 0 392/392 0 0/0
2) In the second terminal window, use the vmstat command to monitor the run queue (r) field.
[2] # vmstat 1
procs memory page disk faults cpu
r b w swap free re mf pi po fr de sr dd f0 s5 s1 in sy cs us sy id
0 0 0 800712 352024 26 102 40 0 0 0 0 5 0 0 0 334 432 124 2 3 95
0 0 0 875544 420648 0 8 0 0 0 0 0 0 0 0 0 431 317 120 1 0 99
3) In the third terminal window, login via telnet to the localhost as the user guest.
[3] # telnet localhost
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
SunOS 5.8
login: guest
Password:
Last login: Tue Jul 30 15:58:55 from localhost
Sun Microsystems Inc. SunOS 5.8 Generic Patch October 2001
$
4) As user guest, create a fork bomb by editing two scripts called "a" and "b". These
scripts will do nothing but call each other an execute sleep processes. They will
continue in an infinite loop until the process table fills to capacity.
[3] $ vi a
./b &
sleep 20 &
[3] $ vi b
./a &
sleep 20 &
5) Make the scripts executable.
[3] $ chmod 555 a b
6) Execute the scripts. As soon as these scripts execute, look immediatley to terminal
windows 1 and 2 and notice the drastic change.
[3] $ ./a &
7) If the system is still responsive, monitor the vmstat and sar output. Also, in terminal
window 4, issue a ps -ef command.
[4] # ps -ef
<>
guest 9723 9722 0 19:51:18 ?? 0:00 -sh
guest 9767 9766 0 19:51:18 ?? 0:00 -sh
guest 8427 1 0 0:00
guest 9709 9708 0 19:51:18 ?? 0:00 -sh
guest 9800 9774 0 19:51:18 ?? 0:00 -sh
8) As the system administrator, stop the CPU DOS by killing all of the user guest's
processes.
[4] # pkill -u guest
9) Search the user guest's home directory for any files created in the last day.
[4] # find /export/home/guest -mtime -1
/export/home/guest
/export/home/guest/a
/export/home/guest/b
Task IV - Preventing CPU DOS
The purpose of this task is to configure the /etc/system file on the server to limit
the ammount of processes a user can take.
1) As root on the server, open up the kernel using the mdb command in read mode. The
adb utility is used for core dump analysis and information gathering on a live kernel.
All of the features of mdb are covered in "ST-350 - System Fault Analysis". The following
mdb command will display the current value for the maximun amoumt of user proceeses allowed
on the server.
# mdb -k
Loading modules: [ unix krtld genunix ip ufs_log nfs isp ipc random ptm logindmux ]
>maxuprc/D <-----Ask the kernel how many proccess a user can own.
maxuprc:
maxuprc: 7909 <-----The kernel reports that a user can own 7909 process table slots
>max_nprocs/D <-----Ask the kernel what the total process table size can be.
max_nprocs:
max_nprocs: 7914 <-----The kernel reports that the maximum table size is 7914. This means
that a user can reserve almost the entire process table
$q <----- exit adb
2) Since a regular user can consume an entire process table. Set a kernel tuning parameter
in the /etc/system file to limit the maximum user processes.
# vi /etc/system
<>
set maxuprc=100
3) Reboot the workstation.
# init 6
4) After the workstation has rebooted, verify with mdb that the kernel tuning setting worked.
# mdb -k
Loading modules: [ unix krtld genunix ip nfs ipc ptm logindmux ]
> maxuprc/D
maxuprc:
maxuprc: 100
>
5) Open three terminal windows. In the first terminal window, use the sar command
to monitor the process table size.
[1] # sar -v 1 1000
SunOS gabriel 5.8 Generic_108528-13 sun4u 08/01/02
18:48:57 proc-sz ov inod-sz ov file-sz ov lock-sz
18:48:58 42/7914 0 1430/33952 0 264/264 0 0/0
6) In the second terminal window, use the su command to assume the identity of guest. Run
the fork bomb.
[2] # su - guest
[2] $ id
uid=1001(guest) gid=10(staff)
[2] $ ./a
7) Observe the output in terminal window #1. Did the process table continue to grow or
did it level off?
sar -v 1 1000
SunOS gabriel 5.8 Generic_108528-13 sun4u 08/01/02
18:48:57 proc-sz ov inod-sz ov file-sz ov lock-sz
18:48:58 42/7914 0 1430/33952 0 264/264 0 0/0
18:48:59 42/7914 0 1430/33952 0 264/264 0 0/0
18:49:00 42/7914 0 1430/33952 0 264/264 0 0/0
18:49:01 141/7914 0 1430/33952 0 461/461 0 0/0
18:49:02 141/7914 0 1430/33952 0 461/461 0 0/0
18:49:03 141/7914 0 1430/33952 0 461/461 0 0/0
8) The "guest" user was limited to 100 processes by tuning the kernel.