Revived from "no internet access" in Python

Introduction

** Are you all suffering from a sudden "no internet access"? ** **

netsh_test1 (3)_LI.jpg

I was bothered. I have created a script to automate routine tasks and have it resident on an old PC. When I left the PC on, I was in a state of "no internet access" before I knew it, and I had to manually disconnect and reconnect the PC network. It's scary that the process stops before you know it, even though it's automated and left unattended.

Therefore, I tried to check the network status and reconnect in the script, so I will introduce it.

(I don't know why you don't have internet access in the first place, so please let me know who you are.)

environment

・ Windows7 ・ Anaconda3

Conclusion (code) for the time being

The content is mostly Windows commands, but I am calling the commands from Python because it is part of the script.

def is_ping_ok():
    proc = subprocess.run(["ping", "yahoo.co.jp"], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    ret = proc.stdout.decode("cp932")
    if "Not found" in ret:
        return False
    else: return True

def restart_network():
    subprocess.run(["netsh", "wlan", "disconnect"])
    subprocess.run(["netsh", "wlan", "connect", 'name="SSID you want to connect to"'])
    time.sleep(5)

def check_network():
    if not is_ping_ok():
        restart_network()

        if is_ping_ok():
            return "Restarted!"
        else: return "Error"
    return "OK"

For the time being, I try it once and give up if it doesn't come back, but if you don't like losing, I think you can recurse thoroughly until it comes back.

Commentary

Check network status

Use the ping command to check if you have internet access. Please refer to this article for the subprocess that suddenly appeared.

The following is for internet access

>>> import subprocess

>>> proc = subprocess.run(["ping","yahoo.co.jp"], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
>>> print(proc.stdout.decode("cp932"))

yahoo.co.jp [182.22.59.229]Pinging to 32 bytes of data:
182.22.59.Response from 229:Number of bytes=32 hours=11ms TTL=50
182.22.59.Response from 229:Number of bytes=32 hours=16ms TTL=50
182.22.59.Response from 229:Number of bytes=32 hours=21ms TTL=50
182.22.59.Response from 229:Number of bytes=32 hours=21ms TTL=50

182.22.59.229 ping statistics:
Number of packets:Send=4, receive=4, loss= 0 (0%Loss)、
Approximate round trip time(millisecond):
minimum=11ms, maximum=21ms, average= 17ms

Without internet access

>>> proc = subprocess.run(["ping","yahoo.co.jp"], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
>>> print(proc.stdout.decode("cp932"))
Host yahoo in ping request.co.jp was not found. Check the host name and try again.

If the return value contains "not found", we have decided to determine that there is no internet access. I think this depends on the language of the terminal.

def is_ping_ok():
    proc = subprocess.run(["ping", "yahoo.co.jp"], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    ret = proc.stdout.decode("cp932")
    if "Not found" in ret:
        return False
    else: return True

Network restart

If you do not have internet access, try reconnecting the network with the following command. For details of the command, refer to this article.

> netsh wlan disconnect
Interface"Wireless network connection"Disconnect request completed successfully.

> netsh wlan connect name="SSID you want to connect to"
The connection request completed successfully.

When called with python, it will be as follows. I put sleep so that I will not move to the next process without completing the connection.

def restart_network():
    subprocess.run(["netsh", "wlan", "disconnect"])
    subprocess.run(["netsh", "wlan", "connect", 'name="SSID you want to connect to"'])
    time.sleep(5)

Summary

I introduced how to fight the sudden "no internet access".

We are looking for a smarter way.

Recommended Posts

Revived from "no internet access" in Python
Access bitcoind from python
OCR from PDF in Python
Access Oracle DB from Python
Try PLC register access in Python
Extract text from images in Python
There is no switch in python
How to access wikipedia from python
Access spreadsheets using OAuth 2.0 from Python
Access Blender Shader Nodes from Python
Access the Twitter API in Python
Extract strings from files in Python
Get exchange rates from open exchange rates in Python
How to access environment variables in Python
Prevent double boot from cron in Python
In python + sqlite3 "OperationalError: no such column:"
Exclusive file access between processes in Python
How to access RDS from Lambda (python)
Download images from URL list in Python
Get battery level from SwitchBot in Python
ModuleNotFoundError in Python: No module named story
Generate a class from a string in Python
Generate C language from S-expressions in Python
Access S3 resources via Cognito in Python
Convert from Markdown to HTML in Python
Get Precipitation Probability from XML in Python
Import Error in Python3: No module named'xxxxx'
Get metric history from MLflow in Python
Get time series data from k-db.com in Python
Quadtree in Python --2
Python in optimization
CURL in python
Metaprogramming in Python
Python 3.3 in Anaconda
Geocoding in python
SendKeys in Python
Meta-analysis in Python
Unittest in python
From file to graph drawing in Python. Elementary elementary
Epoch in Python
Discord in Python
ModuleNotFoundError: No module named'_bz2' error in pyenv Python
Sudoku in Python
DCI in Python
sql from python
quicksort in python
nCr in python
N-Gram in Python
Programming in python
Load and execute command from yml in python
Use Python in your environment from Win Automation
Plink in Python
Constant in python
MeCab from Python
Lifegame in Python.
FizzBuzz in Python
Sqlite in python
StepAIC in Python
Call a Python script from Embedded Python in C ++ / C ++
Create a datetime object from a string in Python (Python 3.3)
Load images from URLs using Pillow in Python 3