gpt4 book ai didi

python - 来自 WAN 外部的 WOL

转载 作者:行者123 更新时间:2023-11-28 17:52:59 25 4
gpt4 key购买 nike

不久前,我 [在 Google 的帮助下] 写了一个小的 WOL 脚本来打开我网络中的计算机。这是脚本:

exec /usr/bin/python -x "$0" "$@"
#
node_lst = [
'srv1 0a:1b:8c:0d:2e:7f',
'srv2 0A-0B-4C-8D-CE:3F',
]
#
import os,sys,string,commands
import struct, socket
import re,random

retval = 0

mac_addr = "mac_addr.txt"
X = '([a-zA-Z0-9]{2}[:|\-|.]?){5}[a-zA-Z0-9]{2}'
S = re.compile(r'\s+')

mmap = {}

## First argument 'None' in str.translate is new in 2.6.
## Previously, it was a string of 256 characters
if sys.version_info < (2, 6):
f1_arg = ''.join(chr(i) for i in xrange(256))
else:
f1_arg = None

## broadcast address
sysOS = "uname -s"
BSD = "ifconfig | grep -w broadcast | cut -d\ -f 6"
LNX = "ip -o addr show | grep -w inet | grep -e eth | cut -d\ -f 9"
#
if commands.getoutput(sysOS) == "Linux":
bCast = commands.getoutput(LNX)
elif commands.getoutput(sysOS) == "Darwin":
bCast = commands.getoutput(BSD)
else:
print "System not supported!!"
sys_exit()

def WakeOnLan(mac_address):

## Building the Wake-On-LAN "Magic Packet"...
## Pad the synchronization stream.
data = ''.join(['FFFFFFFFFFFF', mac_address * 20])
msg = ''

## Split up the hex values and pack.
for i in range(0, len(data), 2):
msg = ''.join([msg, struct.pack('B', int(data[i: i + 2], 16))])

## ...and send it to the broadcast address using UDP
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
s.sendto(msg, (bCast, 9))
s.close()

def sys_exit():
sys.stdout.flush()
sys.exit(1)

## check if hostname is provided
if len(sys.argv) != 2:
print "Usage: %s <hostname>" % sys.argv[0]
sys_exit()

for i in node_lst:
# strip off everything from first "#" [if] found
i = i.split('#',1)[0]
if not re.search(X, i):
continue

h = S.split(i,1)[0] ## host name
m = S.split(i,1)[-1] ## MAC address
mmap[h] = m.strip('\t|" "')

for j, k in mmap.iteritems():
if sys.argv[1] == j:
if not re.search(X.replace('zA-Z','fA-F'), k):
print "Invalid MAC address [",k,"]; nothing to do!!"
sys_exit()
else:
WakeOnLan(k.translate(f1_arg,':.-'))
print "WOL request has been sent to %s [%s]" % (j,k)
break
else:
print "Host [%s] doesn't exist!!" % sys.argv[1]
sys_exit()

这在我的家庭网络(或 LAN)中工作得很好。我如何更改脚本以使其适用于我的 LAN 外部?有什么想法或建议吗?干杯!

最佳答案

这是不可能的,因为 WOL 数据包是广播数据包(因为您也不知道向谁发送)。家用路由器,尤其是 ISP/网络路由器会丢弃所有广播数据包,因为否则每次您运行这个脚本时,整个互联网上的所有计算机都会收到您的数据包,这会造成相当大的困惑。

当然,您可以在 WAN 内运行的计算机上编写一个小应用程序,您希望打开其中的所有计算机,然后让该应用程序发送 WOL 数据包。但是,这需要始终打开可以访问互联网的计算机。

关于python - 来自 WAN 外部的 WOL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6324198/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com