python远程调用脚本(二)

Socket方式调用远程脚本这里只贴一下代码,代码只是简单实现这个功能,并没有考虑异常处理情况,因为这两个方案(rpyc与socket),需要再次讨论确定后,再完善。

Server端:

import os,sys
import socket
 
def nserver():
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock.bind(("xxxx.xxxx.xxxx.xxxx", 11111))
        sock.listen(5)
        while True:
                  try:
                     conn, addr = sock.accept()
                     ret = conn.recv(1024)
                     print ret
                     result = os.system(ret)
                     conn.send(str(result))
                  except KeyboardInterrupt:
                     print "exit"
                     sys.exit(0)
        sock.close()
if __name__ == '__main__':
        nserver()

client端:

#!/usr/bin/env python
import os,sys
import socket
def send_command(command):
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock.connect(("xxxx.xxxx.xxxx.xxxx", 11111))
        sock.send(command)
        result = sock.recv(1024)
        sock.close()
        return result
if __name__ == '__main__':
   cmd=sys.argv[1]
   ifsuccess = send_command(cmd)
   if (ifsuccess == "0"):
      print "command is successful!"

client端分别执行:

$python client.py "/home/luoxuan/iamshell.sh"
command is successful!
 
$python client.py "/home/luoxuan/iamperl.pl"
command is successful!
 
$python client.py "/home/luoxuan/iampython.py"
command is successful!

服务端打印结果:

/home/luoxuan/iamshell.sh
I am shell
/home/luoxuan/iamperl.pl
I am perl/home/luoxuan/iampython.py
I am python

注意:相同的代码,perl执行时,少了换行符


Post a Comment