笔记: 迷你主机Linux平台安装, 采集盒COM连接呼吸机 (三)

创作不易 只因热爱!!
**

热衷分享,一起成长!

笔记: 迷你主机Linux平台安装, 采集盒COM连接呼吸机 (三)

迷你主机Linux平台安装, 采集盒COM连接呼吸机。这些估计实施人员或运维的人员经常会碰到相类似问题。!!

今日主题:命令行下 python 通过 Portal无线网页认证, 自动连接认证.

1.流程

在这里插入图片描述

2.代码

#!/usr/bin/python
#-*- coding: utf-8 -*-

import urllib
import urllib2
import socket
import types
import time
import os
import subprocess
import logging

class Login:
    # 初始化记录日志
    logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',filename='/opt/wifi_conn.log', filemode='a', encoding='utf-8') 
    logging.getLogger('wifi_conn')
    
    def __init__(self):
        # 初始化,定义 Portal认证的无线帐户/密码 本机IP # 因为无线Portal上要求一个IP一个帐户一个密码
        self.username = 'wlan199'
        self.password = 'bHBabXl5QDE4'
        self.ip_pre = '192.168.199.199'
        # 定义timesleep刷新时间间隔
        self.every = 10

    def login(self):
        logging.info(u"正在尝试MX35XXH无线网络Protal认证ing")
        # 无线认证POST的数据data 头部headers
        data = {
            "userName": self.username,
            "userPwd": self.password,
            "userDynamicPwd": "",
            "userDynamicPwdd": "",
            "serviceType": "",
            "userurl": "",
            "userip": "",
            "basip": "",
            "language": "Chinese",
            "usermac": "null",
            "wlannasid": "",
            "wlanssid": "",
            "entrance": "null",
            "loginVerifyCode": "",
            "userDynamicPwddd": "",
            "customPageId": "1",
            "send_dynamic_pwd_type": "0",
            "pwdMode": "0",
            "portalProxyIP": "10.10.10.200",
            "portalProxyPort": "50200",
            "dcPwdNeedEncrypt": "1",
            "assignIpType": "0",
            "appRootUrl": "http://10.10.10.200:8080/portal/",
            "manualUrl": "",
            "manualUrlEncryptKey": ""
        }
        headers = {
            "Accept": "text/plain, */*; q=0.01",
            "Accept-Encoding": "gzip, deflate",
            "Accept-Language": "zh-CN,zh;q=0.9",
            "Connection": "keep-alive",
            "Content-Length": "424",
            "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
            "Host": "10.10.10.200:8080",
            "Origin": "http://10.10.10.200:8080",
            "Referer": "http://10.10.10.200:8080/portal/index_default.jsp",
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36",
            "X-Requested-With": "XMLHttpRequest"
        }
        # 无线认证地址 请用网页工具获取, (如果不知, 请联系 作者)
        post_data = urllib.urlencode(data)
        login_url = "http://10.10.10.200:8080/portal/pws?t=li&ifEmailAuth=false"
        # POST认证中
        try:
            request = urllib2.Request(login_url, post_data, headers)
            response = urllib2.urlopen(request)
        except:
            logging.error('Protal认证***http://10.10.10.200:8080/portal/***POST****error***')
        # 以下尝试解码结果, 发现不管GBK 或 UTF8 均一大堆看不懂,好在用不上结果. 一般POST都成功了,没成功就sleep间隔后重新post认证
        # try:
        #     result = response.read().decode('gbk')
        #     logging.info('gbk' + result)
        # except:
        #     logging.error('Protal认证***response.read().decode(gbk)****error***')
        # try:
        #     result = response.read().decode('utf8')
        #     logging.info('utf8' + result)
        # except:
        #     logging.error('Protal认证***response.read().decode(utf8)****error***') 
        
    def login_wifi(self, timecounts, firsttime_wifi):
        logging.info(u"正在尝试Connect无线网卡网络ing")
        if '192.168' not in os.popen('sudo ip a| grep 192.168').read():
            if 'MX35XXH' not in os.popen('sudo nmcli device wifi list | grep MX35XXH').read():
                logging.info(self.getCurrentTime()+u"无线网络MX35XXH的AP可能下线,不在区域范围内!请检查AP!等待ing")
                timecounts = 0
                time.sleep(3*self.every)
            else:
                firsttime_wifi = self.getNow()
                logging.info(self.getCurrentTime()+u"无线网卡已下线,connect wlp3s0重连中ing,重试次数:"+str(timecounts))
                # timecounts += 1
                os.system('sudo nmcli device connect wlp3s0')
            time.sleep(self.every)
        else:
            firsttime_wifi = self.getNow()
            logging.info(u"无线网卡IP存在,但是连接仍不正确,restart network,重试次数:"+str(timecounts))
            # timecounts += 1
            os.system('sudo systemctl restart network')
            time.sleep(self.every)
        if firsttime_wifi is not None:
            return timecounts, firsttime_wifi
        else: 
            return timecounts, None
    def login_wifi_reset(self):
        os.system('sudo reboot')

    def getNow(self):
        return int(time.time())

    def getIP(self): #import socket
        local_iP = socket.gethostbyname(socket.gethostname())
        if local_iP=='127.0.0.1':
            if self.ip_pre in os.popen('sudo ip a| grep {}'.format(self.ip_pre)).read():
                return self.ip_pre
            else:
                logging.info(u"请注意当前IP可能配置错误,联系管理员更正!")
                time.sleep(300)
                return ''
        if self.ip_pre == str(local_iP):
            return str(local_iP)
        else:
            ip_lists = socket.gethostbyname_ex(socket.gethostname())
            for ip_list in ip_lists:
                if isinstance(ip_list, list):
                    for i in ip_list:
                        if self.ip_pre in str(i):
                            return str(i)
                    return ''
                elif type(ip_list) is types.StringType:
                    if self.ip_pre in ip_list:
                        return ip_list
                    else:
                        return ''
                else:
                    return ''
                
    def canConnect(self):
        # 定义每隔一段时间ping服务器, 防掉线
        fnull = open(os.devnull, 'w')
        result = subprocess.call('ping 172.16.150.101 -w 4', shell = True, stdout = fnull, stderr = fnull)
        fnull.close()
        if result:
            return False
        else:
            return True

    def getCurrentTime(self):
        return time.strftime('[%Y-%m-%d %H:%M:%S]',time.localtime(time.time()))
 
    def main(self):
        logging.info(u"您好,欢迎使用PORTAL认证登陆系统")
        firsttime_wifi = None
        newtime_wifi = None
        firsttime_portal = None
        newtime_portal = None
        counts_wifi = 0
        counts_portal = 0
        while True:
            nowIP = self.getIP()
            # logging.info(u"IP:"+str(nowIP))
            if not nowIP:
                counts_wifi += 1
                logging.info(u"请检查是否正常连接MX35XXH无线网络,重连WIFI次数:"+str(counts_wifi))
                if firsttime_wifi is None:
                    counts_wifi, newtime_wifi = self.login_wifi(counts_wifi, newtime_wifi)
                    firsttime_wifi = newtime_wifi
                else:
                    counts_wifi, newtime_wifi = self.login_wifi(counts_wifi, newtime_wifi)
                    if newtime_wifi is not None:
                        if newtime_wifi- firsttime_wifi>30*self.every:
                            firsttime_wifi = None
                            counts_wifi = 0
                if counts_wifi>=3:
                    if newtime_wifi is not None and firsttime_wifi is not None and newtime_wifi- firsttime_wifi<=30*self.every:
                        logging.info(u"连续3次WIFI无法创建连接,重启linux系统")
                        self.login_wifi_reset()
                time.sleep(self.every)
            else:
                if firsttime_portal is None:
                    firsttime_portal = self.getNow()
                else:
                    if newtime_portal is not None and newtime_portal- firsttime_portal>30*self.every:
                        firsttime_portal = None
                        counts_portal = 0
                logging.info(self.getCurrentTime()+u"成功连接了MX35XXH无线网络,本机IP为"+nowIP)
                counts_portal_in = 0
                once_deleted = True
                while True:
                    if time.strftime('%d')=='10' and once_deleted:
                        subprocess.call("sudo rm -f /opt/wifi_conn.log", shell = True) #每月10日凌晨自动清除日志一次
                        once_deleted = False
                    else:
                        once_deleted = True
                    can_connect = self.canConnect()
                    if not can_connect:
                        counts_portal_in += 1
                        self.login()
                        time.sleep(self.every)
                        if counts_portal_in>=3:
                            counts_portal += 1
                            logging.info(u"连续3次MX35XXH无线Portal认证失败,即将重置网络配置重试,当前重试次数:"+str(counts_portal))
                            newtime_portal = self.getNow()
                            break
                    else:
                        logging.info(u"Nice,当前网络连接正常……")
                        time.sleep(300)
                if counts_portal>=3:
                    if newtime_portal is not None and firsttime_portal is not None and newtime_portal- firsttime_portal<=30*self.every:
                        logging.info(u"连续3次重置网络x3次PORTAL认证仍无法连接,重启linux系统")
                        self.login_wifi_reset()
            time.sleep(self.every)

if __name__ == '__main__':
    # 由于时间相差太多,可能会认证错误, Linux配置时没有设置时区, 这里运行一下
    subprocess.call("sudo timedatectl set-timezone 'Asia/Shanghai'", shell = True)
    login = Login()
    login.main()

end

^**你好呀,我是一个医信行业工程师,喜欢学习,喜欢搞机,喜欢各种捣,也会持续分享,如果喜欢我,那就关注我吧!**^


笔记: 迷你主机Linux平台安装, 采集盒COM连接呼吸机 (一)
笔记: 迷你主机Linux平台安装, 采集盒COM连接呼吸机 (二)
作者|医信工程师随笔|Carltiger_github

图片|网络|侵删!!

关注我,我们共同成长

“你的鼓励就是我分享的动力”

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值