简单socket编程

server端:

import socket

# 实例化一个对象
s = socket.socket()

# 绑定一个ip和端口
s.bind(("ip地址|主机名", 端口号)) #或使用socket.gethostname()得到主机名

# 时刻监听
s.listen(5)
print "server start ......"
while 1:
    c, addr = s.accept()  #返回(client,address)

    # 发送数据
    c.send('Hello client')

    # 接收数据
    data = c.recv(1024)
    print data

    # 断开连接
    c.close()

if __name__ == "__main__":
    pass

这里写图片描述

client端:

import socket
client = socket.socket()

client.connect(('ip地址',端口号))
data = client.recv(1024)
print data
client.send("hello server")
client.close()


if __name__ == "__main__":
    pass

这里写图片描述
实现简单的ssh:
server端:

import socket,os

s=socket.socket()
s.bind(("172.25.254.13",8888))
s.listen(5)
print "server starting...."

while 1:
    conn,addr=s.accept()
    print "new conn:",addr
    while 1:
        data=conn.recv(1024) 
        if not data:
            print "the client has been disconnected"
            break
        print "exexute instruction:",data
        cmd_res=os.popen(data).read()
        print type(os.popen(data)) #文件
        print type(cmd_res) #字符串
        conn.send(cmd_res)
s.close()

client端:

import socket
c=socket.socket()

c.connect(("172.25.254.13",8888))
while 1:
    cmd=raw_input(">>").strip()
    if len(cmd)==0:
        continue
    c.send(cmd)
    cmd_res=c.recv(1024)
    print cmd_res
c.close()

你可能感兴趣的:(python,python)