October 2025
M T W T F S S
 12345
6789101112
13141516171819
20212223242526
2728293031  

Categories

October 2025
M T W T F S S
 12345
6789101112
13141516171819
20212223242526
2728293031  

GET PROCESS THREAD

#!/bin/bash
 
if[ $# -lt 1 ] ; then
    echo “Usage: “
    echo ”     threads_per_process.sh PID | process name [count] “
    echo “”
    echo “Example”
    echo ”  PID: 36434 or”
    echo ”  process string: NumThreads (this script will do a ps -ef|grep NumThreads to get the PID)”
    echo ”  The last number is the number of times the command will run”
    echo “”
    echo ”     threads_per_process.sh 36434 20″
    echo ”     threads_per_process.sh 36434 “
    echo ”     threads_per_process.sh NumThreads”
    echo ”     threads_per_process.sh NumThreads 20″
    echo “”
    exit 1
fi
 
echo “========================================================”
echo “The number of threads is displayed under the column NLWP”
echo “========================================================”
 
PROCESS_ID=$1
COLUMNS=140
 
DELAY=3
if[ $# -gt 1 ] ; then
    DELAY=$2
    shift
fi
 
DEFAULT_COUNT=1
COUNT=1
if[ $# -gt 1 ] ; then
    COUNT=$2
    DEFAULT_COUNT=0
fi
 
PATTERN=`echo $1 | sed ‘s/[0-9]//g’`
 
if[!z $PATTERN  ];then
    # string
    PROCESS_ID=`ps -ef |egrep -v ‘grep|threads_per’ |grep $1|awk ‘{print $2}’`
    echo “The PID to lookup is: “$PROCESS_ID
fi
 
CMD=“COLUMNS=$COLUMNS  ps -p $PROCESS_ID   -o pid,%cpu,rss,etime,nlwp,args”
CMD2=“COLUMNS=$COLUMNS ps -p $PROCESS_ID h -o pid,%cpu,rss,etime,nlwp,args”
 
PATTERN=`echo $PROCESS_ID | sed ‘s/\ /@/g’ | sed ‘s/[0-9]//g’`
n=0
HEADER_COUNT=15
if[z $PATTERN ];then
    if[ $COUNT ge 1];then
        while[ $n lt $COUNT ];do
            PROCESS_ID=`ps -e |awk ‘{print $1}’ | grep $PROCESS_ID`
            if[z $PROCESS_ID  ];then
                echo “The monitored PID no longer exists. Exiting.”
                exit 0;
            fi
            if[ $HEADER_COUNT ==0];then
                HEADER_COUNT=15
            fi
            if[ $HEADER_COUNT ==15];then
                eval $CMD|awk ‘{now=strftime(“%Y-%m-%d %T  “); print now $0}’
            else
                eval $CMD2|awk ‘{now=strftime(“%Y-%m-%d %T  “); print now $0}’
            fi
            HEADER_COUNT=$(expr $HEADER_COUNT 1)
            if[ $DEFAULT_COUNT eq 1];then
                n=0
            else
                n=$(expr $n +1)
            fi
            if[ $n lt $COUNT ];then
                sleep $DELAY
            fi
        done
    fi
else
    echo “The keyword \”$1\” return more than one PID. Please consider constraining the keyword”
fi

bash analyze ports and pids

# put your JAVA_HOME here,
JAVA_HOME=/opt/javavm
 
PID=$1
IFS=
top_number=10
if[ $# -gt 1 ] ; then
  top_number=$2
fi
 
top_number=$((top_number+1))
 
java_stack=`$JAVA_HOME/bin/jstack $PID`
 
top=`top -s -b -H -p $PID -n 1 | grep -vE ‘^top|^Tasks|^Cpu|^Mem|^Swap|^$’ | awk ‘NR==1; NR > 1 {print $0 | “sort  -nrk 9”}’ | head -$top_number`
echo $top
 
echo $top |while read psline;do
  if[`echo $psline|grep -c PID`gt 0];
    thencontinue
  fi
  lwp_id=`echo $psline | awk ‘{print $1}’`
  nid=`printf ‘%x\n’ $lwp_id `
  echo “========> Java LWP: $lwp_id – Native Thread ID=$nid”
  echo $java_stack | sed n “/$nid/,/^$/ p”;
done

Linux common SHELL

Linux common SHELL
1 delete 0 byte file
find -type f -size 0 -exec rm -rf {} \;
2. view the process
Arranged in descending memory
ps -e -o “% C:% p:% z:% a” | sort -k5 -nr
Press the cpu utilization in descending order
ps -e -o “% C:% p:% z:% a” | sort -nr
4 print says in the URL cache
grep -r -a jpg / data / cache / * | strings | grep “http:” | awk -F’http: ” {print “http:” $ 2;} ‘
5 Check number of concurrent requests and TCP connection status http in:
netstat -n | awk ‘/ ^ tcp / {++ S [$ NF]} END {for (a in S) print a, S [a]}’

6. sed -i ‘/ Root / s / no / yes /’ / etc / ssh / sshd_config sed in this text in Root row, matching Root line, replace the no into a yes.
7.1 How to kill mysql process:
ps aux | grep mysql | grep -v grep | awk ‘{print $ 2}’ | xargs kill -9 (learned from the use awk)
killall -TERM mysqld
kill -9 `cat / usr / local / apache2 / logs / httpd.pid` try killing the process PID

The display runs three levels of open services:
ls /etc/rc3.d/S* | cut -c 15- (learned from the use of cut, intercept data)
9 How to display more information in the preparation of SHELL, with EOF
cat << EOF
+ ————————————————- ————- +
| === Welcome to Tunoff services === |
+ ————————————————- ————- +
EOF
10. for the clever use (such as to build mysql soft link)
cd / usr / local / mysql / bin
for i in *
do ln / usr / local / mysql / bin / $ i / usr / bin / $ i
done
11 take IP address:
ifconfig eth0 | grep “inet addr:” | awk ‘{print $ 2}’ | cut -c 6- or
ifconfig | grep ‘inet addr:’ | grep -v ‘127.0.0.1’ | cut -d: -f2 | awk ‘{print $ 1}’
12 memory size:
free -m | grep “Mem” | awk ‘{print $ 2}’

13.
netstat -an -t | grep “: 80” | grep ESTABLISHED | awk ‘{printf “% s% s \ n”, $ 5, $ 6}’ | sort
14 See Apache concurrent requests and TCP connection status:
netstat -n | awk ‘/ ^ tcp / {++ S [$ NF]} END {for (a in S) print a, S [a]}’
15. colleagues to statistics about the server because all of the following jpg file size, wrote a shell to him to count. Original use xargs to achieve, but he once treated a part, there are more than the sum of the …. out, the following command will be able to solve it.
find / -name * .jpg -exec wc -c {} \; | awk ‘{print $ 1}’ | awk ‘{a + = $ 1} END {print a}’

The number of CPU’s (multi-accounting multiple CPU, cat / proc / cpuinfo | grep -c processor), the more low system load, the number of requests per second can handle the more.
————————————————– ————————————————– —————-
16 CPU load # cat / proc / loadavg
Before checking whether the three output value exceeds four times the system logical CPU.
18 CPU load #mpstat 1 1
Check% idle is too low (eg less than 5%)
19 memory space # free
Check free value is too low can also use # cat / proc / meminfo
20 swap space # free
Check swap used value is too high if the swap used value is too high, further examination swap action is frequent:
# Vmstat 1 5
Si and the observed values ??are so large
21 Disk Space # df -h
Check for partition usage (Use%) is too high (eg over 90%) found a partition space close to exhaustion, you can enter the mount point of the partition, use the following command to find the most space-consuming file or directory:
# Du -cks * | sort -rn | head -n 10
22 disk I / O load # iostat -x 1 2
Check the I / O utilization (% util) exceeds 100%
23 Network Load # sar -n DEV
Check the network traffic (rxbyt / s, txbyt / s) is too high
24 Network Error # netstat -i
Check whether there is a network error (drop fifo colls carrier) can also use the command: # cat / proc / net / dev
The number 25 network connection # netstat -an | grep -E “^ (tcp)” | cut -c 68- | sort | uniq -c | sort -n
26 processes total # ps aux | wc -l
Check whether the normal number of processes (eg more than 250)
27 The number of runnable processes # vmwtat 1 5
Column gives the number of runnable processes, check whether it exceeds the system logical CPU 4 times

28 Process # top -id 1
Observe whether there is an exception process occurs
29 Network status check DNS, gateway, etc. are properly connected
30 users # who | wc -l
Check the login user is excessive (eg over 50) can also use the command: # uptime
31 system log # cat / var / log / rflogview / * errors
Check for unusual error log can also search for some unusual keywords, for example:
# Grep -i error / var / log / messages
# Grep -i fail / var / log / messages
32 core logging # dmesg
Check for unusual error logging
33 system time # date
Check the system time is correct
34 the number of open files # lsof | wc -l
The total number of checking whether too many open files
35 Log # logwatch -print configuration /etc/log.d/logwatch.conf, the Mailto set their own email address, start mail service (sendmail or postfix), so that you can receive a daily log report.
The default logwatch report only yesterday logs, you can use # logwatch -print -range all get all the log analysis results.
You can use the # logwatch -print -detail high to obtain more detailed log analysis results (not just the error log).
36 killed 80 port-related processes
lsof -i: 80 | grep -v “PID” | awk ‘{print “kill -9”, $ 2}’ | sh
37. clear zombie processes.
ps -eal | awk ‘{if ($ 2 == “Z”) {print $ 4}}’ | kill -9
38.tcpdump capture, data can be analyzed to prevent being attacked on port 80
# Tcpdump -c 10000 -i eth0 -n dst port 80> / root / pkts
39. then check the IP number of repetitions and small to large order note “-t \ +0” in the middle of two spaces
# Less pkts | awk {‘printf $ 3 “\ n”‘} | cut -d -f 1-4 |. Sort | uniq -c | awk {‘printf $ 1 “” $ 2 “\ n”‘} | sort -n -t \ +0
40. have php-cgi process to see how many activities
netstat -anp | grep php-cgi | grep ^ tcp | wc -l
chkconfig –list | awk ‘{if ($ 5 == “3: on”) print $ 1}’
41.kudzu view card model
kudzu –probe –class = network
Matching Chinese characters regex: [\ u4e00- \ u9fa5]
Commentary: Matching Chinese really is a troublesome thing, with this expression will be easier
Matching double-byte characters (including characters including): [^ \ x00- \ xff]
Commentary: can be used to calculate the length of the string (a double-byte character length gauge 2, ASCII character count 1)
Blank lines matching regular expression: \ n \ s * \ r
Commentary: can be used to remove blank lines
HTML tags matching regular expression: <(\ S *?) [^>] *> * </ \ 1> | <* />.?.?
Commentary: Too bad the version circulated on the Internet, this is only able to match the above section, for complex nested tags still powerless
And last match whitespace regex: ^ \ s * | \ s * $
Commentary: whitespace delete the line end of the line can be used (including spaces, tabs, page breaks, etc.), very useful expression
Matching Email address regex: \ w + ([-. +] \ W +) * @ \ w + ([-.] \ W +) * \ \ w + ([-.] \ W +) *.
Commentary: When a very practical form validation
Website URL matching regular expression: [a-zA-z] +: // [^ \ s] *
Comment: The spread of the Internet version of the function is very limited, to meet the basic needs of the above
Match the account is legitimate (letter beginning, allowing 5-16 bytes, allowing alphanumeric characters and underscores): ^ [a-zA-Z] [a-zA-Z0-9 _] {4,15} $
Commentary: When a very practical form validation
Matching domestic phone number: \ d {3} – \ d {8} | \ d {4} – \ d {7}
Commentary: matching forms such as 0511-4405222 or 021-87888822
Matching Tencent QQ number: [1-9] [0-9] {4}
Commentary: Tencent QQ number from 10,000 to start
Matching China Postal Code: [1-9] \ d {5} (?! \ D)
Commentary: China ZIP code for six figures
Matching ID: \ d {15} | \ d {18}
Commentary: China’s ID card for 15 or 18
Match ip address:… \ D + \ \ d + \ \ d + \ \ d +
Commentary: When extracting useful ip address
Match a specific number:
^ [1-9] \ d * $ // match the positive integers
^ – [1-9] \ d * $ // match negative integers
^ -? [1-9] \ d * $ // match integers
^ [1-9] \ d * | 0 $ // match non-negative integer (positive integer + 0)
^ – [1-9] \ d * | 0 $ // matching non-positive integers (negative integer + 0)
^ [1-9] \ d * \ \ d * |.. 0 \ \ d * [1-9] \ d * $ // match float
^ – (.. [1-9] \ d * \ \ d * | 0 \ \ d * [1-9] \ d *) $ // match negative float
? ^ – (..?. [1-9] \ d * \ \ d * | 0 \ \ d * [1-9] \ d * | 0 \ 0+ | 0) $ // match float
^ [1-9] \ d * \ \ d * |.. 0 \ \ d * [1-9] \ d * | 0 \ 0+ |?. 0 $ // match non-negative floating point (float + 0)
^ (-.. ([1-9] \ d * \ \ d * | 0 \ \ d * [1-9] \ d *)) | 0 \ 0+ | 0 $ // matching non-upright?. points (negative float + 0)
Commentary: When handling large amounts of data useful to note that amendments to the specific application
Match a specific string:
^ [A-Za-z] + $ // match a string of 26 English letters
^ [AZ] + $ // match by 26 uppercase letters of the alphabet composed of a string
^ [az] + $ // match a string of 26 lowercase letters of the alphabet consisting of
^ [A-Za-z0-9] + $ // match the string of numbers and 26 letters of the English
^ \ w + $ // matching string by numbers, 26 English letters or underscores the
Commentary: some of the most basic and most common expressions

1 build file links
(1) Fixed Link:
When you delete a file which is actually just deleted the link to the file, if a file has multiple files linked to really delete this file must remove all links to this file
Example: foo bar create a fixed file link for the file named
ln foo bar
Display file link information
ls -i foo bar
(2) a symbolic link: Similar to the windows shortcuts
ln -s source file name destination file name
2 Find a file
(1) find: by file name to find the advantage is to find a flexible, the disadvantage is the search time is too long
Format: find a path expression match
find / -iname myfile *
Description: iname for matching expression, which has more than 20 kinds of choice
Example: Find by size
find / -size 53k
(2) locate: Find by file name, but according to the index to find, so the speed is faster than find
Example: locate * .ps
(3) whereis: the search results can be displayed while the file is a binary file, source code and documentation storage location of
Example: whereis find
(4) grep string filename parameter
3 archive command: Archive role is to package multiple files into one file, but it does not compress each file
Format: tar – parameter target file name of the source file
Parameter List:
-c establish archive
-f archive to a file instead of a tape drive
-v during replication, to join the file is displayed on the screen
-t display each file list
-x unlock an archive file to the appropriate directory, and contrary -c
-w in each filing / unlock the file for each file when confirmation, to prevent misuse overwrite files
By filing reconciliation gzip file when filtering -z
Archive formats: tar -cvf list of files to be archived archive file name
Example: tar -cvf vnc.tar / root
Xie file formats: tar -xvf archive file name
4 compression and decompression command
gzip – parameter file name
Description: gzip with winzip software is different, it can only compress a file, so often used in conjunction with the tar command, gzip generally without any parameters, such as:
gzip mydoc.tar
Will produce mydoc.tar.gz compressed file in the current directory
Note: You can use tar -z file compression, for example, type the following command
tar -cvfz resarch.tar.gz / etc
The above command will be on file in / etc archive for research.tar, then use gzip to compress files generated research.tar.gz
In contrast, type the following command:
tar -xvfz research.tar.gz
5.RPM (Redhat Package Manager abbreviation). It is a powerful software package developed by Redhat management software
(1) installation package
rpm -i package name
(2) Uninstall one package
rpm -e package name
6. rights management file / directory
-rw-r-r – l
In addition to the above file permissions first letter back nine groups of three letters each, followed by representatives of the file owner, file group, and other users all the permissions on the file, where r represents read
Permissions, w write permission on behalf of, x behalf of the Executive authority. Catalog, x permission for representatives of the search. File permissions shown above represent the file belongs to the user is concerned, it has read and write permissions
; For other users only read access. This is also the general file permissions allocation.
Note: The directory permissions greater than the file permissions
7 Change the file / directory permissions
chmod permissions for the file name + user categories
User categories include the following:
a representative of all users
g represents the file belongs to a user group
o behalf of all the documents to other users outside the group
Rights include: r, w, x
Example: myfile belongs to the group of users with write permissions:
chmod g + w myfile
Example: All users can execute mybatch file
chmod a + x mybatch
Establishment (similar dos bat file) in 8.Linux script file
The difference is that with dos in dos to distinguish whether the file extension to perform, but in linux by adding x to set the file executable permissions
Example: clear set as executable script file
chmod -u + x clear
9 change their user and group files
chown parameter user: group file name
Example: chown tlc: book destfile
The respective user destfile set to tlc, user group is set to book
10. process management
When you enter a command in the command line, as long as the command plus an & operator, you can make this program running in the background. For example, type updatedb & can make this task performed in the background
ctrl + z can put the programs into the background while suspended
bg so continue to be suspended
fg to keep it in the background
ctrl + c to terminate a program run
11 View into the Program Status: ps
Details ps -l display process
ps -f display process tree to represent the superior-subordinate relationship between processes
ps -r display running processes
ps -m display memory usage
Program processes the highest top 12 display system
k kill processes
q Exit
13. kill command to terminate the process
14. manage users and user groups
The general command format to add users
useradd username parameter
Example: useradd staff1 role is to build user staff1, this time not set a password, so then if this user is logged, no need to enter a password. The default user working directory is / home / username
Common parameters:
The minimum set user id id, this value should be greater than 99 and greater than the existing users: -u user id
-g user group name: The user should belong to the specified user group
-d working directory: Specifies the user’s working directory
useradd -g guest -d / mydoc user
This command creates a user-user, it belongs to the guest group (if not in this group, then create it). Its working directory is / mydoc (If you do not have this directory, then create it)
Delete user-friendly format:
userdel username parameter
This command is only one parameter -r, expressed delete users delete the user’s working directory
15. create and modify password
Under linux system in addition to the root user must set a password, the other ordinary user’s password from a technical point of view is not set, but for safety reasons, are generally required to set a password. Set a password in Linux command passwd, it’s the general format is:
passwd -u username
Example: psswd wang1 will modify the user’s password wang1
Achieved with one shell statement: all updated more than 10 days under the current directory (including subdirectories) suffix to suffix .a file .b
for i in $ (find -name ‘* .a’ -a -mtime +10.); do mv $ i $ {i% *.} b;. done
find -name ‘* .a’ -a -mtime +10 |. xargs rename .a .b
Little or insurance
find -name ‘* .a’ -a -mtime +10 |. xargs -n1 -i rename .a .b
. find -type f -name “* .b” | awk ‘{cmd = sprintf (“mv% s% sa /”, $ 1, substr ($ 1,1, length ($ 1) -2)); system
(cmd)} ‘
for i in $ (find -name ‘* .a’ -a -mtime +10.); do mv $ i [color = red] $ b [/ color] {i% *.};. done

shell programming, to achieve the following functions:
/ There are 800 files in tmp path, file name format is: filename_YYYYMMDD_ serial number (001 to 999) .dat, cases
Such as: filename_20040108_089.dat
Now wants to rename these files, the new file name format is: filename_TODAY (current date) _ serial number (from 500 starts to reach
After 999 from 001) .dat,
For example: the filename_20040108_089.dat to filename_20041222_589.dat, pay attention to the new file name order
No need to order of the columns and the original agreement, namely to do the sorting process.
#! / usr / bin / bash
DEST_FILE_PART2 = “_` date ‘+% Y% m% d’`_”
EXT_NAME = “. Dat”
SRC_FILE_LIST = `find / tmp -name” * _ * _ * $ EXT_NAME “-print`
for each in $ SRC_FILE_LIST; do
DEST_FILE_PART1 = `echo $ each | awk -F” _ “‘{print $ 1}’`
OLD_NUM = `echo $ each | awk -F” _ “‘{print $ 3}’ |”. “Awk -F ‘{print $ 1}’`
DEST_FILE_PART3 = `expr $ OLD_NUM + 500`
[$ DEST_FILE_PART3 -gt 999] && DEST_FILE_PART3 = `expr $ OLD_NUM – 499`
&& DEST_FILE_PART3 = `printf% 03d $ DEST_FILE_PART3`
DEST_FILE = $ DEST_FILE_PART1 $ DEST_FILE_PART2 $ DEST_FILE_PART3 $ EXT_NAME
echo “mv $ each to $ DEST_FILE”
mv $ each $ DEST_FILE
done
1 extracted from a.log file contains “WARNING” or “FATAL”, while not contain “IGNOR” line, and then extracted with “:” The first five split
Field
2 write a script, just a simple subtraction, require prompt input variables
3. Shell script reading (interpretation functions performed below), please pick the following program or script errors, and explain what went wrong.
#! / bin / bash
# Monitoring cpuser the point port is normal
logname = “/ home / forum / log / lpointlog.wf”
flagfile = “/ home / forum / log / lognum.txt”
lodnum = sed -n “1,1 p” $ flagfile
newnum = wc -l $ {logname}
echo $ newnum> $ flagfile
totalnum = expr $ newnum – $ oldnum
tail -n $ totalnum $ logname | grep “POINT_THREAD WARNING”
if [$? == 0]
then
mail -s “cpuser point” port exception, handle! “test@aa.com </ dev / null
fi>
Answer:
1.
grep -E ‘warning | fatal’ file | grep -v ignor | awk -F “:” ‘{print $ 5}’

awk ‘/ as / && / end / {print $ 1};! / bd / && / end / {print $ 1};!’ in

/ A / {} line containing the A’s
! / A / does not contain a row of A
Line / A /, / B / containing A, B that contains the
/ A / && / B / includes A, B, and contains the line
/ A /, / B / &&! / C / includes A, B does not contain the line that contains the C’s
Line / A / &&! / B /, / C / &&! / B / A does not contain contain B, to contain and do not contain B, C
2.
#! / bin / sh
echo -n “input var1:”
read var1
echo -n “input var2:”
read var2
echo $ (($ var1 – $ var2))

3.
(1) command line replaced with anti-quotes
`sed -n” 1,1 p “$ flagfile`
(2) if [$? == 0] should be written as if [$? = 0], is used to determine whether the last command executed successfully
if [$? = 0]
then
echo success
fi
(3) The penultimate line should be> / dev / null, behind the last fi> remove
1 variable expansion, when the environment variable is not blank (space or tab key) when separated from the surrounding text,
Please use a more explicit form of braces.
$ Myvar = ‘This is my environment variable!’
$ Echo foo $ {myvar} bar
fooThis is my environment variable! bar

2 extracted from the file path for the file name and path name of the command basename, dirname
$ Basename /usr/local/share/doc/foo/foo.txt
foo.txt
$ Dirname /usr/local/share/doc/foo/foo.txt
/ usr / local / share / doc / foo

3 command substitution, the results of the implementation of a command assigned to a variable, use `, or $ ()
$ MYDIR = `dirname / usr / local / share / doc / foo / foo.txt`
$ Echo $ MYDIR
/ usr / local / share / doc / foo
$ MYDIR = $ (dirname /usr/local/share/doc/foo/foo.txt)
$ Echo $ MYDIR
/ usr / local / share / doc / foo
4 string truncation, $ {MYVAR ## * fo}, $ {MYVAR # * fo}, $ {MYVAR %% * fo}, $ {MYVAR% * fo}
5. If statement in bash, all boolean expressions are enclosed in square brackets with
if [“$ {1 ## *.}” = “tar”]
6 references, you need to deal with all metacharacters quoted as follows:
? * [] ‘”\ $;! & () | ^ # Newline tab
For a single meta-characters, can be \ meta character escaping.
For the entire string, you can add single quotes around the string (‘), will make the whole string metacharacters lose all special meaning.
All per word for the entire string with a few exceptions, the use of double quotes, double quotes prohibited except $ (variable) and `(backtick command domain) than
Character.

Requirements: Completion of this program in a script
1 has been removed from the file user.list given user name and user group, these users and groups to the system by the rules
2 has been given to read the user’s password from password.list in.

user.list follows
zhangsan adminuser, dbuser, updatauser
lisi dbuser, updatauser
wanger updatauser, wheel
#! / bin / bash
#group add
for x in ‘awk’ {print $ 2} ‘user.list | sed’ s /, / \ n / g ‘| sort | uniq -c | sed’ s / [^ a-zA-Z] // g ”
do
groupadd $ x &> / dev / null
done

#back message
if (($? == 0))
then
echo “Group Ok !!”
else
exit 1
fi

#user add
for i in ‘awk’ {print $ 1} ‘user.list’
do
for y in ‘awk’ {print $ 2} ‘password.list’
do
useradd $ i &> / dev / null
echo $ y | passwd -stdin $ i &> / dev / null
done
done

#back message
if (($? == 0))
then
echo “User Ok!”
else
exit 1
fi

#add users to groups

for ((q = 1; q <= 3; q ++))
do

usermod -G ‘awk “NR == $ q {print $ 2}” user.list | awk’ {print $ 2} “‘awk” NR == $ q {print $ 1} ”
user.list | awk ‘{print $ 1} “&> / dev / null
done

if (($? == 0))
then
echo “All Finished!”
fi

 

 

 

No. mission command combination
A delete 0 byte files find -type f -size 0 -exec rm -rf {} \.;
find. type f -size 0 -delete
2 Check the process, in descending order by memory ps -e -o “% C:% p:% z:% a” | sort -k5 -nr
3 Press cpu utilization in descending order ps -e -o “% C:% p:% z:% a” | sort -nr
4 print said cache in the URL grep -r -a jpg / data / cache / * | strings | grep “http:” | awk -F’http: ” {print “http:” $ 2;} ‘
Number of concurrent requests and TCP connection status 5 See http The netstat -n | awk ‘/ ^ tcp / {++ S [$ NF]} END {for (a in S) print a, S [a]}’
6 sed in this text in Root row, matching Root line, replace the no into a yes. sed -i ‘/ Root / s / no / yes /’ / etc / ssh / sshd_config
7 How to kill mysql process ps aux | grep mysql | grep -v grep | awk ‘{print $ 2}’ | xargs kill -9
killall -TERM mysqld
kill -9 `cat / usr / local / apache2 / logs / httpd.pid`
8 shows the operation of three-level open service (learned from the use of cut, intercept data) ls /etc/rc3.d/S* | cut -c 15-
9 How to display more information in the preparation of SHELL, with EOF cat << EOF
+ ——————— +
| === Welcome to Tunoff services === |
+ ——————— +
EOF
10 for usage (eg to build mysql soft link) cd / usr / local / mysql / bin
for i in *
do ln / usr / local / mysql / bin / $ i / usr / bin / $ i
done
11 take IP address ifconfig eth0 | grep “inet addr:” | awk ‘{print $ 2}’ | cut -c 6-
ifconfig | grep ‘inet addr:’ | grep -v ‘127.0.0.1’ | cut -d: -f2 | awk ‘{print $ 1}’
12 memory size free -m | grep “Mem” | awk ‘{print $ 2}’
13 See the connection port 80 and sort netstat -an -t | grep “: 80” | grep ESTABLISHED | awk ‘{printf “% s% s \ n”, $ 5, $ 6}’ | sort
Number of concurrent requests and TCP connection state 14 See the Apache netstat -n | awk ‘/ ^ tcp / {++ S [$ NF]} END {for (a in S) print a, S [a]}’
15 statistics about the server all of the following jpg file size find / -name * .jpg -exec wc -c {} \; | awk ‘{print $ 1}’ | awk ‘{a + = $ 1} END {print a}’
Number cat 16 CPU’s / proc / cpuinfo | grep -c processor
17 CPU load cat / proc / loadavg
18 CPU load mpstat 1 1
19 free memory space
20 disk space df -h
21 found a partition space close to exhaustion, you can enter the mount point of the partition, to find the most space a file or directory with the following command du -cks * | sort -rn | head -n 10
22 disk I / O load iostat -x 1 2
23 Network Load sar -n DEV
24 network error netstat -i
cat / proc / net / dev
25 The number of network connections netstat -an | grep -E “^ (tcp)” | cut -c 68- | sort | uniq -c | sort -n
The total number of 26 processes ps aux | wc -l
27 See process tree ps aufx
28 The number of runnable processes vmwtat 1 5
Check whether the 29 DNS Server is working properly, for example here in order to dig www.baidu.com @ 61.139.2.69 61.139.2.69
30 to check the number of users currently logged in who | wc -l
31 log view, search cat / var / log / rflogview / * errors
grep -i error / var / log / messages
grep -i fail / var / log / messages
tail -f -n 2000 / var / log / messages
32 kernel log dmesg
33 time date
34 have open handles several lsof | wc -l
35 network packet capture, direct output summary information to a file. tcpdump -c 10000 -i eth0 -n dst port 80> / root / pkts
36 and then check the IP number of repetitions and small to large order note “-t \ +0” in the middle of two spaces, use less command. less pkts | awk {‘printf $ 3 “\ n”‘} | cut -d -f 1-4 | sort | uniq -c | awk {‘printf $ 1 “” $ 2 “\ n”‘} | sort -n -. t \ +0
37 kudzu View card type kudzu -probe -class = network

Perl Programming ( perl 5 )

Basics

Scripts

Perl is a script language, which is compiled each time before running. That unix knows that it is a perl script there must be the following header at the topline of every perl script: #!/usr/bin/perl where the path to perl has to be correct and the line must not exeed 32 charachters.
Comments and Commands

After the header line: #!/usr/bin/perl there are either empty lines with no effect or commandlines or commentary lines. Everything from and behind a “#” up to the end of the line is comment and has no effect on the program. Commands start with the first non space charachter on a line and end with a “;”. So one can continue a command over several lines and terminates it only with the semicolon.
Direct commands and soubroutines

Normal commands are executed in the order written in the script. But soubroutines can be placed anywhere and will only be evaluated when called from a normal commandline. Perl knows it’s a soubroutine if it the code is preceeded with a “sub” and enclosed in a block like: sub name { command;}
Other special lines

Perl can include other programming code with: require something or with use something.
Quotations

Single quote: ” or: q//
Double quote: “” or: qq//
Quote for execution: “ or: qx//
Quote a list of words: (‘term1′,’term2′,’term3’) or: qw/term1 term2 term3/
Quote a quoted string: qq/”$name” is $name/;
Quote something wich contains “/”: qq!/usr/bin/$file is readdy!;
Scalar and list context

That perl distinguishes between scalar and list context is the big feature, which makes it uniqe and more usful then most other script languages.

A soubroutine can return lists and not only scalars like in C. Or an array gives the number of elements in a scalar context and the elements itself in a list context.

The enormous value of that feature should be evident.

Variables and Operators

General

There are scalar variables, one and two dimensional arrays and associative arrays. Instead of declaring a variable one preceeds it with a spcial charachter. $variable is a normal scalar variable. @variable is an array and %variable is an associative array. The user of perl does not have to distinguish between a number and a string in a variable. Perl switches the type if neccessary.
Scalars

Fill in a scalar with: $price = 300; $name = “JOHN”; Calculate with it like: $price *= 2; $price = $oldprice * 4; $count++; $worth–; Print out the value of a scalar with: print $price,”\n”;
Arrays

Fill in a value: $arr[0] = “Fred”; $arr[1] = “John”; Print out this array: print join(‘ ‘,@arr),”\n”;
If two dimensional: $arr[0][0] = 5; $arr[0][1] = 7;
Hashes (Associative Arrays)

Fill in a single element with: $hash{‘fred’} = “USA”; $hash{‘john’} = “CANADA”;

Fill in the entire hash:
%a = (
‘r1’, ‘this is val of r1’,
‘r2’, ‘this is val of r2’,
‘r3’, ‘this is val of r3’,
);
or with:
%a = (
r1 => ‘this is val of r1’,
r2 => ‘this is val of r2’,
r3 => ‘this is val of r3’,
);
Assignements

Put something into a variable with a “=” or with some combined operator which assignes and and does something at the same time:

$var = “string”; Puts the string into $var
$var = 5; Puts a number into $var

$var .= “string”; Appends string to $var
$var += 5; Adds number to $var
$var *= 5; Multipliy with 5
$var ||= 5; If $var is 0 make it 5
$var x= 3; Make $var to three times $var as string: from a to aaa

Modify and assigne with:

($new = $old) =~ s/pattern/replacement/;
Comparisons

Compare strings with: eq ne like in: $name eq “mary”.
Compare numbers with: == != >= <= <=> like in: $price == 400.

And/Or/Not

Acct on success or failure of an expression: $yes or die; means exit if $yes is not set.
For AND we have: && and “and” and for OR we have: || or “or”. Not is “!” or “not”.

AND,OR and NOT are regularly used in if() statements:
if($first && $second){….;}
if($first || $second){….;}
if($first && ! $second{….;} means that $first must be non zero but $second must not be so.
But many NOT’s can be handled more reasonable with the unless() statement. Instead:
print if ! $noway; one uses: print unless $noway;

.

Branching

if

if(condition){
command;
}elsif(condition){
command;
}else{
command;
}

command if condition;
unless (just the opposite of if)

unless(condition){
command;
}else{
command;
}

command unless condition;
Looping

while

while(condition){
command;
}

# Go prematurely to the next iteration
while(condition){
command;
next if condition;
command;
}

# Prematureley abort the loop with last
while(condition){
command;
last if condition;
}

# Prematureley continue the loop but do continue{} in any case
while(condition){
command;
continue if condition;
command;
}continue{
command;
}

# Redo the loop without evaluating while(condtion)
while(condtion){
command;
redo if condition;
}

command while condition;
until (just the opposite of while)

until(condition){
command;
}

until(condition){
command;
next if condition;
command;
}

until(condition){
command;
last if condition;
}

until(condition){
command;
continue if condition;
command;
}continue{
command;
}

command until condtion;
for (=foreach)

# Iterate over @data and have each value in $_
for(@data){
print $_,”\n”;
}

# Get each value into $info iteratively
for $info (@data){
print $info,”\n”;
}

# Iterate over a range of numbers
for $num (1..100){
next if $num % 2;
print $num,”\n”;
}

# Eternal loop with (;;)
for (;;){
$num++;
last if $num > 100;
}
map

# syntax
map (command,list);
map {comm1;comm2;comm3;} list;
# example
map (rename($_,lc($_),<*>);
.
File Test Operators

File test operators check for the status of a file: Some examples:
-f $file It’s a plain file
-d $file It’s a directory
-r $file Readable file
-x $file Executable file
-w $file Writable file
-o $file We are owner
-l $file File is a link
-e $file File exists
-z $file File has zero size, but exists
-s $file File is greater than zero
-t FILEHANDLE This filehandle is connetcted to a tty
-T $file Textfile
-B $file Binary file
-M $file Returns the day number of last modification time

Regular Expressions

What it is

A regular expression is an abstract formulation of a string. Usually one has a search pattern and a match which is the found string. There is also a replacement for the match, if a substitution is made.
Patterns

A pattern stands for either one, any number, several, a particular number or none cases of a character or a charachter-set given literaly, abstractly or octaly.
PATTERN MATCH
. any character (dot)
.* any number on any character (dot asterix)
a* the maximum of consecutive a’s
a*? the minimum of consecutive a’s
.? one or none of any characters
.+ one or more of any character
.{3,7} three up to seven of any characters, but as many as possible
.{3,7}? three up to seven, but the fewest number possible
.{3,} at least 3 of any charachter
.{3} exactly 3 times any character
[ab] a or b
[^ab] not a and also not b
[a-z] any of a through z
^a
\Aa a at begining of string
a$
a\Z a at end of string
A|bb|CCC A or bb or CCC
tele(f|ph)one telefone or telephone
\w A-Z or a-z or _
\W none of the above
\d 0-9
\D none of 0-9
\s space or \t or \n (white space)
\S non space
\t tabulator
\n newline
\r carridge return
\b word boundary
\bkey matches key but not housekey
(?#…….) Comment
(?i) Case insensitive match. This can be inside a pattern variable.
(?:a|b|c) a or b or c, but without string in $n
(?=…..) Match ….. but do not store in $&
(?!…..) Anything but ….. and do not store in $&
Substitututions

One can replace found matches with a replacement with the s/pattern/replacement/; statement.
The “s” is the command. Then there follow three delimiters with first a search pattern and second a replacement between them. If there are “/” withing the pattern or the replacement then one chooses another delimiter than “/” for instance a “!”.

To change the content of a variable do: $var =~ s/pattern/replacement/;
To put the changed value into another variable, without distorting the original variable do:
($name = $line) =~ s/^(\w+).*$/$1/;
COMMAND WHAT it DOES
s/A/B/; substitute the first a in a string with B
s/A/B/g; substitute every a with a B
s/A+/A/g; substitute any number of a with one A
s/^#//; substitute a leading # with nothing. i.e remove it
s/^/#/; prepend a # to the string
s/A(\d+)/B$1/g; substitute a followed by a number with b followed by the same number
s/(\d+)/$1*3/e; substitute the found number with 3 times it’s value
Use two “e” for to get an eval effect:
perl -e ‘$aa = 4; $bb = ‘$aa’; $bb =~ s/(\$\w+)/$1/ee; print $bb,”\n”;’
s/here goes date/$date/g; substitute “here goes date” with the value of $date
s/(Masumi) (Nakatomi)/$2 $1/g; switch the two terms
s/\000//g; remove null charachters
s/$/\033/; append a ^M to make it readable for dos
Input and Output

Output a value from a variable

print $var,”\n”;
Output a formated string

printf(“%-20s%10d”,$user,$wage);
Read in a value into a variable and remove the newline

chomp() (perl5) removes a newline if one is there. The chop() (perl4) removes any last character.

chomp($var = );
Read in a file an process it linewise

open(IN,”<filename”) || die “Cannot open filename for input\n”;
while(){
command;
}
close IN;
Read a file into an array

open(AAA,”<infile”) || die “Cannot open infile\n”;
@bigarray = ;
close AAA;
Output into a file

open(OUT,”>file”) || die “Cannot oben file for output\n”;
while(condition){
print OUT $mystuff;
}
close OUT;
Check, whether open file would yield something (eof)

open(IN,”<file”) || die “Cannot open file\n”;
if(eof(IN)){
print “File is empty\n”;
}else{
while(){
print;
}
}
close IN;
Process Files mentioned on the Commandline

The empty filehandle “<>” reads in each file iteratively. The name of the current processed file is in $ARGV. For example print each line of several files prepended with it’s filename:
while(<>){
$file = $ARGV;
print $file,”\t”,$_;
open(IN,”<$file”) or warn “Cannot open $file\n”;
….commands for this file….
close(IN);
}
Get Filenames

Get current directory at once

@dir = <*>;
Use current directory iteratively

while(<*>){
…commands…
}
Select files with <>

@files = ;
Select files with glob()

This is the official way of globbing:
@files = glob(“$mypatch/*$suffix”);

Readdir()

Perl can also read a directory itself, without a globbing shell. This is faster and more controllable, but one has to use opendir() and closedir().
opendir(DIR,”.”) or die “Cannot open dir.\n”;
while(readdir DIR){
rename $_,lc($_);
}
closedir(DIR);
Pipe Input and Output from/to Unix Commands

Process Data from a Unix Pipe

open(IN,”unixcommand|”) || die “Could not execute unixcommand\n”;
while(){
command;
}
close IN;
Output Data into a Unix Pipe

open(OUT,”|more”) || die “Could not open the pipe to more\n”;
for $name (@names){
$length = length($name);
print OUT “The name $name consists of $lenght characters\n”;
}
close OUT;
Execute Unix Commands

Execute a Unix Command and forget about the Output

system(“someprog -auexe -fv $filename”);
Execute a Unix Command an store the Output into a Variable

If it’s just one line or a string:

chomp($date = qx!/usr/bin/date!); The chomp() (perl5) removes the trailing “\n”. $date gets the date.

If it gives a series of lines one put’s the output into an array:

chomp(@alllines = qx!/usr/bin/who!);
Replace the whole perl program by a unix program

exec anotherprog; But then the perl program is gone.

The Perl builtin Functions

String Functions

Get all upper case with: $name = uc($name);
Get only first letter uppercase: $name = ucfirst($name);
Get all lowercase: $name = lc($name);
Get only first letter lowercase: $name = lcfirst($name);
Get the length of a string: $size = length($string);
Extract 5-th to 10-th characters from a string: $part = substr($whole,4,5);
Remove line ending: chomp($var);
Remove last character: chop($var);
Crypt a string: $code = crypt($word,$salt);
Execute a string as perl code: eval $var;
Show position of substring in string: $pos = index($string,$substring);
Show position of last substring in string: $pos = rindex($string,$substring);
Quote all metacharachters: $quote = quotemeta($string);
Array Functions

Get expressions for which a command returned true: @found = grep(/[Jj]ohn/,@users);
Applay a command to each element of an array: @new = map(lc($_),@start);
Put all array elements into a single string: $string = join(‘ ‘,@arr);
Split a string and make an array out of it: @data = split(/&/,$ENV{‘QUERY_STRING’};
Sort an array: sort(@salery);
Reverse an array: reverse(@salery);
Get the keys of a hash(associative array): keys(%hash);
Get the values of a hash: values(%hash);
Get key and value of a hash iteratively: each(%hash);
Delete an array: @arr = ();
Delete an element of a hash: delete $hash{$key};
Check for a hash key: if(exists $hash{$key}){;}
Check wether a hash has elements: scalar %hash;
Cut of last element of an array and return it: $last = pop(@IQ_list);
Cut of first element of an array and return it: $first = shift(@topguy);
Append an array element at the end: push(@waiting,$name);
Prepend an array element to the front: unshift(@nowait,$name);
Remove first 2 chars an replace them with $var: splice(@arr,0,2,$var);
Get the number of elements of an array: scalar @arr;
Get the last index of an array: $lastindex = $#arr;
File Functions

Open a file for input: open(IN,”/path/file”) || die “Cannot open file\n”;
Open for appending: open(OUT,”>>$file”) || &myerr(“Couldn’t open $file”);
Close a file: close OUT;
Set permissions: chmod 0755, $file;
Delete a file: unlink $file;
Rename a file: rename $file, $newname;
Make a hard link: link $existing_file, $link_name;
Make a symbolic link: symlink $existing_file, $link_name;
Make a directory: mkdir $dirname, 0755;
Delete a directory: rmdir $dirname;
Reduce a file’s size: truncate $file, $size;
Change owner- and group-ID: chown $uid, $gid;
Find the real file of a symlink: $file = readlink $linkfile;
Get all the file infos: @stat = stat $file;
Conversions Functions

Number to character: chr $num;
Charachter to number: ord($char);
Hex to decimal: hex(0x4F);
Octal to decimal: oct(0700);
Get localtime from time: localtime(time);
Get greenwich meantime: gmtime(time);
Pack variables into string: $string = pack(“C4”,split(/\./,$IP));
Unpack the above string: @arr = unpack(“C4”,$string);
Subroutines (=functions in C++)

Define a Subroutine

sub mysub {
command;
}
Example:
sub myerr {
print “The following error occured:\n”;
print $_[0],”\n”;
&cleanup;
exit(1);
}
Call a Subroutine

&mysub;
Give Arguments to a Subroutine

&mysub(@data);
Receive Arguments in the Subroutine

As global variables:
sub mysub {
@myarr = @_;
}
sub mysub {
($dat1,$dat2,$dat3) = @_;
}
As local variables:
sub mysub {
local($dat1,$dat2,$dat3) = @_;
}

Some of the Special Variables

SYNTAX

MEANING

$_ String from current loop. e.g. for(@arr){ $field = $_ . ” ok”; }
$. Line number from current file processed with: while(){
$0 Programname
$$ Process id of current program
$< The real uid of current program $> Effektive uid of current program
$| For flushing output: select XXX; $| = 1;
$& The match of the last patternsearch
$1…. The ()-embraced matches of the last patternsearch
$` The string to the left of the last match
$’ The string to the right of the last match

Forking

Forking is very easy! Just fork. One puts the fork in a three way if(){} to separately the parent, the child and the error.
if($pid = fork){
# Parent
command;
}elsif($pid == 0){
# Child
command;
# The child must end with an exit!!
exit;
}else{
# Error
die “Fork did not work\n”;
}

Building Pipes for forked Children

Building a Pipe

pipe(READHANDLE,WRITEHANDLE);
Flushing the Pipe

select(WRITEHANDLE); $| = 1; select(STDOUT);
Setting up two Pipes between the Parent and a Child

pipe(FROMCHILD,TOCHILD); select(TOCHILD); $| = 1; select(STDOUT);
pipe(FROMPARENT,TOPARENT);select(TOPARENT);$| = 1; select(STDOUT);

if($pid = fork){
# Parent
close FROMPARENT;
close TOPARENT;
command;
}elsif($pid == 0){
# Child
close FROMCHILD;
close TOCHILD;
command;
exit;
}else{
# Error
command;
exit;
}
Building a Socket Connection to another Computer

# Somwhere at the beginning of the script
require 5.002;
use Socket;
use sigtrap;

# Prepare infos
$port = 80;
$remote = ‘remotehost.domain’;
$iaddr = inet_aton($remote);
$paddr = sockaddr_in($port,$iaddr);

# Socket
socket(S,AF_INET,SOCK_STREAM,$proto) or die $!;

# Flush socket
select(S); $| = 1; select(STDOUT);

# Connect
connect(S,$paddr) or die $!;

# Print to socket
print S “something\n”;

# Read from socket
$gotit = ;

# Or read a single character only
read(S,$char,1);

# Close the socket
close(S);
Get Unix User and Network Informations

Get the password entry for a particular user with: @entry = getpwnam(“$user”);
Or with bye user ID: @entry = getpwuid(“$UID”);

One can informations for group, host, network, services, protocols in the above way with the commands: getgrnam, getgrid, gethostbyname, gethostbyaddr, getnetbyname, getnetbyaddr, getservbyname, getservbyport, getprotobyname, getprotobynumber.

If one wants to get all the entries of a particular categorie one can loop through them by:

setpwent;
while(@he = getpwent){
commands…
}
entpwent;

For example: Get a list of all users with their homedirectories:
setpwent;
while(@he = getpwent){
printf(“%-20s%-30s\n”,$he[0],$he[7]);
}
endpwent;
The same principle works for all the above data categories. But most of them need a “stayopen” behind the set command.

Arithmetics

Addition: +
Subtraction: –
Multiplication: *
Division: /
Rise to the power of: **
Rise e to the pwoer of: exp()
Modulus: %
Square root: sqrt()
Absolut value: abs()
Tangens: atan2()
Sinus: sin()
Cosine: cos()
Random number: rand()

Formatting Output with “format”

This should be simplification of the printf formatting. One formats once only and then it will be used for every write to a specified filehandle. Prepare a format somwhere in the program:

format filehandle =
@<<<<<<<<<<@###.#####@>>>>>>>>>>@||||||||||
$var1, $var3, $var4
.

Now use write to print into that filhandle according to the format:

write FILEHANDLE;

The @<<< does left adjustment, the @>>> right adjustment, @##.## is for numericals and @||| centers.

Command line Switches

Show the version number of perl: perl -v;
Check a new program without runing it: perl -wc ;
Have an editing command on the command line: perl -e ‘command’;
Automatically print while precessing lines: perl -pe ‘command’ ;
Remove line endings and add them again: perl -lpe ‘command’ ;
Edit a file in place: perl -i -pe ‘command’ ;
Autosplit the lines while editing: perl -a -e ‘print if $F[3] =~ /ETH/;’ ;
Have an input loop without printing: perl -ne ‘command’ ;

Ksh Scripting

Principle of Script

Defining the Shell Type

To make a ksh script (which is a ksh program) crate a new file with a starting line like:
#!/usr/bin/ksh
It is important that the path to the ksh is propper and that the line doesn not have more than 32 characters. The shell from which you are starting the script will find this line and and hand the whole script over to to ksh. Without this line the script would be interpreted by the same typ of shell as the one, from which it was started. But since the syntax is different for all shells, it is necessary to define the shell with that line.

Four Types of Lines

A script has four types of lines: The shell defining line at the top, empty lines, commentary lines starting with a # and command lines. See the following top of a script as an example for these types of lines:

#!/usr/bin/ksh

# Commentary……

file=/path/file
if [[ $file = $1 ]];then
command
fi
Start and End of Script

The script starts at the first line and ends either when it encounters an “exit” or the last line. All “#” lines are ignored.

Start and End of Command

A command starts with the first word on a line or if it’s the second command on a line with the first word after a”;’.
A command ends either at the end of the line or whith a “;”. So one can put several commands onto one line:

print -n “Name: “; read name; print “”

One can continue commands over more than one line with a “\” immediately followed by a newline sign which is made be the return key:

grep filename | sort -u | awk ‘{print $4}’ | \
uniq -c >> /longpath/file
Name and Permissions of Script File

The script mus not have a name which is identical to a unix command: So the script must NOT be called “test”!
After saveing the file give it the execute permissions with: chmod 700 filename.

Variables

Filling in

When filling into a variable then one uses just it’s name: state=”US” and no blanks. There is no difference between strings and numbers: price=50.

Using

When using a variable one needs to put a $ sign in front of it: print $state $price.

Arrays

Set and use an array like:

arrname[1]=4 To fill in
print ${arraname[1]} To print out
${arrname[*]} Get all elements
${#arrname[*]} Get the number of elements
Declaration

There are happily no declarations of variables needed in ksh. One cannot have decimals only integers.

Branching

if then fi

if [[ $value -eq 7 ]];then
print “$value is 7”
fi
or:

if [[ $value -eq 7 ]]
then
print “$value is 7”
fi
or:

if [[ $value -eq 7 ]];then print “$value is 7”;fi
if then else fi

if [[ $name = “John” ]];then
print “Your welcome, ${name}.”
else
print “Good bye, ${name}!”
fi
if then elif then else fi

if [[ $name = “John” ]];then
print “Your welcome, ${name}.”
elif [[ $name = “Hanna” ]];then
print “Hello, ${name}, who are you?”
else
print “Good bye, ${name}!”
fi
case esac

case $var in
john|fred) print $invitation;;
martin) print $declination;;
*) print “Wrong name…”;;
esac
Looping

while do done

while [[ $count -gt 0 ]];do
print “\$count is $count”
(( count -= 1 ))
done
until do done

until [[ $answer = “yes” ]];do
print -n “Please enter \”yes\”: ”
read answer
print “”
done
for var in list do done

for foo in $(ls);do
if [[ -d $foo ]];then
print “$foo is a directory”
else
print “$foo is not a directory”
fi
done
continue…break

One can skip the rest of a loop and directly go to the next iteration with: “continue”.

while read line
do
if [[ $line = *.gz ]];then
continue
else
print $line
fi
done
One can also prematurely leave a loop with: “break”.

while read line;do
if [[ $line = *!(.c) ]];then
break
else
print $line
fi
done
Command Line Arguments

(Officially they are called “positional parameters”)

The number of command line arguments is stored in $# so one can check
for arguments with:
if [[ $# -eq 0 ]];then
print “No Arguments”
exit
fi
The single Arguments are stored in $1, ….$n and all are in $* as one string. The arguments cannot
directly be modified but one can reset the hole commandline for another part of the program.
If we need a first argument $first for the rest of the program we do:
if [[ $1 != $first ]];then
set $first $*
fi
One can iterate over the command line arguments with the help of the shift command. Shift indirectly removes the first argument.
until [[ $# -qe 0 ]];do
# commands ….
shift
done
One can also iterate with the for loop, the default with for is $*:

for arg;do
print $arg
done
The program name is stored in $0 but it contains the path also!

Comparisons

To compare strings one uses “=” for equal and “!=” for not equal.
To compare numbers one uses “-eq” for equal “-ne” for not equal as well as “-gt” for greater than
and “-lt” for less than.

if [[ $name = “John” ]];then
# commands….
fi
if [[ $size -eq 1000 ]];then
# commands….
fi
With “&&” for “AND” and “||” for “OR” one can combine statements:

if [[ $price -lt 1000 || $name = “Hanna” ]];then
# commands….
fi
if [[ $name = “Fred” && $city = “Denver” ]];then
# commands….
fi

Variable Manipulations

Removing something from a variable

Variables that contain a path can very easily be stripped of it: ${name##*/} gives you just the filename.
Or if one wants the path: ${name%/*}. % takes it away from the left and # from the right.
%% and ## take the longest possibility while % and # just take the shortest one.
Replacing a variable if it does not yet exits

If we wanted $foo or if not set 4 then: ${foo:-4} but it still remains unset. To change that we use:
${foo:=4}
Exiting and stating something if variable is not set

This is very important if our program relays on a certain vaiable: ${foo:?”foo not set!”}
Just check for the variable

${foo:+1} gives one if $foo is set, otherwise nothing.

Ksh Regular Expressions

Ksh has it’s own regular expressions.
Use an * for any string. So to get all the files ending it .c use *.c.
A single character is represented with a ?. So all the files starting with any sign followed bye 44.f can be fetched by: ?44.f.

Especially in ksh there are quantifiers for whole patterns:

?(pattern) matches zero or one times the pattern.
*(pattern) matches any time the pattern.
+(pattern) matches one or more time the pattern.
@(pattern) matches one time the pattern.
!(pattern) matches string without the pattern.

So one can question a string in a variable like: if [[ $var = fo@(?4*67).c ]];then …

Functions

Description

A function (= procedure) must be defined before it is called, because ksh is interpreted at run time.
It knows all the variables from the calling shell except the commandline arguments. But has it’s
own command line arguments so that one can call it with different values from different places in
the script. It has an exit status but cannot return a value like a c funcition can.
Making a Function

One can make one in either of the following two ways:
function foo {
# commands…
}

foo(){
# commands…
}
Calling the Function

To call it just put it’s name in the script: foo. To give it arguments do: foo arg1 arg2 …
The arguments are there in the form of $1…$n and $* for all at once like in the main code.
And the main $1 is not influenced bye the $1 of a particular function.
Return

The return statement exits the function imediately with the specified return value as an exit status.

Data Redirection

General

Data redirection is done with the follwoing signs: “> >> < <<". Every program has at least a standardinput, standardoutput and standarderroroutput. All of these can be redirected. Command Output to File For writing into a new file or for overwriting a file do: command > file

For appending to a file do: command >> file

Standard Error Redirection

To redirect the error output of a command do: command 2> file

To discard the error alltogether do: command 2>/dev/null

To put the error to the same location as the normal output do: command 2>&1

File into Command

If a program needs a file for input over standard input do: command < file Combine Input and Output Redirection command < infile > outfile
command < infile > outfile 2>/dev/null

Commands into Program ( Here Document )

Every unix command can take it’s commands from a text like listing with:

command < “testfile” }
‘ a=$var
BEGIN { }, { } and end { }

An awk script can have three types of blocks. One of them must be there. The BEGIN{} block is processed before the file is checked. The {} block runs for every line of input and the END{} block is processed after the final line of the input file.

awk ‘
BEGIN { myvalue = 1700 }
/debt/ { myvalue -= $4 }
/want/ { myvalue += $4 }
END { print myvalue }
‘ infile
Match in a particular field

Awk autosplits a line on whitespace as default. The fields are stored in $1 through $NF and the whole line is in $0. One can match or not match an individual field.

awk ‘
$1 ~ /fred/ && $4 !~ /ok/ {
print “Fred has not yet paid $3”
}
‘ infile
For, If, substr()

Awk can do for() loops like in c++ and has the normal if and while structures. In NR is current line number and in NF the number of fields on the current line.

awk ‘
BEGIN { count = 0 }
/myline/ {
for(i=1;i<=NF;i++){ if(substr($i,3,2) == "ae"){ bla = "Found it on line: " print bla NR " in field: " i count++ } } } END { print "Found " count " instances of it" } ' infile Turn around each word in a file: awk ' { for(i=1;i<=NF;i++){ len = length($i) for(j=len;j>0;j–){
char = substr($i,j,1)
tmp = tmp char
}
$i = tmp
tmp = “”
}
print
}
‘ infile
Awk scripts within a shell script

Extract email addresses from incoming mail. The mail would be guided to the following script from within the ~/.forward file. This is not an eficient method, but only an example to show serial processing of text. The next example will do the same thing within awk only and will be efficient. The mail comes in over standardinput into the script.
Between the commands there must be a pipe “|”. For continuing on the next line one needs a “\” behind the pipe to escape the invisible newline.
#!/usr/bin/ksh
{ while read line;do
print – “$line”
done } |\
tee -a /path/mymailfile |\
awk ‘
/^From/ || /^Replay/ {
for(i=1;i<=NF;i++){ if($i ~ /@/){ print $i } } } ' |\ sed ' s/[<>]//g;
s/[()]//g;
s/”//g;
…more substitutions for really extracting the email only…
‘ |\
{ while read addr;do

if [[ $(grep -c $addr /path/antimailfile) -gt 0 ]];then

mail $addr <>, gsub(), getline, system()

With #!/usr/bin/nawk -f the whole script is interpreted intirely as an awk script and no more shell escapes are needed, but one can and has to do everything in awk itself. It’s nawk because of the getline function.
While iterates until the expression becomes wrong or until a break is encountered.
Gsub() is for string substitution.
Getline reads in a line each time it es called.
System() executes a unix command.
“>>” appends to a file.

This script es an example only. For really extracting email addresses several special cases would have to be considered…

#!/usr/bin/nawk -f

# Lines from a mail are dropping in over stdin. Append every line to a
# file before checking anything.

{ print >> “/path/mymailfile” }

# Find lines with with From: or Replay: at beginning.

/^From:/ || /^Replay/ {

# Find fields with @. Iterate over the fields and check for @

for(i=1;i<=nf;i++){ if($i ~ /@/){ # Clean the email addresses with gsub() gsub(/[<>()”]/,””,$i)

# Check whether the email address is in the antimailfile

while( getline antiaddr < "/path/antimailfile" ){ # Compare actual address in $i with loaded address if($i == antiaddr){ # Send a negative mail system("mail " $i " < /path/badmail") # Now end the while loop break }else{ # Send a positive mail system("mail " $i " < /path/goodmail") } } } } } Calculate on columns and print formated output If one has a formated input of number columns one can still split them on white space, but has to consider the format for output with printf() #!/usr/bin/nawk -f # Reprintet lines without foo or boo ! /(foo|boo)/ { print } # Rearange and calculate with columns but only on lines with foo or boo /(foo|boo)/ { # Extract fields mytype = $1 var1 = $2 var2 = $3 var3 = $4 # Calculate if(mytype == "foo"){ var1 *= 10 var2 += 20 var3 = log(var3) } if(mytype == "boo"){ var1 *= 4 var2 += 10 var3 = cos(var3) } # Print formated output in reverse order printf("%-4s%10.3f%10.3f%10.3f\n",mytype,var3,var2,var1) } How to iterate over each word of a shell variable in awk In this example there is first a shell variable filled in and then it is given to awk. Awk splits it into an array and then iterates over the array and looks for each word on the current line of a file. If it finds it, it prints the whole line. #!/usr/bin/ksh var="term1 term2 term3 term4 term5" awk ' BEGIN { split(myvar,myarr) } { for(val in myarr){ if($0 ~ myarr[val]){ print } } } ' myvar="$var" file Functions This example substitutes the first three occurences of "searchterm" with a different term in each case and from the fourth case it just prints the line as it is. It should show where to place a function and how to call it. #!/usr/bin/nawk -f BEGIN{ mysub1 = "first_sub" mysub2 = "second_sub" mysub3 = "third_sub" mycount = 1 find = "searchterm" } { if($0 ~ find){ if(mycount == 1){ replace(mysub1); } if(mycount == 2){ replace(mysub2); } if(mycount == 3){ replace(mysub3); } if(mycount > 3){ print; }
mycount++
}else{
print
}
}
function replace(mysub) {

sub(find,mysub)
print
break
}
CGI with gawk

As an example for a CGI script in awk I make one which presents the unix man pages in html.

man.cgi

String functions

sub(regexp,sub) Substitute sub for regexp in $0
sub(regexp,sub,var) Substitute sub for regexp in var
gsub(regexp,sub) Globally substitute sub for regexp in $0
gsub(regexp,sub,var) Globally substitute sub for regexp in var
split(var,arr) Split var on white space into arr
split(var,arr,sep) Split var on white space into arr on sep as separator
index(bigvar,smallvar) Find index of smallvar in bigvar
match(bigvar,expr) Find index for regexp in bigvar
length(var) Number of characters in var
substr(var,num) Extract chars from posistion num to end
substr(var,num1,num2) Extract chars from num1 through num2
sprintf(format,vars) Format vars to a string
When to use awk, when to use perl?

Perl can do 100 times more than awk can, but awk is present on any standard unix system, where perl first has to be installed. And for short commands awk seems to be more practical. The autosplit mode of perl splits into pieces called: $F[0] through $F[$#F] which is not so nice as $1 through $NF where awk retains the whole line in $0 at the same time.
To get the first column of any file in awk and in perl:

awk ‘{print $1}’ infile
perl -nae ‘print $F[0],”\n”;’ infile

Linux Troubleshooting Commands

Biggest 10 Files
du -sh * | sort -n | tail
du -x -a . | sort -n -r | head -n 10

List All the Process By memory usage
ps -e -orss=,args= | sort -b -k1,1n | pr -TW$COLUMNS
ps -eo pcpu,pid,user,args | sort -k 1 -r | head -10
ps -eo pcpu,pid,user,args | sort -r -k1 | less

find how many files an application is using
lsof +c 0 | cut -d’ ‘ -f1 | sort | uniq –c

Highest CPU Usage
ps -eo pcpu,pid,user,args | sort -k 1 -r | head -10 | awk “{ print $2 }”

Total Memory Usage
sar -q 1 | tail -1 | awk ‘{ print “” $3}’ | sed ‘s/%//g’

CPU Threshold
top -b -n 1 | awk -F'[:,]’ ‘/^Cpu/{sub(“\\..*”,””,$2); print $2}’

Current User With Session Count
who | awk ‘{ User [$1]++; } END { for (i in User) printf “%-9s %s\n”, i, User [i] }’

Memory Details
free -t -m | grep “Total” | awk ‘{ print “Total Memory space : “$2 ” MB”;
print “Used Memory Space : “$3″ MB”;
print “Free Memory : “$4″ MB”;
}’

Swap memory Details
free -t -m | grep “Swap” | awk ‘{ print “Total Swap space : “$2 ” MB”;
print “Used Swap Space : “$3″ MB”;
print “Free Swap : “$4″ MB”;
}’

Process Using memory
ps aux | awk ‘{if ($5 != 0 ) print $2,$5,$6,$11}’ | sort -k2n

Largest File Or Directory
du -sk /var/log/* | sort -r -n | head -10

Processes Count Used By Users
ps hax -o user | sort | uniq -c

Who Started this Process
ps -o comm= -p $(ps -o ppid= -p PID)

How Much Ram Is Being Used
ps -o rss -C java | tail -n +2 | (sed ‘s/^/x+=/’; echo x) | bc

When Was the Process Started
ps -o lstart PID

Environment Variables belong to a Process
ps ewwo command PID | tr ‘ ‘ ‘\n’ | grep \=

List Threads by Pid along with Thread Start Time
ps -o pid,lwp,lstart –pid PID -L

CPU usage for EACH cores
ps ax -L -o pid,tid,psr,pcpu,args | sort -nr -k4| head -15 | cut -c 1-90

Memory Percentage Usage of a Process
ps -o comm,%mem,args PID

Total CPU Usage Percentage
ps aux | awk {‘sum+=$3;print sum’} | tail -n 1

Find Class Files inSide the Jar Location
find . -iname ‘*.jar’ -printf “unzip -c %p | grep -q ‘sample Text’ && echo %p\n” | sh

Find the Class File in jars
find . -name “*.jar” | while read line; do unzip -l $line; done | grep

Search The File From Multiple Jar Files
find . -name “*.jar” | xargs -tn1 jar tvf | grep –color “log4j.xml”

List of Files That Are Open For Writing to Disk
lsof | grep -e “[[:digit:]]\+w”

See which Process is Holding the File
lsof -r1 /common/jboss.log

List the files accessed by a program
strace -f -o foo.trace su user -c ‘mycommand’?

get size of data that haven’t been written to disk yet
The term for that is “dirty” data (data that has been changed, but not yet flushed to permanent storage).
cat /proc/meminfo | grep Dirty
Dirty : 188 kB

Owner of the File
/sbin/fuser admin.lok
admin.lok: 5912
Pmap Output In Kilo Bytes
pmap -x PID | awk ‘/\[ anon \]/ {total += $3} END {print total}’

determine which application is utilizing a certain port?
lsof -w -n -i tcp:80 ( or any Othe Port)
Start Number of active, and recently torn down TCP sessions
netstat -ant | egrep -i ‘(ESTABLISHED|WAIT|CLOSING)’ | wc -l

Number of sessions waiting for ACK (SYN Flood)
netstat -ant | egrep -i ‘(SYN)’ | wc -l
Find Network Connections
Out Going Going Connections
localhost:root002-~ $ lsof | grep omdx1971
java 1142 dwls977 924u IPv6 141719124 0t0 TCP localMachine :27710->eth0.remoteMachine.nova.com:54426 (ESTABLISHED)

java 1142 dwls977 925u IPv6 141713891 0t0 TCP localMachine :27710->eth0.remoteMachine.nova.com:54141 (ESTABLISHED)

Incoming Connections
Once you got the Out Going Connections , we can get the Port and try it on the local machine to find the connection information

remoteMachine:root002-~ $ netstat | grep 54426
tcp 0 0 localMachine :54426 eth0.remoteMachine.nova.co:27710 ESTABLISHED
All Outgoing Connections
netstat -an | grep -i tcp | grep ESTABLISHED | less
talk to Other over the Network
Dev:vx1379:djbs002-~ $ lsof -p 29118 -a -i ( Process Talk)
show the number of connections active to a port and also the number of connections from that ip in order
netstat -ntu | awk ‘{print $5}’ | cut -d: -f1 | sort | uniq -c | sort -n
List listening TCP sockets
netstat -ant | egrep -i ‘(LISTEN)’
List Per User Process
ps -e -o uid,vsz | awk ‘{ usage[$1] += $2 } END { for (uid in usage) { print uid, “:”, usage[uid] } }’
Working Directory of a Running process
lsof -bw -d cwd -a -c java
Extract files from war/Ear
jar xf abc.war log4j-test.xml WEB-INF/
All Connections from a Specific process
lsof -p PID -a -i
Scan a port On a Remote Machine
nc -v -w 1 -z
Show The Java Process
top -b -n 1|grep java|wc -l
Smallest To biggest
ls -s | sort -nr | more
Find Files That Exceed a Specified Size Limit
find . -size +400 -print
Grep All Files Of A Certain File Type For A Specific Pattern
find . -type f -name ‘*.cs’ -print0 | xargs -0 grep –color=always -n PATTERN

Zero Length File Sizes
find . -type f -size 0k -exec rm {} \; | awk ‘{ print $8 }’
Find and Kill a Process
ps ux | grep | grep –v grep | awk ‘{print $2}’ | xargs –r kill -9
Files Opened By a Process
lsof +f | grep PID
Find The Command Line Of the Process Using Specific Port
cat /proc/$(lsof -ti:)/cmdline
All Open Tomcat Threads
ps -ALcf | grep org.apache.catalina.startup.Bootstrap | wc -l

Find The MAC Address
[root@vx111a test]# cat /sys/class/net/eth0/address

List all the Installed Perl packages
perl -MFile::Find=find -MFile::Spec::Functions -Tlwe ‘find { wanted => sub { print canonpath $_ if /\.pm\z/ }, no_chdir => 1 }, @INC’
Find Whether a Port is Open On a Remote Machine
nmap -p
Status Of the HTTP
curl -o /dev/null –silent –head –write-out ‘%{http_code}\n’
200
-o /dev/null throws away the usual output
-silent throws away the progress meter
-head makes a HEAD HTTP request, instead of GET
-write-out ‘%{http_code}\n’ prints the required status code
Find Whether The Process is 32Bit or 64Bit
file -L /proc/PID/exe

The Output would be some thing like this
/proc/6462/exe: ELF 32-bit LSB executable, Intel 80386, version 1 (SYSV), for GNU/Linux 2.2.5, dynamically linked (uses shared libs), not stripped
Convert Of Bytes to Mbs
units –terse “3415014314 bytes” “MB”

SSh and Execute a Command
ssh root@ -q ‘echo $MYDIR’
Find out what is listening on a series of ports
/sbin/fuser -n tcp {7000..8000}
View details of network activity between
lsof -i :7000-8000
List all files opened by a particular command
lsof -c java
List Threads By PID along with Thread Start Time
ps -o lwp,lstart –pid PID

Count Threads OF a Process
ps uH -p PID | wc –l

Print a stack trace of a running process
Pstack PID
Return Number of kernel Threads Owned by a process
ps -o thcount –p PID
Show Ports that belong to this PID
netstat –all –program | grep PID

Drop all the Connections available now for a Port
iptables -I INPUT -p tcp -dport 80 -j DROP

Find and Grep a File
find $PWD -type f -exec egrep PAVAN {} \;

Find the Time took Process To Complete
/usr/bin/time -v

Memory Information ( Much Better than Free Command)
vmstat -s -S M
List all the Jars loaded by a Process
lsof -p PID | grep jar

All process Running as a Specific User
pgrep -l -f -x -u root
Find and Remove Files Matching a pattern
find $PWD -type f -name “*Jul-*.ESS-A1.log” -exec rm -f {} \;

Find and Zip files matching a Pattern
find $PWD –type f –name “ess_admin.controllermessages.log.” | xargs tar zcvf one.tar

How to list all unique ip address currently connected to a specific port
ss -o state established ‘( dport = :10012 )’|awk -F”[\t :]+” ‘NR!=1{ ip[$5]+=1 } END{ for (i in ip){n++};print n }’

Find and Gzip
find $PWD –type f –name “*.log” | xargs tar zcvf one.tar

Find and Remove
find –type f –name “*.log” | xargs rm
find –type f –name “*.log” -exec rm -f {} \;

Find Files That are Updated in The Last 60 Minutes
find $PWD -mmin -60

Find all files Older than 2 days and gzip them
find $PWD -type f -mtime +2 | xargs gzip

How many Open Tomcat Threads
ps -ALcf | grep org.apache.catalina.startup.Bootstrap | wc -l

Differences between 2 files in remote hosts
diff <(ssh alice cat /etc/apt/sources.list) <(ssh bob cat /etc/apt/sources.list) Monitor the active thread count of a process (jvm) on linux ps uH -p 10343 | wc -l How do I find out which service is listening on a specific port? lsof -Pnl +M -i4 ( IP 4 ) lsof -Pnl +M -i6 ( IP 6 ) netstat -npl Display CPU,Memory Usages of the Users ps axo user,pcpu,pmem,rss --no-heading | awk '{pCPU[$1]+=$2; pMEM[$1]+=$3; sRSS[$1]+=$4} END {for (user in pCPU) if (pCPU[user]>0 || sRSS[user]>10240) printf “%s:@%.1f%% of total CPU,@%.1f%% of total MEM@(%.2f GiB used)\n”, user, pCPU[user], pMEM[user], sRSS[user]/1024/1024}’ | column -ts@ | sort -rnk2
Kill a Process on the Port
kill -9 `lsof -t -i :port_number`
How Many Established Connection
lsof | grep -c “(ESTABLISHED)”
How to enlarge existing file to specific size
dd if=/dev/zero bs=1 seek=new_filesize count=0 of=your_file
For example this:
dd if=/dev/zero bs=1G seek=1000 count=0 of=test
will enlarge file test to 1000G
Tail the Last Bytes of Files
tail -c 400 jboss.log > jboss.log11
Deleted Files along with File Descriptor(FD)
lsof | awk ‘(/deleted/) {print “FD :-“,$4,”| File Name:-“,$9}’
Check the Files For Changes From the last 1 Hour
awk -vDate=`date -d’now-1 hours’ +[%d/%b/%Y:%H:%M:%S` ‘ { if ($4 > Date) print Date FS $4}’
Threads in a Process
ps -eLo pid,ppid,tid,pcpu,comm | grep PID
Grep Multiple Words
grep -w ‘warning\|error\|critical’ /var/log/messages
Find Out What Partition a File Belongs To
We can use the df command to find out what partition a file belongs,

[root@vx111a perl]# df -T file1
Filesystem Type 1K-blocks Used Available Use% Mounted on
/dev/sda7 ext3 49594196 5499736 41534504 12% /soa
Find Out Port
/sbin/fuser 10011/tcp
10011/tcp: 32506

lsof -i tcp:10012
COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME
java 32506 jbs002 67u IPv6 20552857 0t0 TCP *:10012 (LISTEN)
Thread Ids of a process in Linux using Proc
cat /proc/PID/task

How To Find The Number Of Open Files for a Process Name and process pid sorted by number of open files.?
lsof | perl -lane ‘$x{“$F[0]:$F[1]”}++;END { print “$x{$_}\t$_” for sort {$x{$a}<=>$x{$b}} keys %x}’
To show connections to a specific host
lsof -i@192.168.1.5

Show connections based on the host and the port using @host:port
lsof -i@192.168.1.5:22
lsof -i@eth0.omhq111a.nova.com

Grep All Files Of A Certain File Type For A Specific Pattern
find . -type f -name ‘*.*’ -print0 | xargs -0 grep –color=always -n GCMonitor

Top 20 Process With High File Descriptors
for x in `ps -eF| awk ‘{ print $2 }’`;do echo `ls /proc/$x/fd 2> /dev/null | wc -l` $x `cat /proc/$x/cmdline 2> /dev/null`;done | sort -n -r | head -n 20

Ping a URL to Find the HTTP Status
Dev:Hunter@root-~ $ printf “GET / HTTP/1.0\r\nvx111a: www\r\n\r\n” | nc vx111a 10011 | head
HTTP/1.1 200 OK
Server: Apache-Coyote/1.1
Set-Cookie: JSESSIONID=291DBACCB3596F4FBC38ABFBDE99AA7C.jasB2; Path=/
ETag: W/”7857-1235874240000″
Last-Modified: Sun, 01 Mar 2009 02:24:00 GMT
Content-Type: text/html
Content-Length: 7857
Date: Thu, 10 Oct 2013 02:33:39 GMT
Connection: close

Dev:Hunter@root-~ $ nc -zw2 vx111a 10011 || echo http service is down
Connection to vx111a 10011 port [tcp/*] succeeded!

Dev:Hunter@root-~ $ curl -sL -w “%{http_code}\\n” “http://vx111a:10011/wls_monitor/” -o /dev/null
200

Redirect and Print
Dev:vx111a:jbs002-~ $ jmap -heap 922 2>/dev/null | grep MaxPermSize | awk ‘{print $3}’
268435456

The 2>/dev/null at the end of the find command tells your shell to redirect the error messages (FD #2) to /dev/null, so you don’t have to see them on screen. Use /dev/null to to send any unwanted output from program/command. All data written on a /dev/null special file is discarded by the system. To redirect standard error to /dev/null and store file list to output.txt, type:

Find Who is Using Port
Dev:vx111a:djbs002-~ $ /sbin/fuser 10011/tcp
10011/tcp: 32506

Dev:vx111a:djbs002-~ $ lsof -i tcp:10012
COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME
java 32506 djbs002 67u IPv6 20552857 0t0 TCP *:10012 (LISTEN)

Search For Out Of memory
find . -type f -exec grep -l java.lang.OutOfMemoryError {} \;
./MANDY-B1_gc.log
./heap.log
./MANDY -B1.log.yyyyMMdd_HHmmss

Conenct to the Linux Machine From windows Machine to Download Files
pscp -i C:\Ateam_uberkey.ppk jbs002@vx111a:/tmp/top.log C:\Users\Jag\Desktop\temp\top.log

Note : pscp is available with putty Software which is free to download

Obtain the Number of Thread States in a Thread Dump
dev:vx1abc:he002:nc-Dumps $ awk ‘/State: / { print }’ < td.log.073716.013908855 | sort | uniq -c 10 java.lang.Thread.State: RUNNABLE 8 java.lang.Thread.State: TIMED_WAITING (on object monitor) 2 java.lang.Thread.State: TIMED_WAITING (sleeping) 2 java.lang.Thread.State: WAITING (on object monitor) 24 java.lang.Thread.State: WAITING (parking) Obtain the Count of Threads based on Thread State dev:vx1cea:djhe002:nc-stackDetils $ awk '/State: TIMED_WAITING/ { getline; print }' < td.2013-10-17-03.log | sort | uniq -c 50 at java.lang.Object.wait(Native Method) 15 at java.lang.Thread.sleep(Native Method) 5 at sun.misc.Unsafe.park(Native Method) Grep Multiple Strings grep 'RUNNABLE\|ListenPort\|port\|clusters\|broadcastchannel\|multicastaddress\|multicastport\|server_cluster' td.log.073652.957462762 Number of Connection Hits in between Dev:vx1322:jbs002-JAS-A2 $ egrep "2013-08-09 16:47:12|2013-08-09 16:50:00" jboss.log | wc -l 3 How many Requests Happened Per Minutes egrep "17/Aug/2013:01|17/Aug/2013:02" PHYRES-H1_access.log | cut -d[ -f2 | cut -d] -f1 | awk -F: '{print $2":"$3}' | sort -nk1 -nk2 | uniq -c | sed 's/[ ]*//' Query packages dev:vx1abc:he002:nc-~ $ rpm -q --queryformat '\n%{NAME} %{VERSION} %{RELEASE} %{ARCH}\n' glibc glibc 2.12 1.80.el6_3.6 x86_64 glibc 2.12 1.80.el6_3.6 i686 Processor and Memory Usage Per User ps axo user,pcpu,pmem,rss --no-heading | awk '{pCPU[$1]+=$2; pMEM[$1]+=$3; sRSS[$1]+=$4} END {for (user in pCPU) if (pCPU[user]>0 || sRSS[user]>10240) printf “%s:@%.1f%% of total CPU,@%.1f%% of total MEM@(%.2f GiB used)\n”, user, pCPU[user], pMEM[user], sRSS[user]/1024/1024}’ | column -ts@ | sort -rnk2

shell to get the process usage in MB

#!/bin/bash
ps -A -o pid,rss,command | grep nginx | grep -v grep | awk ‘{total+=$2}END{printf(“nginx=%dMb\n”, total/1024)}’
ps -A -o pid,rss,command | grep php-fpm | grep -v grep | awk ‘{total+=$2}END{printf(“php-fpm=%dMb\n”, total/1024)}’
ps -A -o pid,rss,command | grep mysqld | grep -v grep | awk ‘{total+=$2}END{printf(“mysql=%dMb\n”, total/1024)}’
ps -A -o pid,rss,command | grep transmission-da | grep -v grep | awk ‘{total+=$2}END{printf(“transmission=%dMb\n”, total/1024)}’
ps -A -o pid,rss,command | grep fail2ban | grep -v grep | awk ‘{total+=$2}END{printf(“fail2ban=%dMb\n”, total/1024)}’
ps -A -o pid,rss,command | grep sshd | grep -v grep | awk ‘{total+=$2}END{printf(“sshd=%dMb\n”, total/1024)}’

TOP 12 ‘PS’ PERFORMANCE COMMANDS

TOP 12 ‘PS’ PERFORMANCE COMMANDS

admin@UM 02:03 AIX, Unix
I use following ps commands in order to check for performance probelms:
1) Displaying top CPU_consuming processes:

# ps aux|head -1; ps aux|sort -rn +2|head -10
2) Displaying top 10 memory-consuming processes:

# ps aux|head -1; ps aux|sort -rn +3|head
3) Displaying process in order of being penalized:

# ps -eakl|head -1; ps -eakl|sort -rn +5
4) Displaying process in order of priority:

# ps -eakl|sort -n +6|head
5) Displaying process in order of nice value

# ps -eakl|sort -n +7
6) Displaying the process in order of time

# ps vx|head -1;ps vx|grep -v PID|sort -rn +3|head -10
7) Displaying the process in order of real memory use

# ps vx|head -1; ps vx|grep -v PID|sort -rn +6|head -10
8) Displaying the process in order of I/O

