python3的soker模块实现功能
模拟和linux交互,只可以使用查看命令
服务端
主要是创建一个服务端,在创建服务端的时候,主要步骤如下:
创建socket对象socket——》绑定IP地址和端口bind——》监听listen——》得到请求accept——》接收请求recv——》发送信息send
import socket import subprocess server = socket.socket() #创建对象 server.bind(('', 8888)) #绑定代码(IP地址,端口号),第一个可以写IP地址或者localhost,如果不写的话,说明允许想和太主机上的所有ip都可以接受连接 server.listen(5) #监听代码,设置最大连接数,参数为整数,当第一个连接上的时候,其他的都不会连接,等第一个退出的时候,其他的顶上。 print('等待连接.....') conn, addr = server.accept() #被动接受请求 print('已连接......') while True: #死循环 data = conn.recv(10240) #接受消息,最多接收的字节数为10240,那么多余的字符将会在下次接收的过程中进行接收。 cmd = subprocess.Popen(data.decode('utf-8'), shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout = cmd.stdout.read() stderr = cmd.stderr.read() conn.send(stdout + stderr) #发送消息
客户端
创建socket对象socket——》connet连接服务器——》获取消息recv——》发送消息send
import socket import threading client = socket.socket() client.connect(('192.168.29.137', 8888)) #客户端连接服务端 while True: info = input('===>:') #交互 if not info:continue client.send(info.encode('utf-8')) data = client.recv(10240) #接收消息代码 print(data.decode('utf-8'))
模拟通信软件,可以双方对话
服务端
import socket import subprocess import threading server = socket.socket() server.bind(('', 8888)) server.listen(5) print('等待电话.....') conn, addr = server.accept() print('电话来了......') def recv(): while True: data = conn.recv(10240) print(data.decode('utf-8')) def send(): while True: data = input('===>:') conn.send(data.encode('utf-8')) t1 = threading.Thread(target=recv) t2 = threading.Thread(target=send) t1.start() t2.start()
客户端
import socket import threading client = socket.socket() client.connect(('localhost', 8888)) def send(): while True: info = input('===>:') client.send(info.encode('utf-8')) def recv(): while True: data = client.recv(1024) print(data.decode('utf-8')) t1 = threading.Thread(target=send) t2 = threading.Thread(target=recv) t1.start() t2.start()
查看测试主机和端口通不通
import re import socket def sendmail(aa): import smtplib from email.mime.text import MIMEText from email.header import Header sender = '发送的邮箱' receiver = '接收的邮箱' subject = '报警' username = '邮箱用户名' password = '邮箱密码' msg = MIMEText(aa, 'plain', 'utf-8') msg['Subject'] = Header(subject, 'utf-8') msg['From'] = 'Tim<发送邮箱>' msg['To'] = "接收邮箱" smtp = smtplib.SMTP() smtp.connect('smtp.163.com') smtp.login(username, password) smtp.sendmail(sender, receiver, msg.as_string()) smtp.quit() client = socket.socket() host_list = ['192.168.254.24:1111','192.168.7.118:423'] for item in host_list: ip = re.compile('(.*?):(.*)').search(item).group(1) port = re.compile('(.*?):(.*)').search(item).group(2) result = client.connect_ex((ip, int(port))) if result != 0: sendmail('%s不通l,%s端口不通l' % (ip,port))