Skip to content

Instantly share code, notes, and snippets.

@Wegazz
Created April 12, 2021 13:32
Show Gist options
  • Save Wegazz/bf6ec1000344ea39ee5a4649674416c0 to your computer and use it in GitHub Desktop.
Save Wegazz/bf6ec1000344ea39ee5a4649674416c0 to your computer and use it in GitHub Desktop.
Ping server from python and ping. Parse ttl from ping
import subprocess
import platform
import re
class ping():
server = 'ya.ru'
verbose = False
def __init__(self, server: str = 'ya.ru', verbose: bool = False):
ping.server = server
ping.verbose = verbose
@classmethod
def __run_in_shell(
cls,
adress_of_server: str
) -> str:
""" Run command and get it's output
out - разобрать регуляркой.
возвращает ответ пинга.
"""
adress_of_server = adress_of_server or ping.server
ping_str = "-n" if platform.system().lower() == "windows" else "-c"
shell_command = f'ping {ping_str} 1 {adress_of_server}'
process = subprocess.Popen(
shell_command,
shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE
)
out, err = process.communicate()
out = out.decode("cp866").strip()
err = err.decode("cp866").strip()
if ping.verbose:
if len(err) > 0:
print(f'Err: {err}')
if len(out) > 0:
print(f'Out: {out}')
if not process.returncode:
return out
else:
if len(err) > 0:
return False
if len(out) > 0:
return out
@classmethod
def ttl(cls, adress_of_server: str = None) -> int:
"""
Функция, которая пингует выбаный сервер.
adress_of_server (по умолчанию ya.ru) - google.com или 192.168.1.1
Если он отвечат то ворвращает его TTL
Иначе возвращает int 0
При ошибке возвращает False
"""
res = cls.__run_in_shell(adress_of_server)
if res:
# print(f'Out: {out}')
pattern = re.compile(r'[t,T][t,T][l,L]=\d*')
ttl_call = pattern.search(str(res))
# print(ttl_call)
if ttl_call is not None:
ttl_group = ttl_call.group() # вывод "TTL=64"
# регулярка получает только цифры вывод "64"
result_ttl = re.findall(r'\d+', ttl_group)
return int(result_ttl[0])
else:
return int(0)
return False
@classmethod
def it(cls, adress_of_server: str = None) -> bool:
""" упрощенный пинг
Если сервер отвечает -> True
Если сервер Не отвечает -> None
Ошибка -> False
"""
res = cls.ttl(adress_of_server)
if res > 0:
return True
elif res == 0:
return None
else:
return res
if __name__ == "__main__":
print(ping.it('192.168.1.20'))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment