python

python netstat + telnet test

MasterOfAI 2020. 12. 28. 12:46

Goal:

1. 내 PC는 DHCP Server 이고, IP address 는 169.254.0.100 임
2. 내 PC에 DHCP Client 형태로 169.254.0.1 ~ 99 까지의 client PC들이 연결 될수 있음
3. 현재 어떤 것이 연결되었는지 , 어떤 것이 안되었는지는 알수 없는 상황
4. Server PC의 운영체제는 Windows 7 이고 client PC들은 운영체제가 Linux 임
5. 이 경우 연결된 모든 client 들을 찾아서 , login 한 후 "reboot" 이라는 linux command 를 날려 client 들을 재 부팅 시키는 python code 를 만들어라. 

 

Code:

 

import telnetlib

import subprocess

import re

 

# netstat 를 통해 연결된 모든 PB들의 ip address 를 획득 

print("Geting the netstat information it will take some time")

remote_list = []

# 아래와 같이, netstat 로 부터 console 에 출력 되는 결과를 result 에 담을 수 있다. 

outerr = subprocess.Popen("netstat"stdout=subprocess.PIPE).communicate() 

result = out.splitlines()

for line in result:

    line = line.decode('utf-8')

    result = re.findall("169.254.0.\d+",line)

    if len(result)>1:

        remote_list.append(result[1])

 

# 중복제거

my_set = set(remote_list

remote_list = list(my_set

 

# telnet 접속 및 reboot 실행 

for host in remote_list:

    tn = telnetlib.Telnet(host)

    # login string 은 장비 마다 다르니 변경 필요

    response = tn.read_until(b"ibir login: ")

    # login name 역시 변경 필요

    tn.write(b"root\n")

    tn.read_until(b"Password: ")

    # password 역시 장비마다 다르니 변경 필요

    tn.write(b"tanisys\n")

    tn.write(b"reboot\n")

    tn.write(b"exit\n")

    print(tn.read_all().decode('ascii'))

 

'python' 카테고리의 다른 글

Python 정규 표현식  (0) 2021.05.21
raise  (0) 2021.01.12
python ping + telnet test  (0) 2020.12.28
Python Number  (0) 2020.12.15
Python Data Type  (0) 2020.12.14