python之网络编程

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u011244839/article/details/79975930

用python写了一个简单的socket编程demo,记录一下。主要实现在客户端发送linux指令,在服务器端执行后返回执行结果,代码比较简单,所以就不多加赘述了。

服务端:

#!/usr/bin/python
# -*- coding: UTF-8 -*-

import socket, os

HOST = ''
port = 8888
buf_size = 1024

server_s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
server_s.bind((HOST, port))
server_s.listen(5)

def exeCmd(cmd):
    p = os.popen(cmd)
    result = p.read()
    code = p.close()
    return result, code

while True:
    print('等待连接。。。')
    listen_s, addr = server_s.accept()
    print('连接IP:', addr)
    while True:
        cmd = listen_s.recv(buf_size)
        if not cmd:
            break
        result,Code = exeCmd(cmd)
        if not Code:
            slisten_s.send(result.encode())
        else:
            listen_s.send('error!!!')
    listen_s.close()
server_s.close()

客户端:

#!/usr/bin/python
# -*- coding: UTF-8 -*-

import socket

HOST = '192.168.13.2'
port = 8888
buf_size = 1024

client_s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
client_s.connect((HOST,port))
print('连接成功!')
while True:
    cmd = input('输入指令:')
    if not cmd:
        break
    client_s.send(cmd.encode())
    result = client_s.recv(buf_size).decode()
    print("执行结果:", result)
client_s.close()

阅读更多
想对作者说点什么?

博主推荐

换一批

没有更多推荐了,返回首页