Friday, April 25, 2008

ksh scripting tips

1. How do create a script that waits on another process for a specified time and
then kills it ?

wait_until.sh example contents
------------------------------------------------------------------------
#!/bin/ksh
IF=eth0
tcpdump -vntXi $IF -s0 not tcp and not udp and not arp and not icmp > /tmp/cfg/tcpdump.$IF 2>&1 &
sleep 120
kill -9 $(jobs -p) # or kill -9 %1
-----------------------------------------------------------------------

2. How do you wait indefinitely till the script completes ?

wait_indefinitely.sh example contents

------------------------------------------------------------------------
#!/bin/ksh
IF=eth0
tcpdump -vntXi $IF -s0 not tcp and not udp and not arp and not icmp > /tmp/cfg/tcpdump.$IF 2>&1 &
wait
-----------------------------------------------------------------------

3. How do you make sure that there are only N background jobs ?

will update this in a bit ....

Ok, the following is not KSH but an expect script that does the following:
ssh's to a box and runs tcpdump. If the tcpdump output falls idle for 2 minutes it
logs out

#!/usr/bin/expect

set timeout 1
proc myE { value { tm 9}} {
global timeout
set timeout $tm
expect {
"\n" {
send "$value\r"
}
timeout {
puts "timed out\r"
}
}
}
proc myE2 { value { tm 120}} {
global timeout
set timeout $tm
set ctr 0
send "$value\r"
expect {
"\n" {
incr ctr 1
after 250
exp_continue }
eof { puts "eof\n" }
timeout {
send "\003\r"
send "sleep 10\r"
send "exit\r"
send "exit\r"
}
}
}
spawn ssh aloha
myE "sudo su -"
myE2 "tcpdump -Xv -s0 -i any port 53" 5
interact

No comments: