最近TeamViewer不能正常使用(检测到商业用途,无法启动新的会话;又想骗我去用商业付费版),家里宽带的公网IP是动态分配的,远程很不方便。为摆脱被不能远程支配的恐惧,我使用python编写了一个脚本来获取动态的IP地址,并利用windows服务来管理。

在这里碰到了一些坑,一起来了解一下。

(这里也可以不用创建windows服务,直接设置任务计划定期执行脚本就行,只是执行的时候会有一个小黑窗弹出来,可以将脚本打包为exe文件并屏蔽黑窗)

创建Windows服务

1.python实现windows服务需要借助第三方库pywin32

pip install pywin32

2.这里先来一段简单的创建服务的代码(Create_WindowsService.py),暂不涉及功能

import win32serviceutil
import win32service
import win32event
import timeclass PythonService(win32serviceutil.ServiceFramework):_svc_name_ = "Send IP"                              # 服务名_svc_display_name_ = "Send IP"                      # 服务在windows系统中显示的名称_svc_description_ = "Send My Computer IP to me"     # 服务的描述def __init__(self, args):win32serviceutil.ServiceFramework.__init__(self, args)self.hWaitStop = win32event.CreateEvent(None, 0, 0, None)self.run = Truedef SvcDoRun(self):while self.run:# 功能函数()time.sleep(60)def SvcStop(self):self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)win32event.SetEvent(self.hWaitStop)self.run = Falseif __name__ == '__main__':win32serviceutil.HandleCommandLine(PythonService) 
    这段代码中PythonService类继承了win32serviceutil.ServiceFramework类,初始化后系统服务开始启动,并调用函数SvcDoRun。由于属性self.run为真,因此SvcDoRun函数不会停止,直到我们触发停止服务,调用SvcStop函数,属性self.run被赋予假,循环跳出,windows服务停止。我们需要实现的功能也就放在该循环中。

3.这里是一些创建服务命令,当然我们也可以安装后直接在windows服务里进行操作

#1.安装服务
python Create_WindowsService.py install#2.让服务自动启动
python Create_WindowsService.py --startup auto install #3.启动服务
python Create_WindowsService.py start#4.重启服务
python Create_WindowsService.py restart#5.停止服务
python Create_WindowsService.py stop#6.删除/卸载服务
python Create_WindowsService.py remove

4.这里可能会遇到一些问题,简单说下我遇到的一些

(1)首先,在cmd下操作以上命令,如安装服务 python Create_WindowsService.py install时,报错:拒绝服务

这是因为cmd需要管理员权限(我使用的不是administrator用户),很简单,开始——cmd——右键 以管理员身份运行

(2)出现 “1063 服务没有及时响应启动或控制请求” 类型的错误

将安装目录Python3\Lib\site-packages\win32路径下的pythonservice.exe注册一下。

这需要win32目录下有pywintypes36.dll文件,或者有该文件的环境变量

复制Python36\Lib\site-packages\pywin32_system32\pywintypes36.dll到Python3\Lib\site-packages\win32下

最后,注册命令:pythonservice.exe /register

可能会报sys.winver数据类型的错误,不会有影响,可以查看下该值,是字符型(版本号)

实现获取动态IP并发送至手机

这里采用的是把获取的IP发送到手机钉钉(也可以短信或邮件、微信等),以方便随时查看。

1.使用钉钉创建一个群聊或者团队,添加自定义机器人,复制机器人地址,之后调用api接口就可以通过机器人发送信息。

def message(text):headers = {'Content-Type': 'application/json;charset=utf-8'}api_url = "你的机器人webhok地址"json_text = {"msgtype": "text","at": {"atMobiles": [“可以添加你的手机号,机器人会@你”],"isAtAll": False},"text": {"content": text}}response_code = requests.post(api_url, json.dumps(json_text), headers=headers).status_codeprint(response_code)

2.获取你的公网IP地址

def get_public_ip():url = "https://ip.cn/"headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) ""AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36"}try:response = requests.get(url, headers=headers)flag_num = 0public_ip = Nonewhile flag_num < 3:if response.status_code == 200:public_ip = re.search('\d+\.\d+\.\d+\.\d+', str(response.text)).group()breakelse:flag_num += 1return public_ipexcept Exception as e:return None

3.定义一个属性,获取并赋予其公网ip值,如果ip变化,则更新类变量的值(每次服务停止后,该属性会重新初始化)

def __init__(self, args):…………# 定义属性self.local_ip = None

4.下面给出完整代码(最新升级版)

import datetime
import requests
import re
import json
import win32serviceutil
import win32service
import win32event
import timedef get_public_ip():url = "https://ip.cn/"headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) ""AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36"}try:response = requests.get(url, headers=headers)flag_num = 0public_ip = Nonewhile flag_num < 3:if response.status_code == 200:public_ip = re.search('\d+\.\d+\.\d+\.\d+', str(response.text)).group()breakelse:flag_num += 1return public_ipexcept Exception as e:return Nonedef message(text):headers = {'Content-Type': 'application/json;charset=utf-8'}api_url = "https://oapi.dingtalk.com/robot/send?" \"access_token=你的机器人webhok地址"json_text = {"msgtype": "text","at": {"atMobiles": [],"isAtAll": False},"text": {"content": text}}try:response_code = requests.post(api_url, json.dumps(json_text), headers=headers).status_codeprint(response_code)except Exception as e:print("Send Message to DingDing failed!")print(e)class PythonService(win32serviceutil.ServiceFramework):_svc_name_ = "Send IP"  # 服务名_svc_display_name_ = "Send IP"  # 服务在windows系统中显示的名称_svc_description_ = "Send My Computer IP to me"  # 服务的描述def __init__(self, args):win32serviceutil.ServiceFramework.__init__(self, args)self.hWaitStop = win32event.CreateEvent(None, 0, 0, None)self.run = Trueself.local_ip = Nonedef SvcDoRun(self):while self.run:try:t_number = datetime.datetime.now().strftime('%M%S')# 每小时0分、30分检测一次ip变化if t_number == "0000" or t_number == "3000":IP = get_public_ip()if self.local_ip != IP:self.local_ip = IPmessage(IP)except Exception as e:print(e)time.sleep(1)  # 不加此延迟会占用很高的cpudef SvcStop(self):self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)win32event.SetEvent(self.hWaitStop)self.run = Falseif __name__ == '__main__':try:win32serviceutil.HandleCommandLine(PythonService)except Exception as e:print(e)

