Linux自动wifi搜索使用python连接和断开连接

时间:2019-07-03 12:16:52

标签: python sockets networking

我正在为客户端和服务器编写代码,其中  客户端将搜索网络并自动连接,  分享一些信息。现在,如果网络超出以下范围 客户端,然后客户端与此断开连接。我怎样才能做到这一点。  以前,我在客户端和服务器中使用了UDP套接字,在其中使用了 用于搜索连接的ip和客户端到wifi的脚本 服务器的热点。如果服务器是有效的IP  搜索然后传输一些消息。但是在客户端,客户端 还应该搜索wifi连接,然后再连接到它。 以前,我在客户端和服务器中使用了UDP套接字,在其中使用了 用于搜索连接的ip和客户端到wifi热点的脚本  服务器。如果服务器搜索的是有效ip,则发送  一些消息。但在客户端,客户端也应搜索 wifi连接,然后连接到它。因为客户端正在移动,并且它将一次又一次地连接到服务器并断开连接。 因此,当我运行程序时,客户端和服务器发送数据,但是当客户端超出服务器范围并再次连接到该服务器(同一服务器)时,客户端卡住。 客户端每2秒发送一次数据。时间。

    # -*- coding: utf-8 -*-
"""
Created on Tue Apr  2 10:29:46 2019

@author: Gaurav Sharma
"""

import os, time
import re
import threading, UDPComm, RSA, base64

private_key , public_key = RSA.generate_keys()
encrypt_str = "encrypted_message="
iplist={'10.42.0.50':'101','10.42.0.91':'102'}

#arr = array.array('
class ClientThread(threading.Thread):
    def __init__(self,clientAddress, clientRegNo,clientPort):
        threading.Thread.__init__(self)
        self.clientAddress = clientAddress
        self.clientPort = clientPort
        self.clientRegNo = clientRegNo
        self.client_public_key=""
        self.clientValid=False
        self.keyExchanged=False
        self.ConnEstablised=False
        print ("New connection incoming: ", (clientAddress, clientPort))
    def run(self):
        sock = UDPComm.getSock((self.clientAddress, self.clientPort))
        print ("Connection from : ", (self.clientAddress, self.clientPort))
        #self.csocket.send(bytes("Hi, This is from Server..",'utf-8'))
        UDPComm.sendTo(sock, "Server:Handshake", "", (self.clientAddress, self.clientPort))
        while True:

            sock.settimeout(10)
            try:
                data = sock.recv(1024)
                time.sleep(1)
            except Exception as e:
                print (e)
                break
            try:
                msg = base64.b64decode(data)
                print ("Message from client", msg)
            except Exception as e:
                print (e)

            if self.ConnEstablised:
                print ("Received:\nEncrypted message = "+str(data))
                decrypted = RSA.decrypt_message(data, private_key)
                decrypted = decrypted.replace(encrypt_str, '')
                print ("Decrypted message = " + decrypted)
                UDPComm.sendTo(sock, "Server:OK", self.client_public_key, (self.clientAddress, self.clientPort))
                continue

            if self.keyExchanged:
                print ("Received:\nEncrypted message = "+str(data))
                decrypted = RSA.decrypt_message(data, private_key)
                decrypted = decrypted.replace(encrypt_str, '')
                print ("Decrypted message = " + decrypted)
                if decrypted=="Client:OK":
                    print("Successfully exchanged keys")
                    UDPComm.sendTo(sock, "Server:OK", self.client_public_key, (self.clientAddress, self.clientPort))

                    self.ConnEstablised=True
                    continue
                else:
                    print("Failed to establish Connection")
                    break

            if self.clientValid:
                if len(data)>0:
                    self.client_public_key = RSA.importKey(data)
                    print("Client public key received")
                    UDPComm.sendTo(sock, "Server:OK", self.client_public_key, (self.clientAddress, self.clientPort))
                    self.keyExchanged=True
                    continue
                else:
                    print("Failed to Exchange keys")
                    break

            if 'Client:AckHandshake:' in msg:
                msg = msg.replace('Client:AckHandshake:','')
                if msg==self.clientRegNo:
                    UDPComm.sendTo(sock, public_key.exportKey(), "key", (self.clientAddress, self.clientPort))
                    print ("Public key sent to client.")
                    self.clientValid=True
                    continue
                else:
                    print("Failed to authorize client")
                    break


        print ("Client at ", (self.clientAddress,self.clientPort) , " disconnected...")


