骑着蜗牛追火车

导航

 

环境--->本机测试

[Server]:

[root@centos6 day4]# vim server.py   

import socket
import os

HOST = ''
#Symbolic name meaning all avaliable interfaces

PORT = 50007
#Arbitrary non-privileged port

ADDR = (HOST,PORT)

s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.bind(ADDR)
s.listen(1)   #backlog=1


while 1:
        #不间断响应建立socket连接.
        conn,addr = s.accept()
        print 'Connected by',addr
        while True:
                data = conn.recv(1024)
                print data
                cmd_result = os.popen(data).read()   #执行客户端cmd

                if not data:break
                conn.sendall(cmd_result)
conn.close()

***************************

[Client]:

[root@centos6 day4]# cat client.py
#!/usr/bin/env python
# _*_ coding: UTF-8 _*_

import socket

#echo client program
HOST = '172.20.13.141'   #HOST='localhost'
PORT = 50007
#the same port as used by the server

ADDR = (HOST,PORT)
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.connect(ADDR)

while 1:
        try:
                user_input = raw_input('\033[33;1minput a command:\033[0m')
        except KeyboardInterrupt:
                print 'You interrupt connection by yourself..!'
                continue
        else:
                s.sendall(user_input)
                data = s.recv(1024).split('\n')

                print '\033[31;1mCommand excution result:\033[0m'
                for line in data:print line
s.close()
#print 'Received',repr(data)

 

附:python --> os.popen()方法

python调用Shell脚本,有两种方法:os.system()和os.popen(),前者返回值是脚本的退出状态码,后者的返回值是脚本执行过程中的输出内容。

(1)os.system(command):该方法在调用完shell脚本后,返回一个16位的二进制数,低位为杀死所调用脚本的信号号码,高位为脚本的退出状态码。

(2)os.popen(command):这种调用方式是通过管道的方式来实现,函数返回一个file对象,里面的内容是脚本输出的内容(可简单理解为echo输出的内容)。

(3)os.popen.read()

 

  确切的说:os.popen()可以实现一个“管道”,从这个命令获取的值可以继续被使用。因为它返回一个文件对象,可以对这个文件对象进行相关的操作。

但是如果要直接看到运行结果的话,那就应该使用os.system,用了以后,立竿见影!

 

看这里---->参考链接:http://blog.csdn.net/sxingming/article/details/52071514

 

posted on 2017-10-25 17:33  骑着蜗牛追火车  阅读(275)  评论(0编辑  收藏  举报