用python让每只狗都有它的IP地址

文章介绍了一个用Python编写的程序,该程序在RaspberryPi启动时通过I2C在WaveshareOLED显示器上显示其IP地址,方便在网络中寻找和SSH连接,避免了在大量设备中查找动态分配IP的麻烦。程序可以在/etc/rc.local中设置,以便每次启动时自动运行。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

我们正在对我们的Petoi机器进行大型兽医手术.

但是我们所做的一件事应该有更广泛的应用,那就是这个。当您有一个刚刚位于您的网络上并通过 SSH 访问的 Raspberry Pi 时,它的 IP 地址并不明显,特别是如果像我们一样,您的本地网络上有超过 100 台设备。因此,我们编写了一个小的Python程序,在启动时使用I2C在其中一个小型,廉价的Waveshare OLED显示器上显示IP地址:

现在,您不必登录到网络集线器并在每次启动时搜索Pi动态分配的地址(是的 - 我们知道我们可以在集线器上为其保留静态地址,但是您保留的地址越多,当未使用保留的设备时,可用的地址就越少)。

请参阅上面的 Waveshare 链接来安装您需要的 OLED 库,将这个 Python 程序放在 Pi 上的某个地方并称之为 display-ip.py:

import socket
import sys
import os
picdir = os.path.join(os.path.dirname(os.path.dirname(os.path.realpath(__file__))), 'pic')
libdir = os.path.join(os.path.dirname(os.path.dirname(os.path.realpath(__file__))), 'lib')
if os.path.exists(libdir):
    sys.path.append(libdir)

import traceback
from waveshare_OLED import OLED_0in91
from PIL import Image,ImageDraw,ImageFont

try:
    disp = OLED_0in91.OLED_0in91()
    # Initialize library.
    disp.Init()
        
    # Clear display.
    disp.clear()

    # Create blank image for drawing.
    image1 = Image.new('1', (disp.width, disp.height), "WHITE")
    draw = ImageDraw.Draw(image1)
    font1 = ImageFont.truetype(os.path.join(picdir, 'Font.ttc'), 12)
    #Get IP
    host_name = socket.gethostname()
    ip = "IP: " + socket.gethostbyname(host_name + ".local")
    draw.text((20,0), ip, font = font1, fill = 0)

    image1=image1.rotate(0) 
    disp.ShowImage(disp.getbuffer(image1))

except IOError as e:
    logging.info(e)
    
except KeyboardInterrupt:    
    OLED_0in91.config.module_exit()
    exit()

然后在 /etc/rc.local 的底部添加以下内容:

sudo python3 /path/to/where/that/program/is/display-ip.py > /dev/null &

而且每次启动时,您都可以直接通过SSH连接到Pi。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值