python网络编程实例

Posted ㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤ0

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python网络编程实例相关的知识,希望对你有一定的参考价值。

文章目录

python网络编程实例

字符串转换实例

使用SOCK_STREAM方式通信,服务端接收到来自客户端的字符串转换为大写后返回给客户端
str_socket_s.py 服务端代码

#!/usr/bin/env python3
# coding:utf-8
import socket				//导入socket模块
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)     		//构造socket对象,使用ipv4地址和TCP方式通信
s.bind(('192.168.247.100',10086))						//调用bind函数将对象s绑定到元组('192.168.247.100',100086)上
s.listen(1)							//监听来自客户端的连接,1表示只接收一个连接
print('Wait for connecting...')
(conn,addr) = s.accept()      //调用accept函数接受一个来自客户端的连接,返回元组(conn,addr),其中conn也是一个socket对象,用来与客户端通信,addr为元组变量,保存客户端IP和端口。
print('conn = ',conn)
print('addr = ',addr)
while True:
    str1 = conn.recv(1024)            //conn通过recv函数控制一次接收字节流的大小
    str2 = str(str1,encoding = 'utf-8')				//将字节流数据转换为字符串
    print('I received a string is:',str2)				
    str3 = str2.upper()								//通过upper方法将小写转换为大写
    conn.send(str3.encode('utf-8'))			//最后将字符转转换回字节流发送给客户端
    if str2 =='.':
        break
conn.close()						//关闭连接
s.close()								//释放socket对象

str_socket_c.py 客户端代码

#!/usr/bin/env python3
# coding:utf-8
import socket
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.connect(('192.168.247.100',10086))			//调用connect函数连接服务器
print('I am connecting the server')
while True:
    xx = input('请输入字符串:')  					//接收字符串
    s.send(xx.encode('utf-8'))						//将字符串转换为字节流,然后通过socket对象发送给服务端
    str1 = s.recv(1024)									//控制服务端返回的字节流的接收大小
    str2 = str(str1,encoding = 'utf-8')				//将服务端返回的字节流转换为字符串
    print('The original string is :',xx,'\\ttheprocessed string is:',str2)    	
    if xx == '.':
        break
s.close()

测试效果:
服务端

[root@localhost ~]# python3 str_socket_s.py 
Wait for connecting...
conn =  <socket.socket fd=4, family=AddressFamily.AF_INET, type=SocketKind.SOCK_STREAM, proto=0, laddr=('192.168.247.100', 10086), raddr=('192.168.247.100', 36738)>
addr =  ('192.168.247.100', 36738)
I received a string is: haha
I received a string is: xixi
I received a string is: hehe
I received a string is: .

客户端

[root@localhost ~]# python3 str_socket_c.py 
I am connecting the server
请输入字符串:haha
The original string is : haha 	theprocessed string is: HAHA
请输入字符串:xixi
The original string is : xixi 	theprocessed string is: XIXI
请输入字符串:hehe
The original string is : hehe 	theprocessed string is: HEHE
请输入字符串:.
The original string is : . 	theprocessed string is: .

文件下载实例

服务端代码:

#!/usr/bin/env python3
# coding:utf-8
import socket
import os
def sendfile(conn):
    str1 = conn.recv(1024)
    filename = str1.decode('utf-8')
    print('The client requests my file:',filename)
    if os.path.exists(filename):
        print('I have %s,begin to download!' % filename)
        conn.send(b'yes')
        conn.recv(1024)
        size = 1024
        with open(filename,'rb') as f:
            while True:
                data = f.read(size)
                conn.send(data)
                if len(data) < size:
                    break
        print('%s is downloaded successfully!' % filename)
    else:
        print('Sorry,I have no %s!' % filename)
        conn.send(b'no')
    conn.close()
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.bind(('192.168.247.100',10086))
s.listen(10)
print('Wait for connecting...')
while True:
    (conn,addr) = s.accept()
    sendfile(conn)

客户端代码:

#!/usr/bin/env python3
# coding:utf-8
import socket
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.connect(('192.168.247.100',10086))
filename = input('请用绝对路径输入想要下载的文件:')
print('I want to get the file %s!' %filename)
s.send(filename.encode('utf-8'))
str1 = s.recv(1024)
str2 = str1.decode('utf-8')
if str2 == 'no':
    print('To get the file %s failed!' % filename)
else:
    s.send(b'I am ready!')
    temp = filename.split('/')
    myname = 'my_' + temp[len(temp)-1]
    size = 1024
    with open (myname,'wb') as f:
        while True:
            data = s.recv(size)
            f.write(data)
            if len(data) < size:
                break
    print('The downloaded file is %s. ' % myname)
s.close()

测试效果
服务端

