python模拟socket简单网络编程

上一篇 / 下一篇  2013-05-23 17:55:29 / 个人分类:自动化测试

最近在用Python来做些简单的网络编程,觉得挺方便,拿来跟大家share下:
首先,包含两部分,客户端和服务端,分别见client.py和server.py

第一部分  client.py

#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import commands
import socket
address = ('10.81.14.221', 31502) ##参数分别为想作为服务端的ip和本py脚本的端口,随便找个没被占用的即可
#查询core文件总数
status2,corenum = commands.getstatusoutput("ls -l /home/coresave/ | grep 'core' | wc -l")  #相当于ruby中的system命令,并获取返回值,system只获取返回状态码
print corenum 
#查询当日core文件总数
status1,corenum_today = commands.getstatusoutput("find . /home/coresave/ -mtime -1 ! -type d | grep 'core' | wc -l")
#pf ="/home/work/yefei/monitor/result"
#os.system("rm result 2>/dev/null")
#查询进程是否存在
pstate = os.system("ps -A|grep noah-agent >/dev/null")  #获取执行状态码
pstate>>= 8
if pstate: 
    pstate = 0
else:
    pstate = 1
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)#创建个socket连接
sock.connect(address)#连接server
sock.send('process_state:%d,total_core:%d,today_core:%d' % (pstate,int(corenum),int(corenum_today)))#向server发送消息
#print sock.recv(1024)
sock.close()     #关闭客户端

第二部分  server.py
  #!/usr/bin/env python
import socket
import time
import os,sys
import MySQLdb 

address = ('10.81.14.221', 31502)  #参数分别为想作为服务端的ip和本py脚本的端口,随便找个没被占用的即可
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)  #创建一个socket连接
sock.bind(address) #绑定到服务器
sock.listen(500)   #监听服务
index1 = len("process_state:")  #len(string) 获取字符串string的长度 ,打印出来为13
len2 = len(",total_core:")
len3 = len(",today_core:")
while True: 
    connection,src_address = sock.accept() #创建接收客户端的一个对象connection(名字随便起);把客户端的Ip和port存储到src_address(数组形式)
#   print 'got connected from',src_address
#   connection.send('welcome to python server!')
    cdn_addr = src_address[0]
#   print cdn_addr
    buf = connection.recv(1024)  #buf为clientserver的send方法发送过来的内容,设定最大为1024字节,类型为字符串
    print type(buf)   #type后边跟对象名,可以判定buf是什么类型,相当于ruby 的puts xx.class
#   print buf
    index2 = buf.index(",total_core:")  #和ruby中的index方法一样,str.index('total',0,43)意思是返回total在str中出现的位置
    process_stat = int(buf[index1:index2])
    index3 = index2 + len2
    index4 = buf.index(",today_core:")
#   total_core = int(buf[index3:len(buf)])
    total_core = int(buf[index3:index4])
    index5 = index4 + len3
    today_core = int(buf[index5:len(buf)])
    print process_stat,total_core,today_core
    conn=MySQLdb.connect(host='10.81.15.41',user='work',passwd="passwd",db='yefei_process_monitor') #创建mysql数据库连接
    cursor=conn.cursor()  #cursor用来执行命令的方法
    sql="insert into monitor_data(ip_addr, process_status,total_core,today_core) values ('%s',%d,%d,%d)" % (cdn_addr,int(process_stat),int(total_core),int(today_core))
#   print sql
    cursor.execute(sql)
    cursor.close()
    conn.close()
    connection.close()

第三部分,执行方法
  1. 首先修改py中的mysql配置和server配置和端口
  2. 启动server,通过python server.py,相当于个进程,一直启动并监听       client发来的请求
  3. 执行client.py
  4. server端收到后会进行处理
  

TAG:

 

评分:0

我来说两句

Open Toolbar