PythonTip >> 博文 >> chinaunix

简单python脚本(判断是否为家庭网络,是则自动拨号到公司)

zihua 2014-01-13 18:01:33 点击: 853 | 收藏


很简单的一个脚本,就是开机时判断是不是在家庭网络中,如果是就自动拨号到公司

练习下python代码而已
代码中关于怎么获取本机IP的方法可以参考:http://blog.chinaunix.net/uid-8874157-id-3890771.html


点击(此处)折叠或打开

  1. #!/usr/bin/env python
  2. #coding:utf-8
  3. # Author: Edward --<edgeman_03@163.com>
  4. # Purpose: 判断是否为家庭网络环境,如果是,则自动启动OPENVPN服务连接至公司
  5. # Created: 2013年09月08日

  6. import os
  7. import sys
  8. import socket

  9. def get_my_ip():
  10.     """
  11.     Returns the actual ip of the local machine.
  12.     This code figures out what source address would be used if some traffic
  13.     were to be sent out to some well known address on the Internet. In this
  14.     case, a Google DNS server is used, but the specific address does not
  15.     matter much. No traffic is actually sent.
  16.     """
  17.     try:
  18.         csock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
  19.         csock.connect(('8.8.8.8', 80))
  20.         (addr, port) = csock.getsockname()
  21.         csock.close()
  22.         return addr
  23.     except socket.error:
  24.         return "127.0.0.1"

  25. def main():
  26.     if "192.168.1" in get_my_ip():
  27.         os.system('sudo service openvpn restart')
  28.         #print "starting openvpn services ok!"
  29.     else:
  30.         sys.exit()

  31. if __name__=='__main__':
  32.     main()

再来一个windows下面的版本,方式差不多,只是程序用的是openvpn-gui的客户端
另外为使客户端连接时不提示对话框,静默连接,需修改注册表
修改位置: HKEY_LOCAL_MACHINE\SOFTWARE\OpenVPN-GUI ,修改 silent_connection 值为 1
代码如下:

点击(此处)折叠或打开

  1. #!/usr/bin/env python
  2. #coding:utf-8
  3. # Author: Edward -- <edgeman_03@163.com>
  4. # Purpose: 判断是否为家庭网络环境,如果是,则自动启动OPENVPN服务连接至公司
  5. # Created: 2013/9/9

  6. import sys
  7. import os
  8. import socket
  9. import time

  10. def get_my_ip():
  11.     """
  12.     Returns the actual ip of the local machine.
  13.     This code figures out what source address would be used if some traffic
  14.     were to be sent out to some well known address on the Internet. In this
  15.     case, a Google DNS server is used, but the specific address does not
  16.     matter much. No traffic is actually sent.
  17.     """
  18.     try:
  19.         csock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
  20.         csock.connect(('8.8.8.8', 80))
  21.         (addr, port) = csock.getsockname()
  22.         csock.close()
  23.         return addr
  24.     except socket.error:
  25.         return "127.0.0.1"

  26. def main():
  27.     time.sleep(10)
  28.     if "192.168.1" in get_my_ip():
  29.         os.chdir(r"C:\Program Files\OpenVPN\bin")
  30.         os.popen('openvpn-gui.exe --connect hq-udp-1196.ovpn')
  31.     else:
  32.         sys.exit()

  33. if __name__=='__main__':
  34.     main()



原文链接:http://blog.chinaunix.net/uid-8874157-id-3890775.html

作者:zihua | 分类: chinaunix | 标签: python | 阅读: 853 | 发布于: 2014-01-13 18时 |