在使用下面 python script 前, 確認你有安裝 vpnc (VPN connector) 與 Python 的 pexpect (A Python module for controlling interactive programs in a pseudo-terminal) 套件.
Install vpnc on CentOS
1. 根據平台下載適當的 vpnc 的 rpm 檔, 如果是 CentOS 64bits, 這邊是使用 vpnc-0.5.3-1.el5.rf.x86_64.rpm
2. 進行安裝, 如果是 CentOS 則使用 yum 命令:
Install pexpect 套件
1. 直接下載套件並使用 setup.py 進行安裝.
2. 透過 pip 命令安裝:
Auto-login VPNC Script
下面的 Python 代碼會自動幫你透過 vpnc 登入 virtual private network. 整個 script 進行三件事:
- login.py
- #!/usr/bin/python
- import subprocess, os, sys, time
- from subprocess import Popen
- from subprocess import PIPE
- import pexpect
- VPNC_PATH="/sbin/vpnc"
- VPNC_HOST="xxx.xxx.xxx.xxx"
- IPSec_ID="xxx"
- IPSec_secret="xxx"
- AUTH_UN="username"
- AUTH_PW="password"
- proc = Popen(["ps", "aux"], stdout=PIPE)
- proc2 = Popen(["grep", "vpnc"], stdin=proc.stdout, stdout=PIPE)
- proc.stdout.close()
- proc3 = Popen(["grep", "-v", "grep"], stdin=proc2.stdout, stdout=PIPE)
- proc2.stdout.close()
- output = proc3.communicate()[0].strip().split()
- if len(output) > 0:
- print "\t[Info] VPNC is already running with PID={0}!\n".format(output[5])
- exit(0)
- # 1) Start VPNC login
- fout = open('loginVPN.log','w')
- child = pexpect.spawn("{0}".format(VPNC_PATH))
- child.logfile = fout
- child.expect("Enter IPSec gateway address:")
- child.sendline(VPNC_HOST)
- child.expect("Enter IPSec ID for")
- child.sendline(IPSec_ID)
- child.expect("Enter IPSec secret for")
- child.sendline(IPSec_secret)
- child.expect("Enter username for")
- child.sendline(AUTH_UN)
- child.expect("Enter password for")
- child.sendline(AUTH_PW)
- index = child.expect(["VPNC started in background", "Password for VPN", pexpect.EOF, pexpect.TIMEOUT])
- if index == 0:
- print("Login VPN successfully!")
- elif index == 1:
- print("Wrong seting!")
- elif index == 2:
- print("Unknown error!")
- else:
- print("Timeout!")
- fout.close()
Supplement
* Python 套件管理程式簡介
* Pexpect module API
* [ Python 範例代碼 ] 利用 ps 與 grep 找出 processes 並將之 kill
沒有留言:
張貼留言