def getIPs():    
    global iplist
    myCmd = os.popen('./show_client.sh').read()
    IPs = myCmd.split()
    r = re.compile(r"^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$")
    IPs = (filter(r.match, IPs))
    print("Connected IPs:", IPs)
    a = set(IPs)
    b = set([x for x in iplist])
    c = a & b
    if c:
        print("Valid IPs", c)
    else:
        print("No valid IPs detected")
    return c

def getNeighbours():
    global new_list, old_list, hello, byebye, iplist
    new_list = getIPs()
    hello = set(new_list) - set(old_list)
    byebye = set(old_list) - set(new_list)

    if len(hello)>0 and len(byebye)>0:
        print("The Following IP's joined new\n", hello)
        print("value of Ip\n", new_list)
        print("The Following IP's disconnected new\n", byebye)
        old_list = set(new_list)
    elif len(hello)>0:
        print("The Following IP's joined new\n", hello)
        old_list = set(new_list)
    elif len(byebye)>0:
        print("The Following IP's disconnected new\n", byebye)
        old_list = set(new_list)
    else:
        print("No changes")
    for ips in hello:
        clientAddress=ips
        clientRegNo = iplist[clientAddress]
        clientPort=12345
        newthread = ClientThread(clientAddress, clientRegNo, clientPort)
        newthread.start()

def WifiListener():
    print("WifiListener  started")
    while(True):
        getNeighbours()
        time.sleep(5)

LOCALHOST = "127.0.0.1"
#clientPort = 12345
#clientAddress = '' #used for all communication
PORT= 12345
old_list=set()
new_list=set()
hello=set()
byebye=set()
thread1 = threading.Thread(target = WifiListener)
thread1.start()
#WifiListener()
print("Server started")
print("Waiting for client request..") 

这是客户端代码

   import socket
"""
@ author gaurav sharma
"""
import UDPComm
import RSA
import base64

UDP_IP = '0.0.0.0'
UDP_PORT = 12345

private_key , public_key = RSA.generate_keys()
encrypt_str = "encrypted_message="

clientRegNo = "101" #take from db

server_public_key=""
sock = socket.socket(socket.AF_INET, # Internet
                     socket.SOCK_DGRAM) # UDP
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.bind((UDP_IP, UDP_PORT))

step=0

while True:
    data, addr = sock.recvfrom(1024) # buffer size is 1024 bytes
    #data = unicode(data, errors='ignore')
    try:
        msg = base64.b64decode(data)
    except Exception as e:
        print(e)
        msg=''
    print ("Received:",msg)
    print ("Received from:", addr)

    if msg=="Server:Handshake":
        message = "Client:AckHandshake:"+clientRegNo
        UDPComm.sendTo(sock, message, "", addr)
        step=1
        continue

    if step==1:
        #data = data.replace("Server:PublicKey", '')
        #data=data.replace("\r\n", '')
        if len(data)>0:
            print("Server pubic key received!")
            server_public_key = RSA.importKey(data)
            message = public_key.exportKey()
            UDPComm.sendTo(sock, message, "key", addr)
            step=2
            continue
        else:
            print("Unable to Establish connection")


    if step==2:
        decrypted = RSA.decrypt_message(data, private_key)
        decrypted = decrypted.replace(encrypt_str, '')
        print ("Decrypted message = " + decrypted)
        if decrypted=="Server:OK":
            print("Succesfully exchanged keys")
            message = "Client:OK"
            UDPComm.sendTo(sock, message, server_public_key, addr)
            step=3
            continue
        else:
            print("Unable to exchange keys")

    if step==3:
        decrypted = RSA.decrypt_message(data, private_key)
        decrypted = decrypted.replace(encrypt_str, '')
        print ("Decrypted message = " + decrypted)
        if decrypted=="Server:OK":
            message = "Client:OK"
            UDPComm.sendTo(sock, message, server_public_key, addr)
        else:
            print("Not connected to any server")

0 个答案:

没有答案