# ps vx|head -1; ps vx|grep -v PID|sort -rn +4|head -10
9) Displaying WLM classes

# ps -a -o pid, user, class, pcpu, pmem, args
10) Determining process ID of wait processes:

# ps vg|head -1; ps vg|grep -w wait
11) Wait process bound to CPU

# ps -mo THREAD -p
12) CPU usage with priority levels

# topas -P

LINUX MEMORY

Find Memory Usage

System memory used and free

Total Used and Free Memory in MBytes (in that order)

free -m|grep “buffers/cache”|cut -d”:” -f2
Memory by Process

Raw

ps -e -orss=,args= | sort -b -k1,1n | pr -TW$COLUMNS
Human readable

ps -e -orss=,args= | sort -b -k1,1n | awk ‘{ split( “KB MB GB” , v ); s=1; while( $1>1024 ){ $1/=1024; s++ } print int($1) ” ” v[s] ” ” $2 }’
Memory by Process – Grouped together

Raw

ps -e -orss=,args= | awk ‘{arr[$2]+=$1} END {for (i in arr) {print arr[i],i}}’ | sort -b -k1,1n
Human readable

ps -e -orss=,args= | awk ‘{arr[$2]+=$1} END {for (i in arr) {print arr[i],i}}’ | sort -b -k1,1n | awk ‘{ split( “KB MB GB” , v ); s=1; while( $1>1024 ){ $1/=1024; s++ } print int($1) ” ” v[s] ” ” $2 }’
Total RSS Memory