[root@localhost ~]# ls /tmp
test
[root@localhost ~]# python3 download_socket_s.py
Wait for connecting...
The client requests my file: /tmp/test
I have /tmp/test,begin to download!
/tmp/test is downloaded successfully!

客户端

[root@localhost ~]# ls
anaconda-ks.cfg       download_socket_s.py  network.sh   str_socket_c.py
download_socket_c.py  lzu.html              socket01.py  str_socket_s.py
[root@localhost ~]# python3 download_socket_c.py
请用绝对路径输入想要下载的文件:/tmp/test
I want to get the file /tmp/test!
The downloaded file is my_test. 
[root@localhost ~]# ls
anaconda-ks.cfg       lzu.html    socket01.py
download_socket_c.py  my_test     str_socket_c.py
download_socket_s.py  network.sh  str_socket_s.py

扫描端口实例

代码

#!/usr/bin/env python3
# coding:utf-8
import socket
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.settimeout(0.5)#扫描本机设置较短超时时间
ip = input('请输入要扫描主机的ip:')
start = 0
stop = 65535
for port in range(int(start),int(stop)):
    result = s.connect_ex((ip,port))
    if result == 0:
        print(ip+'上的'+str(port)+'端口是开启的' )
s.close()

测试效果

[root@localhost ~]# python3 port.py
请输入要扫描主机的ip:192.168.247.214
192.168.247.214上的22端口是开启的
192.168.247.214上的23端口是开启的
[root@localhost ~]# ss -anlt
State   Recv-Q  Send-Q   Local Address:Port    Peer Address:Port  Process  
LISTEN  0       128            0.0.0.0:22           0.0.0.0:*              
LISTEN  0       128               [::]:22              [::]:*              

获取服务端CPU使用情况实例

服务端代码:

 #!/usr/bin/env python3
# coding:utf-8
import socket
import psutil
def do_cpu():
    data = str(psutil.cpu_percent(0)) + '%\\n'
    count = 0
    for process in psutil.process_iter():
        data = data + process.name()
        data = data + ',' + str(process.pid)
        cpu_usage_rate_process = str(process.cpu_percent(0)) + '% '
        data = data + ',' +cpu_usage_rate_process + '\\n'
        count+=1
        if count == 10:
            break
    return data
s = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
s.bind(('192.168.247.100',10086))
print('Bind UDP on 10086')
while True:
    (info,addr) = s.recvfrom(1024)
    data = do_cpu()
    s.sendto(data.encode('utf-8'),addr)
    print('The client is ',addr)
    print('Sended CPU data is:',data)

客户端代码:

#!/usr/bin/env python3
# coding:utf-8
import socket
s = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
s_addr = ('192.168.247.100',10086)
s.sendto(b'CPU info',s_addr)
(data_b,addr) = s.recvfrom(1024)
if addr == s_addr:
    data_s = data_b.decode('utf-8')
    data_list = data_s.split('\\n')
    print('CPU usage rate is',data_list[0])
    print('Top 10 processes are flowing...')
    print('% -20s% -5s% -10s' % ('NAME','PID','CPU usage'))
    data_list = data_list[1:-1]
    for xx in data_list:
        yy = xx.split(',')
        print('% -20s% -5s% -10s' % (yy[0],yy[1],yy[2]))
s.close()

测试效果
服务端

[root@localhost ~]# python3 cpu_s.py 
Bind UDP on 10086
The client is  ('192.168.247.100', 40648)
Sended CPU data is: 0.2%
systemd,1,0.0% 
kthreadd,2,0.0% 
rcu_gp,3,0.0% 
rcu_par_gp,4,0.0% 
kworker/0:0H-kblockd,6,0.0% 
mm_percpu_wq,9,0.0% 
ksoftirqd/0,10,0.0% 
rcu_sched,11,0.0% 
migration/0,12,0.0% 
watchdog/0,13,0.0% 

客户端

[root@localhost ~]# python3 cpu_c.py 
CPU usage rate is 0.2%
Top 10 processes are flowing...
NAME                PID  CPU usage 
systemd             1    0.0%      
kthreadd            2    0.0%      
rcu_gp              3    0.0%      
rcu_par_gp          4    0.0%      
kworker/0:0H-kblockd6    0.0%      
mm_percpu_wq        9    0.0%      
ksoftirqd/0         10   0.0%      
rcu_sched           11   0.0%      
migration/0         12   0.0%      
watchdog/0          13   0.0%  

以上是关于python网络编程实例的主要内容,如果未能解决你的问题,请参考以下文章

python网络编程实例

python网络编程实例

Python基础编程题100列目录

Python--网络编程-----socket代码实例

python进阶三(面向对象编程基础)3-3 python中定义实例方法

初学python100例-案例35 数字反转 少儿编程python编程实例讲解