套接字的简单程序
Posted 少年乘风
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了套接字的简单程序相关的知识,希望对你有一定的参考价值。
模拟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()
以上是关于套接字的简单程序的主要内容,如果未能解决你的问题,请参考以下文章