ps -e -orss= | awk ‘{ sum += $1 } END { print sum }’
Human redable

ps -e -orss= | awk ‘{ sum += $1 } END { print sum }’ | awk ‘{ split( “KB MB GB” , v ); s=1; while( $1>1024 ){ $1/=1024; s++ } print int($1) ” ” v[s] ” ” $2 }’
Total Memory

smem -w -t -k

JMAP, HISTO, Thread Dump, CPU Utilization

Dear Reader,

In a production environment Java Profiling is not an option, we have seen multiple times that
our CPU has reached almost 100% or even 300% sometime. That is really a panic scenario especially
when you are handling production environment or at client place to check what went wrong.

Fortunately, Java comes with some great debugging tools, co-operating those tools with Linux
built-in tools will help you to know what is happening.

I am going to explain below items here:
1) An introduction about Java threads and its relation to Linux LWP (Light Weight Process).
2) Step-by-step process to take thread dump and analyze CPU utilization.
3) “jmap” – Memory Map (dump), Command to get this.
4) “jmap” – Histo, Command to get this.
5) Command to see list of open files in Unix.

1) Introduction: Any java program starts when the JVM calls the main method, this creates a thread
called the main thread and any thread you create using java code will be derived from the main
thread. The same exact behavior occurs on the Linux level, the main thread for java means a Process
for the OS and every thread you create using java the OS will create a Light-weight-process
or LWP. In short: Java main thread = Linux process and Java supporting threads = Linux LWP.

