Python SocketServer

这几天在搞2台服务器同步文件的问题,由于公司文件传送限制用户权限,导致写好的传送脚本scp.exp用apache用户无法执行脚本同步。所以另外想办法,参照相关文档用python写了一个SocketServer,在后台跑然后接受php的命令去执行脚本($ nohup python server.py > nohup.out &或者$ python server.py &,然后#exit,再ssh登陆,查看后台进程#ps -ef | grep py,能查到server.py的进程就OK了。)
server端:server.py

import os
import SocketServer
class MyHandler(SocketServer.BaseRequestHandler):
    def handle(self):
        while 1:
            dataReceived = self.request.recv(1024)
            if not dataReceived: break
            #self.request.send(dataReceived)
            #print dataReceived
            if dataReceived == 'cmd=1':
                os.system('/home/cgi/scp.exp')
                self.request.send(dataReceived+'&result=1\n')
            else:
                self.request.send(dataReceived+'&result=0\n')
myServer = SocketServer.ThreadingTCPServer(('localhost',6000), MyHandler)
myServer.serve_forever()

client端:client.py

import socket
remote_host = '127.0.0.1'
remote_port = 6000
send_buf = raw_input()
#send_buf = open('test.txt', 'rb').read()
#send_buf = send_buf.replace('\x0D\x0A', '')
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((remote_host, remote_port))
sock.send(send_buf)
response_data = sock.recv(1024)
print response_data
sock.close()

或者用PHP写client端:client.php

$fp = fsockopen("127.0.0.1", 6000, $errno, $errstr, 30);
if (!$fp) {
    echo "$errstr ($errno)<br />\n";exit;
} else {
    $out = "cmd=1";
    fwrite($fp, $out);
    while (!feof($fp)) {
        $str .= fgets($fp, 4096);
    if(strpos($str, "\n") !== FALSE){
        if(strpos($str, "&result=1") != FALSE){
            break;
        }else{
    }
    }
}
fclose($fp);

发表评论