Python 编写 Windows 服务,实时发送动态IP至手机相关推荐

  1. C++语言编写windows服务

    C++语言编写windows服务 1 windows服务 2 DebugView调试工具 3 c语言编写windows服务 4 将程序作为windows服务 1. windows服务 通过快捷键&qu ...

  2. python写一个服务_写一个Python的windows服务

    1. 安装pywin32和pyinstaller pip install pywin32 pip install pyinstaller 2.写一个服务Demo # -*- coding: utf-8 ...

  3. python开发服务程序_Python 编写Windows服务程序:将Python作为Windows服务启动 | 学步园...

    Python程序作为Windows服务启动,需要安装pywin32包.下载路径: #-*- coding:utf-8 -*- import win32serviceutil import win32s ...

  4. python实现阿里云域名绑定动态IP

    一般家庭网络的公网IP都是不固定的,而我又想通过域名来访问自己服务器上的应用,也就是说:需要通过将域名绑定到动态IP上来实现这个需求.于是乎,我开始探索实现的技术方案.通过在网上查阅一系列的资料后,发 ...

  5. python打包windows服务 开机自启动守护进程

    自启动方法一:系统自启动 设置python程序开机自启动 1.创建一个xxx.bat文件,右键编辑 2.在xxx.bat文件里面写入以下内容后保存:(可以按照如下流程自己去cmd中测试一下) d: # ...

  6. vs编写windows服务和调用webservice

    调用timer不能用 System.Windows.Forms.Timer而应该用System.Timers.Timer System.Timers.Timer t = new System.Time ...

  7. 编写Windows服务程序,将Python作为Windows服务启动

    首先需要安装两个模块. pip install pywin32 -i https://pypi.tuna.tsinghua.edu.cn/simplepip install pyinstaller - ...

  8. python 打包windows服务 开机自启动

    服务的优势就在于可以开机自启动 而在windows上,python不能直接将脚本注册为服务,需要将其先打包成exe,再将exe注册为服务 打包exe 使用pyinstaller打包,安装好pyinst ...

  9. 【使用Python编写一个访问实时股票数据的工具】包括获取股票信息、与数据库交互等

    访问股票信息工具 整体思路 访问股票信息的接口 数据库以及表结构 简单的界面设计 功能说明 这里给大家介绍一下,当时初学几天python时写的一个小工具,访问实时股票信息,之前用java写过一个模拟股 ...

最新文章

  1. 6-5-树的双亲表示法-树和二叉树-第6章-《数据结构》课本源码-严蔚敏吴伟民版...
  2. cmyk图像处理matlab,数字图像处理及MATLAB实现 全套课件.pptx
  3. 在离线环境中安装Visual Stuido 2017
  4. Linux块设备驱动总结
  5. 递归的效率问题及递归与循环比较
  6. ctf.360.cn第二届,逆向部分writeup——第三题
  7. 详解数字电视机顶盒的功能技术与应用3
  8. 蓝桥杯 ADV-70 算法提高 冒泡法排序
  9. 自学python好找工作么-非计算机专业自学Python好找工作吗?
  10. linux鸟叔的私房菜txt,鸟哥的Linux私房菜(pdf+epub+mobi+txt+azw3)
  11. The APR based Apache Tomcat Native library which allows optimal performance in production environmen
  12. Java JavaScript BOM和正则表达式
  13. 计算机一级如何启动ie浏览器,ie,详细教您怎么解决ie浏览器打不开的问题
  14. vs程序出错运行上次的成功的exe
  15. 摩拜创始人套现15亿:你的同龄人,正在抛弃你+韩寒回应
  16. 结构光学习 | 波前重构技术
  17. java io 阻塞io_Java 阻塞IO-Java BIO-嗨客网
  18. ios系统判断设备上是否有安装某app
  19. 用外业精灵完成施工前(光缆、电缆、拆迁)相关的踏勘-点位采集
  20. kali-Firefox安装flash插件

热门文章

  1. 3-Tensorflow-demo_02-变量_占位符_feeddict使用
  2. Substance Painter(SP)如何打开FBX和OBJ文件
  3. 想转行做IT,不知道能不能行?我给你个栗子,但可以不吃
  4. 外贸开发信 html,7个回复率极高的外贸开发信邮件模板
  5. 单纯形法;大M法;两阶段法
  6. 软件测试之——关于APP弱网测试
  7. 分享四个非常方便的二维码生成链接
  8. cmd快速进入某个文件夹
  9. 插件测评:体验最新版 CSDN 浏览器助手,希望能够一起变得更好
  10. JAVA程序连连看的项目总结,JAVA课程设计连连看游戏的开发