The idea here:
Ask Linux which LWP is eating the CPU.
Ask Java for a Thread Dump.
Map this LWP to a Java thread.
Get the part of code causing the issue.

2) Step-by-step process:
Get the PID: the very first step is to know what is the Java process ID, we will use Linux commands
as below. Use either of the below commands (we use our grep “DAPPNAME”, you can use anything):
jps -v | cut -c -106 | grep DAPPNAME
jps -mvl | cut -c -106 | grep DAPPNAME
ps -eaf | cut -c -106 | grep DAPPNAME
ps -ef | cut -c -106 | grep DAPPNAME
ps -eaf | grep java

Below are the sample output when you execute the command:
dmodi@MyDirectory:~$ jps -mlv | cut -c -106 | grep DAPPNAME
8243 org.quickserver.net.server.QuickServer -load config/DmodiServer.xml -DAPPNAME=CLIENT
13712 org.quickserver.net.server.QuickServer -load ./conf/DmodiDNXServer.xml -DAPPNAME=SERVER
12229 org.quickserver.net.server.QuickServer -load ./config/DmodiPOSServer.xml -DAPPNAME=SERVER2

Explanation: “jps” – Java Virtual Machine Process Status Tool, a command in Unix. “106” shows 106
characters we want to display in console.

The next step is to get the CPU usage per each LWP related to the main process, we can use below commands:
ps -eLo pid,lwp,nlwp,ruser,pcpu,stime,etime,args | grep PROCESS_ID | cut -c -106 > threadsList.txt

