Last active
December 8, 2017 15:37
-
-
Save shellexy/6dd7362dfdef80dee3d4d37b565530fe to your computer and use it in GitHub Desktop.
wake on lan 远程唤醒计算机
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/usr/bin/python | |
| # -*- coding: utf-8 -*- | |
| # wol.py 远程唤醒计算机 | |
| # 参见 http://code.activestate.com/recipes/358449-wake-on-lan/ | |
| # https://github.com/bentasker/Wake-On-Lan-Python | |
| # 原作者 Fadly Tabrani, B Tasker,协议 PSF | |
| ## 可以改为自己需要远程唤醒的计算机的 MAC 地址 | |
| MACADDRESS = '00:13:0d:e4:60:61' | |
| ## 这个一般不用修改 | |
| BROADCAST = '192.168.1.255' | |
| import socket | |
| import struct | |
| import time | |
| import sys | |
| USAGE = '''Usage: | |
| wol.py [macaddress] [broadcast] Wake the remote computer, | |
| we can change the default macaddress in code, | |
| the default broadcast is 192.168.1.255 . | |
| wol.py -h Display this help and exit. | |
| ''' | |
| def wake_on_lan(macaddress, broadcast): | |
| """Switches on remote computers using WOL. """ | |
| # Check macaddress format and try to compensate. | |
| if len(macaddress) == 12: | |
| pass | |
| elif len(macaddress) == 12 + 5: | |
| sep = macaddress[2] | |
| macaddress = macaddress.replace(sep, '') | |
| else: | |
| raise ValueError('Incorrect MAC address format') | |
| # Pad the synchronization stream. | |
| data = ''.join(['FFFFFFFFFFFF', macaddress * 20]) | |
| send_data = b'' | |
| # Split up the hex values and pack. | |
| for i in range(0, len(data), 2): | |
| send_data = b''.join([send_data, struct.pack('B', int(data[i: i + 2], 16))]) | |
| # Broadcast it to the LAN. | |
| try: | |
| sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) | |
| sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1) | |
| sock.sendto(send_data, (broadcast, 7)) | |
| time.sleep(1) | |
| sock.sendto(send_data, (broadcast, 7)) | |
| time.sleep(1) | |
| sock.sendto(send_data, (broadcast, 7)) | |
| print("Done") | |
| except Exception as e: | |
| print(e) | |
| if __name__ == '__main__': | |
| if '-h' in sys.argv: | |
| print(USAGE) | |
| sys.exit(1) | |
| macaddress = sys.argv[1] if len(sys.argv) >= 2 else MACADDRESS | |
| broadcast = sys.argv[2] if len(sys.argv) >= 3 else BROADCAST | |
| print('wake_on_lan %s %s' % (macaddress, broadcast)) | |
| wake_on_lan(macaddress, broadcast) | |
| pass |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment