Linux shell script implements TCP/UPD protocol communication (redirect application) _linux Shell

Source: Internet
Author: User
Tags sendmsg

A few days ago, there were some interesting examples of redirects and piping-related usage. Software communication based on TCP/UDP protocol is implemented through redirection.

There is a special file in the Linux device:

/dev/[tcp|upd]/host/port just read or write to this file, the system will try to connect: host this machine, corresponding port port. If the host and port exist, a socket connection is established. There will be a corresponding file appearing under the/PROC/SELF/FD directory.

First, test under:/dev/tcp/host/post file

[chengmo@centos5  shell]$ cat</dev/tcp/127.0.0.1/22 ssh-2.0-openssh_5.1 #我的机器shell端口是 #实际:/dev/ TCP does not have this directory at all, it belongs to a special device [chengmo@centos5  shell]$ cat</dev/tcp/127.0.0.1/223-bash:connect: Deny connection-bash:/dev/tcp /127.0.0.1/223: Reject Connection #223接口不存在, open failed   [chengmo@centos5  shell]$ exec 8&LT;&GT;/DEV/TCP/127.0.0.1/22 [ chengmo@centos5  shell]$ ls-l/proc/self/fd/Total 0 lrwx------1 Chengmo Chengmo 0 10-21 23:05->/dev/pts/0 LRW 
x------1 Chengmo Chengmo 10-21 23:05 1->/dev/pts/0 lrwx------1 Chengmo Chengmo 10-21 23:05 2->/dev/pts/0 Lr-x------1 Chengmo Chengmo 10-21 23:05 3->/proc/22185/fd lrwx------1 Chengmo Chengmo 10-21 23:05 8-> so CKET:[15067661]   #文件描述符8, has opened a socket communication channel, this is a can read and write socket channel, because with: "<>" open [chengmo@centos5  shell]$ EXEC 8>&-#关闭通道 [chengmo@centos5  shell]$ ls-l/proc/self/fd/Total 0 lrwx------1 Chengmo Chengmo 64 10-21 23:0 8 0->/dev/pts/0 lrwx------1 Chengmo Chengmo 64 10-21 23:1->/dev/pts/0 lrwx------1 Chengmo Chengmo 2 10-21 23:08->/dev/pts/0 lr-x------1 Chengmo Chengmo 64 10-21 23:08 3->/proc/22234/fd

Read time from time server:

[Chengmo@centos5 html]$ CAT</DEV/TCP/TIME-B.NIST.GOV/13

55491 10-10-22 11:33:49 0 0 596.3 UTC (NIST) *

The above statement uses the redirected input statement.

Second, read Remote Web server header information through redirection

#!/bin/sh 
#testhttphead. Sh
#实现通过主机名, the port reads the header information for the Web server
#copyright chengmo,qq:8292669
if ($    #<2)); then
echo "usage:$0 host port";
Exit 1;
Fi
#如果参数缺失, exit program, return to status 1
exec 6<>/dev/tcp/$1/$2 2>/dev/null;
#打开host的port a read-write socket connection, which is connected to the file descriptor 6
if ($?!    =0)); then
echo "open $ error!";
Exit 1;
Fi
#如果打开失败, $? Return is not 0, terminate program
echo-e "head/http/1.1\n\n\n\n\n" >&6; 
#将HEAD information, send to socket connection
cat<&6; 
#从socket读取返回信息, display as standard output
exec 6<&-;
EXEC 6>&-; 
#关闭socket的输入, output
exit 0;

After the script is established: Save as Testhttphead.sh

Run Result:

[chengmo@centos5 ~/shell]$ sh testhttphead.sh www.baidu.com http/1.1
OK
date:thu, Oct 15:17:23 GMT
server:bws/1.0
content-length:6218
content-type:text/html;charset=gb2312
cache-control:private
Expires:thu, Oct 15:17:23 GMT
set-cookie:baiduid=1c40b2f8c676180fd887379a6e286dc1:fg=1 expires=thu, 21-Oct-40 15:17:23 GMT; path=/; domain=.baidu.com
p3p:cp= "OTI DSP COR IVA IND com"
connection:keep-alive
[chengmo@centos5 ~/s hell]$ sh testhttphead.sh 127.0.0.1 8080
open 127.0.0.1 8080 error!

Suddenly there was a strange idea:
We can achieve TCP/UPD protocol communication by Telnet in the Windows age, so how do you implement it with the traditional method?