The newly created file threadsList.txt will contain below things in similar way (The headers will not be
shown as below):
PID LWP NLWP RUSER %CPU STIME ELAPSED COMMAND
8243 8243 3 dmodi 0.0 May13 1-19:20:18 java -Dprogram.name=run.sh -Xms64m -Xmx100m -Dsun.rmi.dgc
8243 8244 3 dmodi 0.0 May13 1-19:20:18 java -Dprogram.name=run.sh -Xms64m -Xmx100m -Dsun.rmi.dgc
8243 8245 3 dmodi 99.9 May13 1-19:20:18 java -Dprogram.name=run.sh -Xms64m -Xmx100m -Dsun.rmi.dgc

To see headers too, just execute the below command:
ps -eLo pid,lwp,nlwp,ruser,pcpu,stime,etime,args > threadsList.txt

Explanation: PID is process Id.
LWP: is Light weight processes Lists for the above PID. These values are in Decimal.
NLWP: is number of LWP created for the above PID.
Rest other headers don’t require any explanation.
We can see LWP – 8245 is eating CPU. We need to convert this value into HEX value which will be “2035”.

Now take the thread dump and kill the process Id: 8243. Open the thread dump file and search value “2035”.
See below command:
//Taking thread dump
jstack -l 8243 > ThreadDump_15_May_2014_13_PM.txt

