今天有点无聊,打通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:
相关推荐
一个Bash Shell 实现的局域网即时通信工具 ^_^.docx
Linux_bash_shell_cheat_sheetV2_2.pdf.pdf 对linux环境下编写shell脚本有很好的指导作用
Bash_reference_manual_2014_bashshell_源码.zip
主要是一份bash shell 4.2 的源码,共享给大家
bash shell高级编程
learning_the_bash_shell
Bash Shell 管理Linux
bash shell
bash_shell笔记_1_脚本基础知识
学习Bash Shell的经典教材,推荐
Bash shell编程参考手册,Linux编程必备。
Bash Shell 编程高级教程 (中文版)
Learning the bash Shell, 3rd Edition This refreshed edition serves as the most valuable guide yet to the bash shell. It's full of practical examples of shell commands and programs guaranteed to ...
Bash reference manual by bryan fox
linux shell教程,很不错,强烈推荐
实验十二 Bash Shell相关指令练习
本程序为本人练习bash script所编写。主要实现的功能如下: 1.按学号查询学生成绩信息 2.添加学生成绩信息 3.删除学生成绩信息 4.修改学生成绩信息 5.使用函数分别判断输入的姓名、学号、成绩是否符合要求 6.对...
learn bash shell~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
《Learning the bash Shell,3rd Edition,by Cameron Newham》, bash 的权威指南,本书中文版本下载地址:http://download.csdn.net/source/2244004。内容预览: Chapter 1. bash Basics Chapter 2. Command-Line ...