`

一个Bash Shell 实现的局域网即时通信工具 ^_^

阅读更多

今天有点无聊,打通ssh的时候遇到了问题,搞了半天才搞定。

在搞的过程中发现,在两台经过ssh打通的机器很容易将消息发送到彼此。

进而想想,如果收到消息的机器能够即时将内容显示出来,那不就是一个山寨版的即时聊天工具嘛,哈哈。

 

于是我的恶搞开始了。。。

 

基本思路如下:

 

1. 最核心的其实就是使用ssh执行远程命令,将内容写到远程计算机的文件中。

2. 消息接受机器监控某个消息文件,一旦发现有消息到大,就取出来,并将其写到标准输出,让用户知道。

3. 同时接受消息的机器可以接受用户的输入,并将其发送到另一台机器。

---消息接收器的守护进程需要在后台run,接受用户输入,并发送的进程在前台run。

 

思路确定后就是实施了,我们需要:

 

1. 一个总的程序入口,我们叫它“process.sh”。负责启动消息接收进程和接收用户输入并调用发送逻辑,将数据发送。

2. 一个消息接收器,我们叫它“receive.sh”。负责接收消息,并将告诉用户这条消息是别人发送过来的。

3. 一个消息发送器,我们叫它“send.sh”。负责将用户输入的消息,发送到指定的机器上去。

4. 一个消息接收文件,这个文件存放每次会话中所有接收到的消息。

 

结构如下:

 

 

-rw-rw-r-- 1 admin admin  12 Nov 22 16:19 msg

-rwxrwxr-x 1 admin admin 442 Nov 22 16:09 process.sh

-rwxrwxr-x 1 admin admin  56 Nov 11 23:02 receive.sh

-rwxrwxr-x 1 admin admin  75 Nov 22 12:57 send.sh

 

代码如下:

process.sh:

 

#!/bin/bash
clean(){
        for pid in `ps aux | grep 'tail -f msg' | grep -v 'grep' | awk '{print $2}'`
        do
                kill -9 $pid >/dev/null 2>&1
        done

        for pid in `ps aux | grep  'bin/bash ./receive.sh'  | grep -v 'grep' | awk '{print $2}'`
        do
                kill -9 $pid >/dev/null 2>&1
        done
}

stop(){
        clean
        exit 0;
}

clean
>msg

tail -f msg | ./receive.sh &

while read line
do
        if [ "$line" = "exit" ]; then
                stop
        fi
        ./send.sh "$line" 10.20.151.97
done

 

receive.sh

 

#!/bin/bash
while read msg
do
echo "receive: "$msg
done

 

send.sh

 

 

#!/bin/bash
msg=$1
ssh admin@$2 "echo $msg >> /home/admin/msgserver/msg"

 

代码行数一共只有38行。

 

我们将这四个文件都放到/home/admin/msgserver里面,并且保证两台机器上的路径设置都一样。

 

然后两台机器分别运行process.sh文件:./process.sh

效果如下:

 

我们首先发送一条消息:"hello i am xiaoqiang"。如图1

另一台机器马上收到一条消息:“receive: hello i am xiaoqiang”。 如图2

收到消息后马上回一个消息:“hello, i am guagua,haha”。如图2

第一台机器又马上收到一条消息:“receive: hello, i am guagua,haha”。如图1

 

然后如果要退出,输入"exit"即可。

 

当然这个东西是不能用的,也没有人2B到用这个哈。做这个就权当练习shell和ssh用法了。

 

 

附:

 

图1:

 

图2:

  • 大小: 9.2 KB
  • 大小: 9.9 KB
1
0
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics