python下的socket
1、简单的server和client端的socket代码
server.py:
#!/usr/bin/env python
#_*_ coding:utf-8 _*_
import socket
ip_port = ('127.0.0.1',9999)
sk = socket.socket()
sk.bind(ip_port)
sk.listen(1)
while 1:
print 'waiting'
conn,addr = sk.accept()
conn.sendall('welcome to 10086')
conn.close()
client.py:
#!/usr/bin/env python
#_*_ coding:utf-8 _*_
import socket
ip_port = ('127.0.0.1',9999)
sk = socket.socket()
sk.connect(ip_port)
data = sk.recv(1024)
sk.close()
print data
分别在两个窗口运行:
# python server.py
# python client.py
2、多线程,阻塞模式
server.py:
#!/usr/bin/env python
#_*_ coding:utf-8 _*_
import socket
# 阻塞式
sk = socket.socket()
ip_port = ('192.168.8.51',50001)
sk.bind(ip_port)
sk.listen(2)
while True:
conn,addr = sk.accept()
print 'get a data from ',addr
while True:
data = conn.recv(1024)
if not data : break
conn.send(data.upper())
print 'recevie:',data
sk.close()
client.py:
#!/usr/bin/env python
#_*_ coding:utf-8 _*_
import socket
ip_port = ('192.168.8.51',50001)
sk = socket.socket()
sk.connect(ip_port)
while True:
input_data = raw_input('')
sk.send(input_data)
data = sk.recv(1024)
print 'recevi:',data
sk.close()
3、模拟实现ssh
ssh_socket_server.py:
#!/usr/bin/env python
#_*_ coding:utf-8 _*_
import SocketServer
import commands,time
class MySocksServer(SocketServer.BaseRequestHandler):
def handle(self):
print 'get a new conn from ',self.client_address
while True:
cmd = self.request.recv(1024)
if not cmd:
print 'lost connetion with',self.client_address
break
cmd_result = commands.getstatusoutput(cmd)
# send result size
self.request.send(str(len(cmd_result[1])))
#self.sleep(0.2)
# send result
self.request.sendall(cmd_result[1])
if __name__ == '__main__':
h = '0.0.0.0'
p = 50003
s = SocketServer.ThreadingTCPServer((h,p),MySocksServer)
s.serve_forever()
socket_client:
#!/usr/bin/env python
#_*_ coding:utf-8 _*_
import socket
from _mysql import result
ip_port = ('192.168.8.51',50003)
sk = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
sk.connect(ip_port)
def recv_all(obj,msg_length):
raw_result = ''
while msg_length != 0:
if msg_length <= 4096:
data = obj.recv(msg_length)
msg_length = 0
else:
data = obj.recv(4096)
msg_length -= 4096
raw_result += data
return raw_result
while True:
input_data = raw_input('')
if len(input_data) == 0: break
sk.sendall(input_data)
# recv response size
res_size = int(sk.recv(100))
print 'data size from server',res_size
result = recv_all(sk,res_size)
print result
sk.close()
4、模拟实现ftp账号远程登录通过获取数据
ftp客户端
ftp_client.py:
#!/usr/bin/env python
#_*_ coding:utf-8 _*_
import socket
import MySQLdb
import os
import hashlib
from _mysql import result
ip_port = ('192.168.50.18',50004)
sk = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
sk.connect(ip_port)
#连接数据库函数
def conn_db():
try:
return MySQLdb.connect(host='localhost',user='root',passwd='',port=3306)
except MySQLdb.Error,e:
print "Mysql Error %d: %s" % (e.args[0], e.args[1])
# md5加密的函数
def md5_create(name):
code = hashlib.md5()
code.update(name)
return code.hexdigest()
#验证用户名密码是否正确
def login(username,password):
#连接数据库
conn = conn_db()
cur = conn.cursor()
conn.select_db('python')
cur.execute('select password from user where username = "%s"' % username)
result = cur.fetchone()
md5code = md5_create(password)
#验证密码是否正确
if result[0] == md5code:
return True
else:
return False
def recv_all(obj,msg_length):
raw_result = ''
while msg_length != 0:
if msg_length <= 4096:
data = obj.recv(msg_length)
msg_length = 0
else:
data = obj.recv(4096)
msg_length -= 4096
raw_result += data
return raw_result
#获取数据函数
def get_all(self,obj,msg_length,dst_file):
while msg_length != 0:
if msg_length <= 4096:
data = obj.recv(msg_length)
msg_length = 0
print 'to less ',msg_length
else:
data = obj.recv(4096)
msg_length -= 4096
print 'else ',msg_length
dst_file.write(data)
return 'done'
while True:
user_input = raw_input('please input your username and password eg: user pwd ')
if len(user_input) == 0:
print 'your username or password is error'
break
username,password = user_input.split()
#验证用户密码是否正确
login_rs = login(username,password)
if login_rs:
while True:
user_input = raw_input('msg to send::')
if len(user_input) == 0: continue
user_cmd = user_input.split()
#如果命令为put则进行传输数据
if user_cmd[0] == 'put':
if len(user_cmd) == 2:
f = file(user_cmd[1] , 'rb')
f_size = os.stat(user_cmd[1]).st_size
sk.send("%s %s %s" %(user_cmd[0],user_cmd[1],f_size))
print 'going to send...'
sk.sendall(f.read())
print sk.recv(1024)
else:
sk.sendall(user_cmd[0])
print 'else',user_cmd[0]
res_size = int(sk.recv(100))
print 'data size from server',res_size
result = recv_all(sk,res_size)
print result
sk.close()
服务器端:
ftp_server.py
#!/usr/bin/env python
#_*_ coding:utf-8 _*_
import SocketServer
import commands
import socket
class MySocksServer(SocketServer.BaseRequestHandler):
def recv_all(self,obj,msg_length,dst_file):
while msg_length != 0:
if msg_length <= 4096:
data = obj.recv(msg_length)
msg_length = 0
print 'to less ',msg_length
else:
data = obj.recv(4096)
msg_length -= 4096
print 'else ',msg_length
dst_file.write(data)
return 'done'
def handle(self):
print 'get a new conn from ',self.client_address
while True:
cmd = self.request.recv(1024)
if not cmd:
print 'lost connetion with',self.client_address
break
#option,filename,file_size = cmd.split()
cmd_c = cmd.split()
if cmd_c[0] == 'put':
# client want to upload file
f = file('recv/%s' % cmd_c[1],'wb')
write_to_file = self.recv_all(self.request, int(cmd_c[2]), f)
if write_to_file == 'done':
self.request.send('file upload success')
f.close()
else:
print 'start send cmd back info'
cmd_result = commands.getstatusoutput(cmd_c[0])
self.request.send(str(len(cmd_result[1])))
self.request.sendall(cmd_result[1])
if __name__ == '__main__':
h = '0.0.0.0'
p = 50004
s = SocketServer.ThreadingTCPServer((h,p),MySocksServer)
sk = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.serve_forever()