//Killing process
kill -9 8243

3) “jmap” – Memory Map (dump): Prints shared object memory maps or heap memory details of a given JVM process.
dmodiUnixUser@productName79:~$ jmap -dump:file=deepak.bin 8243
Dumping heap to /home/dmodiUnixUser/deepak.bin …
Heap dump file created
dmodiUnixUser@productName79:~$ ls
deepak.bin
This newly created file will be big in size (of 5-10 MB around). You can’t see this content using
“less” or “cat” command. You need tool to see this. We don’t use this generally, so not mentioning here.

4) “jmap” – Histo: See below command:
dmodiUnixUser@productName79:~$ jmap -histo:live 8243 > deepak.txt
Contents of this file “deepak.txt” will have similar like above:

num #instances #bytes class name
———————————————-
1: 14452 2229096
2: 14452 1740720
3: 1004 1406296
4: 1336 1270504 [B
5: 25057 1060840
6: 835 809368
7: 1004 787096

5) List of open files in Linux:
lsof – list open files
dmodiUnixUser@productName79:~$ lsof | grep home/dmodi/productName/dist/
COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME
java 16460 dmodiUnixUser mem REG 9,2 25680 8127062 home/dmodi/productName/dist/sample1.jar
java 16460 dmodiUnixUser mem REG 9,2 66770 8127061 home/dmodi/productName/dist/sample2.jar

dmodiUnixUser@productName79:~$ lsof | grep PROCESS_ID > help.txt
dmodiUnixUser@productName79:~$ less help.txt
———————————-END—————————————–