[Chengmo@centos5 ~/shell]$ echo-e "head/http/1.1\n\n\n\n\n" |telnet www.baidu.com 
-Trying ...
Connected to www.baidu.com.
Escape character is ' ^] '.
Connection closed by foreign host.
#直接给发送, Failure
[Chengmo@centos5 ~/shell]$ (telnet www.baidu.com) <<eof
head/http/1.1
EOF
trying 220.181.6.175 ... Connected to
www.baidu.com.
Escape character is ' ^] '.
Connection closed by foreign host.
#重定向输入, or failure?

Find the right way:

[Chengmo@centos5 shell]$ (echo-e "head/http/1.1\n\n\n\n\n"; sleep 2) |telnet www.baidu.com 
220.181.6.175 ... Connected to
www.baidu.com.
Escape character is ' ^] '.
http/1.1 OK
Date:thu, Oct 15:51:58 GMT
server:bws/1.0
content-length:6218
content-type:te xt/html;charset=gb2312
cache-control:private
expires:thu, Oct 15:51:58 GMT
set-cookie:baiduid =0b6a01acecd5353e4247e088a8cb345a:fg=1; Expires=thu, 21-oct-40 15:51:58 GMT; path=/; domain=.baidu.com
p3p:cp= "OTI DSP COR IVA IND com"
connection:keep-alive
#成功了! Join sleep actually can, sleep change to 1 seconds can also

Is it due to sleep, Echo will launch 2 seconds to send the channel: Telnet? Inferences can be overturned from these 2 aspects:

One aspect: the data enclosed by () is a pair of commands that are executed as a child command and executed together to finish the program. Each command echo statement, sent directly to the screen (that is, standard output), as long as the standard output, will pass through the channel immediately: Telnet, if the next command and output, will pay attention to telnet, until () all the commands executed, and the channel connection is disconnected.

One more thing: if it's a delayed delivery, when there's data coming up to telnet and when the Telnet command starts. Would you like to postpone it or send it earlier? It does not matter.

This type of command to see sleep, in fact, is to keep the channel connected to Telnet for 2 seconds. The channel is connected and the Telnet terminal input is still in, so you can keep the data from the Baidu server.

So, how long is the delay, or with the server processing speed is related.

It's a good way to use sleep if you send data to Telnet via ECHO to keep the channel Unicom.

By redirecting to Telnet to enter parameters this way, I can't think of how to implement deferred input. If you know a friend, you can advise.

Difference:

Telnet and echo HTTP access, and by opening the read and write socket is not the same, open the socket channel, can be exchanged processing. Incoming commands, activity results, and incoming commands, and then get results. Telnet through echo cannot be handled this way.

Third, through the shell script redirects realizes the monitoring memcache state

Instance:

#!/bin/sh   #通过传入ip and ports, send instructions to obtain return data #copyright Chengmo qq:8292669   #函数往往放到最上面 function sendmsg () { &nbsp
;  msg=$1;
    echo  "$" >&8;
    getout; #向socket通道发送指令, and the call gets the return parameter   function getout () {        #read command-u reads data from open file Descriptor 8,-D 
Read data ignored: \ R line break     while read-u 8-d $ ' \ R ' name;     do          if ["${name}" = "End"  -O "${
name} ' = = ' ERROR '];then             break;
        fi;
        echo $name;     done} #由于: Memcached each time the communication completes, will return: End or error (error), by judging whether it is "ends" feel that read is not over, otherwise the loop will not stop   if [$#-
Lt 2];then     echo "usage:$0 host Port [command]";
    exit 1;
Fi   [[$#-GT 2]]&&command=$3;
  #设置默认值 If command is defined: Stats command= "${command=stats}";
Host= "$";
Port= "$";
      EXEC 8<>/dev/tcp/${host}/${port};
#打开通向通道是8   If ["$?"!= "0"];then     echo "open $host   $port fail!";
    exit 1;
Fi   sendmsg "$command";
#发送指定命令     sendmsg "quit";
#发送退出通向命令     EXEC 8<&-;
EXEC 8>&-; #关闭socket通道   Exit 0;

This is done by redirecting, implementing socket communication, sending and then getting the return example. In fact, the above code seems to only send a paragraph at a time. Time. We can repeatedly call: sendmsg, capturing output data. To achieve continuous, read and write operations.

Instance screenshot:

Other implementation methods:

In fact, through: Telnet can also be achieved.

[Chengmo@centos5 shell]$ (echo "stats"; sleep 2) |telnet 127.0.0.1 11211

Implemented through NC commands:

[Chengmo@centos5 shell]$ (echo "stats") |nc 127.0.0.1 11211

No delay required, open channel directly

In the second program, you see that the shell can handle the interactive design completely. If this is the case, landing ftp,pop3,stmp can be similar to implementation. These, we do through shell socket Similar program implementation, should not be difficult, just to capture the problem such as send parsing.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.