吾爱破解 - LCG - LSG |安卓破解|病毒分析|www.52pojie.cn

 找回密码
 注册[Register]

QQ登录

只需一步,快速开始

查看: 596|回复: 7
收起左侧

[已解决] py写的PING通IP向其发送指令,有点小问题,求助

[复制链接]
ilovejay88 发表于 2024-4-28 20:49
本帖最后由 ilovejay88 于 2024-4-28 21:30 编辑

各位大神好,帮小弟看下这段代码,我这段代码是想当某个IP通时,向其UDP发送一个指令,然后为了后期增加IP或者修改IP方便,我把IP文本做在INI文件中用来读取,但是似乎在读取过程中出现问题,能帮我分析下吗,感激不尽

import os
import time
import datetime
import socket
import configparser
from subprocess import Popen, PIPE, call

# 存储已ping通的IP地址
pinged_ips = []

# 读取配置文件的路径
CONFIG_FILE = "config.ini"

# 如果配置文件不存在,则创建一个空的配置文件
if not os.path.exists(CONFIG_FILE):
    with open(CONFIG_FILE, 'w') as f:
        f.write("[ip_commands]\n")  # 写入节
        f.write("10.111.96.202:23 = \\x04\n")  # 写入键值对
        f.write("10.111.96.203:23 = \\x05\n")  # 写入键值对
        f.write("10.111.96.204:23 = \\x06\n")  # 写入键值对
        f.write("\n")  # 空行
        f.write("[shutdown]\n")  # 写入节
        f.write("time = 23:00\n")  # 写入键值对

# 创建ConfigParser对象
config = configparser.ConfigParser()

# 读取INI文件
config.read(CONFIG_FILE)

# 获取IP地址和指令
ip_commands = dict(config.items('ip_commands'))
shutdown_time = config.get('shutdown', 'time')

# 延迟10
time.sleep(10)

# 获取当前时间
def get_current_time():
    return datetime.datetime.now().strftime('%H:%M')

# 发送UDP数据包
def send_udp_command(ip, port, command):
    try:
        with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as sock:
            server_address = (ip, int(port))
            sock.sendto(command.encode(), server_address)
            print(f"{ip}:{port} 已发送开机指令")
    except Exception as e:
        print(f"发送数据到 {ip}:{port} 时出错: {str(e)}")

# 主循环
while True:
    current_time = get_current_time()
    if current_time >= shutdown_time:
        print("到达预设关闭时间,程序即将退出。")
        os._exit(0)  # 安全退出程序

    for key, command in ip_commands.items():
        ip, port = key.split(':')
        if ip not in pinged_ips:
            # 尝试ping IP地址
            try:
                response = call(['ping', '-n', '1', ip], stdout=PIPE, stderr=PIPE)
                if response == 0:  # ping成功
                    pinged_ips.append(ip)
                    send_udp_command(ip, port, command)
                    # 根据IP打印特定的启动信息
                    if ip == "10.111.92.202":
                        print("6号厅还音柜启动")
                    elif ip == "10.111.96.114":
                        print("2号厅启动")
                    elif ip == "10.111.96.115":
                        print("3号厅启动")
                    time.sleep(2)  # 等待2
            except Exception as e:
                print(f"尝试ping {ip} 时出错: {str(e)}")

    time.sleep(60)  # 主循环等待60




下面是INI中的文本。
[ip_commands]
10.111.96.202:23 = \x04
10.111.96.203:23 = \x05
10.111.96.204:23 = \x06

[shutdown]
time = 23:00


Python运行调试报错
ValueError: not enough values to unpack (expected 2, got 1)

发帖前要善用论坛搜索功能,那里可能会有你要找的答案或者已经有人发布过相同内容了,请勿重复发帖。

devilpanama 发表于 2024-4-28 21:09
[Python] 纯文本查看 复制代码
{'10.111.96.202': '23 = \\x04', '10.111.96.203': '23 = \\x05', '10.111.96.204': '23 = \\x06'}

字典值不对吧
 楼主| ilovejay88 发表于 2024-4-28 21:13
devilpanama 发表于 2024-4-28 21:09
[mw_shl_code=python,true]{'10.111.96.202': '23 = \\x04', '10.111.96.203': '23 = \\x05', '10.111.96.2 ...

请大神明示。。。
thepoy 发表于 2024-4-28 21:27
本帖最后由 thepoy 于 2024-4-28 21:29 编辑

最重要的不是代码,而是报错信息。

啥年代还用 ini 啊,换 toml 吧。

没用过 ini 解析器,看着像是解析器的问题,但你这么点配置不如自己写一个简单的解析器。

或者如果你用的是 windows 的话,你可以试试把"\n"换成"\r\n"试试。
 楼主| ilovejay88 发表于 2024-4-28 21:31
thepoy 发表于 2024-4-28 21:27
最重要的不是代码,而是报错信息。

啥年代还用 ini 啊,换 toml 吧。

ValueError: not enough values to unpack (expected 2, got 1)

报错就是报的这个
换行符的问题?
FitContent 发表于 2024-4-28 21:33

默认情况下,.ini 文件把符号 : 也视为 key、value 的分割符,也就是说:下面的两种语法都是可以的。

key1 = value1
key1 : value1

而写入的 ip 地址中包含了符号 :,所以 xxx:yy = zz 被解释为 xxx 和 yy = z 这两个部分了。

具体可以见官方的文档configparser — Configuration file parser — Python 3.12.3 documentation,在 Supported INI File Structure 小节中说明。

解决方法就是:指明使用 = 作为分割符,修改如下代码即可

config = configparser.ConfigParser(delimiters=('='))

免费评分

参与人数 1吾爱币 +1 热心值 +1 收起 理由
ilovejay88 + 1 + 1 谢谢@Thanks!

查看全部评分

 楼主| ilovejay88 发表于 2024-4-28 21:49
FitContent 发表于 2024-4-28 21:33
[md]默认情况下,`.ini` 文件把符号 `:` 也视为 `key、value` 的分割符,也就是说:下面的两种语法都是可以 ...

感谢老大,解决了我的问题。谢谢
devilpanama 发表于 2024-4-28 21:49
你要的字典应该是key='10.111.96.202: 23'  value='\\x04',但是读取时变成key='10.111.96.202' value= '23 = \\x04'
您需要登录后才可以回帖 登录 | 注册[Register]

本版积分规则 警告:本版块禁止回复与主题无关非技术内容,违者重罚!

快速回复 收藏帖子 返回列表 搜索

RSS订阅|小黑屋|处罚记录|联系我们|吾爱破解 - LCG - LSG ( 京ICP备16042023号 | 京公网安备 11010502030087号 )

GMT+8, 2024-5-14 22:17

Powered by Discuz!

Copyright © 2001-2020, Tencent Cloud.

快速回复 返回顶部 返回列表