ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 파이썬으로 사용 중인 컴퓨터의 ip 찾기
    Python/이것저것 파이썬 2024. 1. 16. 21:34
    반응형

    파이썬으로 본인 컴의 아이피를 찾아보자. 

    import json
    import socket
    import urllib.request
    
    with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as sock:
        sock.connect(("8.8.8.8", 80))
        print('내부 :', sock.getsockname()[0])
    
    with urllib.request.urlopen('http://ip.jsontest.com') as response:
        html = response.read().decode()
        print('외부 :', json.loads(html)['ip'])

    ip.jsontest.com 가 없어지면 쓸 수 없는 코드..
    그렇다면 서버를 만들어 보자... 플라스크를 사용했다. 

    from flask import Flask, request, jsonify
    
    app = Flask(__name__)
    
    
    @app.route('/')
    def echo_ip():
        ip_addr = request.remote_addr
        return jsonify({'ip': ip_addr})
    
    
    @app.route('/client')
    def client():
        ip_addr = request.environ['REMOTE_ADDR']
        return jsonify({'ip': ip_addr})
    
    
    @app.route('/proxy_client')
    def proxy_client():
        ip_addr = request.environ.get('HTTP_X_FORWARDED_FOR', request.remote_addr)
        return jsonify({'ip': ip_addr})
    
    
    if __name__ == '__main__':
        app.run()

    https://stackabuse.com/how-to-get-users-ip-address-using-flask/

    장고로 만들어 보자..

    from django.http import JsonResponse
    
    
    def index(request):
        x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
        if x_forwarded_for:
            ip = x_forwarded_for.split(',')[0]
        else:
            ip = request.META.get('REMOTE_ADDR')
        return JsonResponse({'ip': ip})

    1시간에 한번 IP를 체크하고, 변화가 있으면 텔레그램으로 알려주는 프로그램을 작성해 보았다. 

    apscheduler는 pip로 설치하자.

    # check-ip, 2014.01.18, by comdoc 
    
    import json
    import logging
    import os
    import ssl
    from urllib import request, parse
    
    from apscheduler.schedulers.blocking import BlockingScheduler
    
    TELEGRAM_BOT_TOKEN = ''
    TELEGRAM_CHAT_ID = ''
    IP_FILE_PATH = "check_ip.json"
    ssl._create_default_https_context = ssl._create_unverified_context
    
    
    def get_current_ip():
        try:
            url = 'https://api64.ipify.org?format=json'
            req = request.Request(url)
            res = request.urlopen(req)
            decoded = res.read().decode("utf8")
            json_dict = json.loads(decoded)
            return json_dict['ip']
        except Exception as e:
            logging.error(f'Error getting IP address: {e}')
            return None
    
    
    def get_previous_ip():
        if os.path.exists(IP_FILE_PATH):
            with open(IP_FILE_PATH, 'r') as file:
                return json.load(file).get('ip')
        return None
    
    
    def save_current_ip(ip):
        with open(IP_FILE_PATH, 'w') as file:
            json.dump({'ip': ip}, file)
    
    
    def send_telegram_message(message):
        try:
            url = f'https://api.telegram.org/bot{TELEGRAM_BOT_TOKEN}/sendMessage'
            req = request.Request(url)
            data = {'chat_id': TELEGRAM_CHAT_ID, 'text': message}
            post_data = parse.urlencode(data).encode('UTF-8')
            res = request.urlopen(req, post_data)
            decoded = res.read().decode('UTF-8')
            json_dict = json.loads(decoded)
            if not json_dict.get('ok'):
                logging.error(json_dict.get('result'))
            else:
                logging.info(f"[telegram] date:{json_dict['result']['date']}, text:{json_dict['result']['text']}")
        except Exception as e:
            logging.error(f'Error sending message: {e}')
            return None
    
    def check_ip_changes():
        current_ip = get_current_ip()
    
        if current_ip:
            previous_ip = get_previous_ip()
            print(current_ip, previous_ip)
            logging.debug(f'{current_ip}, {previous_ip}')
            if current_ip != previous_ip:
                message = f'IP address has changed!\n\nPrevious IP: {previous_ip}\nCurrent IP: {current_ip}'
                send_telegram_message(message)
                save_current_ip(current_ip)
    
    
    if __name__ == '__main__':
    
        logging.basicConfig(filename="check_ip.log", level=logging.INFO)
    
        scheduler = BlockingScheduler()
        scheduler.add_job(check_ip_changes, 'interval', hours=1)
    
        try:
            print('Press Ctrl+C to exit')
            check_ip_changes()
            scheduler.start()
        except (KeyboardInterrupt, SystemExit):
            scheduler.shutdown()
    반응형
Designed by Tistory.