码迷,mamicode.com
首页 > 其他好文 > 详细

套接字的简单程序

时间:2017-08-22 10:48:27      阅读:116      评论:0      收藏:0      [点我收藏+]

标签:pipe   one   try   art   strip()   put   int   soc   open   

模拟ssh的远程操控:

服务端:

import socket
import subprocess

phone = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
phone.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
phone.bind((127.0.0.1, 8081))
phone.listen(5)

print(starting----------------)
while 1:
    conn,cilent_addr = phone.accept()
    print(conn, cilent_addr)

    while 1:
        try:
            ret = conn.recv(1024)
            if not ret:break
            res = subprocess.Popen(ret.decode(utf_8), shell=True,
                                   stdout=subprocess.PIPE,
                                   stderr=subprocess.PIPE)
            stdout = res.stdout.read()
            stderr = res.stderr.read()
            conn.send(stdout + stderr)
        except Exception:break
    conn.close()
phone.close()

客户端:

import socket
phone = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
phone.connect((127.0.0.1, 8081))


while 1:
    cmd = input(>>>: ).strip()
    if not cmd: continue
    phone.send(cmd.encode(utf_8))
    cet = phone.recv(1024)
    print(cet.decode(gbk))

phone.close()

 

套接字的简单程序

标签:pipe   one   try   art   strip()   put   int   soc   open   

原文地址:http://www.cnblogs.com/niehaidong111/p/7409787.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!