iT邦幫忙

0

Python偵測VPN網路是否可連線 - Python練習題二

  • 分享至 

  • xImage
  •  

公司為跨國企業, 與工廠間的數據利用VPN進行資料交換, 利用Python配合Windows的排程記錄各站點間網路的狀況

import re
import socket
import datetime


def internet_on(server_addr):
    """測試網路是否可連線
    參數: server_addr
    """
    try:
        ip_reg = re.compile('^((25[0-5]|2[0-4]\d|1\d{2}|[1-9]?\d)\.){3}(25[0-5]|2[0-4]\d|1\d{2}|[1-9]?\d)$')
        is_ip = ip_reg.match(server_addr)
        #print("checking internet connection..")
        socket.setdefaulttimeout(5)
        if is_ip is None:
            host = socket.gethostbyname(server_addr)
        else:
            host = server_addr

        s = socket.create_connection((host, 80), 2) #time out 會 raise socket.timeout("timed out")
        s.close()
        #print('internet on.')
        return True
    except: #Exception as e:
        #print(e)
        #print("internet off.")
        return False
        

def write_log(file_name, msg):
    with open(file_name, 'a', encoding='utf-8') as file_obj:
        file_obj.write(msg)


 
# vpn server 地址
db_ip = {"RichPine":"192.168.0.1", "RichWay":"192.168.1.1", "EverBest":"192.168.2.1", "Google":"www.google.com"}

for fty_name in db_ip:
    dt_now = datetime.datetime.now()

    file_name = dt_now.strftime('%Y%m%d') + '_' + fty_name + '.log'
    msg =  dt_now.strftime('%Y-%m-%d %H:%M:%S')

    result = internet_on(db_ip[fty_name])
    if result == False:
        msg = msg + ' : off ----------\n' 
    else:
        msg = msg + ' : on\n'

    #print(fty_name, db_ip[fty_name], result, file_name, msg)
    write_log(file_name, msg)

執行結果
https://ithelp.ithome.com.tw/upload/images/20210412/20098325r2Nb2dANBq.jpg


圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言