分类 【编程开发】 下的文章

自动登录深信服上网控制-golang版本

因为电脑挂了,造成之前所写的python版本的认证小程序也没有环境执行了,所以改用golang写了一版,胜在不依赖于任何环境,我也懒得装python了,就这样挺好,虽然编译出来有点大(7M多),但是可以拷贝到哪都可以直接执行

package main

import (
    "crypto/tls"
    "fmt"
    "io/ioutil"
    "net"
    "net/http"
    "net/url"
    "strings"
    "time"

    "github.com/axgle/mahonia"
)

var MacMap = map[string]string{
    // wzp_important虚拟机
    "10.20.38.16": "00:50:56:af:0e:a1",
    // PC11276
    "10.20.38.172": "2c:27:d7:26:fe:75",
    // DELL XPS15
    "10.20.38.25": "14:fe:b5:a3:d5:39",
    // LVS_test虚拟机
    "10.20.38.59": "00:50:56:af:5f:a0",
}

func Contains(s, substr string) bool {
    return strings.Index(s, substr) != -1
}

func mac() string {
    // 获取本机的MAC地址
    var result string
    interfaces, err := net.Interfaces()
    if err != nil {
        panic("Error : " + err.Error())
    }
    for _, inter := range interfaces {
        mac := inter.HardwareAddr //获取本机MAC地址
        result = strings.TrimSpace(mac.String())
        if len(result) > 0 {
            break
        }

    }
    //fmt.Println("MAC: ", result)
    return result
}

func checkMac(mac string) bool {
    result := false
    if len(mac) <= 0 {
        return false
    }
    mac = strings.TrimSpace(mac)
    for _, v := range MacMap {
        if strings.EqualFold(v, mac) {
            result = true
        }
    }
    return result
}

func NetAuth() {
    tr := &http.Transport{
        TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
    }
    // 定义配置信息
    resultURL := "https://深信服IP/cgi-bin/showflux.cgi"
    username := "用户名"
    password := "密码"
    authURL := "http://深信服IP/webAuth/"

    // 验证是否认证
    reqest, err := http.NewRequest("GET", resultURL, nil)
    if err != nil {
        fmt.Println("请求是否验证信息构造失败!")
        panic(err)
    }

    reqest.Header.Set("Content-Type", "application/x-www-form-urlencoded; param=value")
    reqest.Header.Add("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8")
    reqest.Header.Add("Accept-Encoding", "gzip, deflate")
    reqest.Header.Add("Accept-Language", "zh-cn,zh;q=0.8,en-us;q=0.5,en;q=0.3")
    reqest.Header.Add("Connection", "keep-alive")
    reqest.Header.Add("Host", authURL)
    reqest.Header.Add("Referer", authURL)
    reqest.Header.Add("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:12.0) Gecko/20100101 Firefox/12.0")
    client := &http.Client{Transport: tr}
    response, err := client.Do(reqest)
    if err != nil {
        fmt.Println("请求是否验证信息构造失败!", err)
        panic(err)
    }
    body, err := ioutil.ReadAll(response.Body)
    if err != nil {
        fmt.Println("读取深信服返回报文(是否验证)错误!")
        panic(err)
    }
    stringBody := string(body)
    // 字符集转化
    bodyStr := mahonia.NewDecoder("gbk").ConvertString(stringBody)
    // 关闭request,防止EOF错误
    reqest.Close = true

    //fmt.Println(bodyStr)
    if Contains(bodyStr, "未登录") {
        // 尚未认证,开始认证
        v := url.Values{}
        v.Set("username", username)
        v.Add("password", password)
        v.Add("rememberPwd", "1")
        v.Add("pwd", password)
        v.Add("secret", "true")

        reqest, err = http.NewRequest("POST", authURL, strings.NewReader(v.Encode()))

        if err != nil {
            fmt.Println("请求验证信息构造失败!")
            panic(err)
        }

        response, err = client.Do(reqest)

        if err != nil {
            fmt.Println("请求深信服认证错误!")
            panic(err)
        }

        body, err = ioutil.ReadAll(response.Body)
        fmt.Println(time.Now().Format("2006-01-02 15:04:05"), "未认证,认证成功!")
        if err != nil {
            fmt.Println("读取深信服返回报文错误!")
            panic(err)
        }

        //fmt.Println(string(body))
    } else {
        fmt.Println(time.Now().Format("2006-01-02 15:04:05"), "已认证,继续监听!")
    }
    // 释放资源
    defer response.Body.Close()
}

//http://10.20.247.250/webAuth/
func main() {
    if !checkMac(mac()) {
        fmt.Println("合法性检查失败,请勿非法拷贝!")
        //fmt.Println("本机MAC地址:" + mac())
        return
    }
    fmt.Println(time.Now().Format("2006-01-02 15:04:05"), "合法性检查结果:", checkMac(mac()))

    for {
        go NetAuth()
        time.Sleep(60 * time.Second)
    }

}

自动登录深信服上网认证控制

#!/usr/bin/env python
# -*- coding: UTF-8 -*-
import re
import requests

if __name__ == '__main__':
    session = requests.session()

    base_headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.71 Safari/537.36 OPR/35.0.2066.23 (Edition beta)', 'Referer': 'http://blog.bbzhh.com'}
    session.headers = base_headers
    resp = session.post('http://深信服认证主机IP/webAuth/',{'username':'用户名','password':'密码','rememberPwd':'1','pwd':'密码','secret':'true'})
    print unicode(resp.text).encode('utf8')

Python操作LDAP

基于Python3,需要安装依赖ldap3

#!/usr/bin/env python3
# -*- coding: UTF-8 -*-

from ldap3 import Server, Connection, ALL,NTLM,LDAPBindError


if __name__ == "__main__":
    server = Server('172.16.66.129', get_info=ALL)

    #user必须为 'Domain名称\\用户名' , 或者'域名\\用户名'
    try:
        conn = Connection(server, user="test.com\\Administrator", password="123456aA", authentication=NTLM,auto_bind=True)
        #启用tls加密
        #conn.start_tls()
        print(conn.extend.standard.who_am_i())

        #查找所有用户用户
        conn.search('dc=test, dc=com', '(objectclass=person)')
        print(conn.entries)
        print('========================================================')
        #查找某一ou下的用户
        conn.search('ou=zsb, dc=test, dc=com', '(objectclass=person)')
        print(dir(conn.entries[0]))
        print(conn.entries[0].entry_to_json())
        print('========================================================')
        #查找所有管理员帐户
        conn.search('dc=test, dc=com', '(&(objectclass=person)(uid=admin))')
        print(conn.entries)
        print('========================================================')
        #添加用户
        print(conn.add('cn=python,ou=zsb,dc=test,dc=com', 'User',
                 {'givenName': 'Python测试', 'sn': 'test', 'departmentNumber': 'vvvv', 'telephoneNumber': 1313131313}))
    except LDAPBindError:
        print('认证失败,请检查用户名密码')
    #print(server.info)
    #print(server.schema)

Java操作LDAP

package com.hoperun.ldap;

import java.util.Properties;

import javax.naming.Context;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.Attribute;
import javax.naming.directory.BasicAttribute;
import javax.naming.directory.BasicAttributes;
import javax.naming.directory.DirContext;
import javax.naming.directory.ModificationItem;
import javax.naming.directory.SearchControls;
import javax.naming.directory.SearchResult;
import javax.naming.ldap.InitialLdapContext;
/**
 * Created by tan9le on 16/5/13.
 */

public class LdapTest{
    DirContext dc = null;
    String root = "DC=test,DC=com"; // LDAP的根节点的DC

    public void init() {
        Properties env = new Properties();
        String adminName = "administrator@test.com";// username@domain
        String adminPassword = "123456aA";// password
        String ldapURL = "LDAP://172.16.66.129:389";// ip:port
        env.put(Context.INITIAL_CONTEXT_FACTORY,"com.sun.jndi.ldap.LdapCtxFactory");
        env.put(Context.SECURITY_AUTHENTICATION, "simple");// "none","simple","strong"
        env.put(Context.SECURITY_PRINCIPAL, adminName);
        env.put(Context.SECURITY_CREDENTIALS, adminPassword);
        env.put(Context.PROVIDER_URL, ldapURL);
        try {
            dc = new InitialLdapContext(env, null);
            System.out.println("认证成功");
        } catch (Exception e) {
            System.out.println("认证失败");
            e.printStackTrace();
        }
    }

    public void close() {
        if (dc != null) {
            try {
                dc.close();
            } catch (NamingException e) {
                System.out.println("NamingException in close():" + e);
            }
        }
    }

    public void delete(String dn) {
        try {
            dc.destroySubcontext(dn);
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("Exception in delete():" + e);
        }
    }

    public boolean renameEntry(String oldDN, String newDN) {
        try {
            dc.rename(oldDN, newDN);
            return true;
        } catch (NamingException ne) {
            System.err.println("Error: " + ne.getMessage());
            return false;
        }
    }

    public boolean modifyInformation(String dn, String employeeID) {
        try {
            System.out.println("updating...\n");
            ModificationItem[] mods = new ModificationItem[1];
            // 修改属性
            Attribute attr0 = new BasicAttribute("OU",employeeID);
            mods[0] = new ModificationItem(DirContext.ADD_ATTRIBUTE, attr0);
            /* 修改属性 */
            dc.modifyAttributes(dn+",DC=test,DC=com", mods);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            System.err.println("Error: " + e.getMessage());
            return false;
        }
    }

    public void add(String newUserName) {
        try {
            BasicAttributes attrs = new BasicAttributes();
            BasicAttribute objclassSet = new BasicAttribute("objectClass");
            objclassSet.add("sAMAccountName");
            objclassSet.add("employeeID");
            attrs.put(objclassSet);
            attrs.put("ou", newUserName);
            dc.createSubcontext("ou=" + newUserName + "," + root, attrs);
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("Exception in add():" + e);
        }
    }

    public void searchInformation(String searchBase) {
        try {
            SearchControls searchCtls = new SearchControls();
            searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);
            String searchFilter = "(&(objectCategory=person)(objectClass=user)(name=*))";
            String returnedAtts[] = { "memberOf" };
            searchCtls.setReturningAttributes(returnedAtts);
            NamingEnumeration<SearchResult> answer = dc.search(searchBase,
                    searchFilter, searchCtls);
            while (answer.hasMoreElements()) {
                SearchResult sr = (SearchResult) answer.next();
                System.out.println("<<<::[" + sr.getName() + sr.getAttributes()+ "]::>>>>");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public SearchResult searchByUserName(String searchBase, String userName) {
        SearchControls searchCtls = new SearchControls();
        searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);
        String searchFilter = "sAMAccountName=" + userName;
        String returnedAtts[] = { "memberOf" }; // 定制返回属性
        searchCtls.setReturningAttributes(returnedAtts); // 设置返回属性集
        try {
            NamingEnumeration<SearchResult> answer = dc.search(searchBase,
                    searchFilter, searchCtls);
            return answer.next();
        } catch (Exception e) {
            e.printStackTrace();
            System.err.println("Throw Exception : " + e);
        }
        return null;
    }



    public static void main(String[] args) {

        LdapTest ldap = new LdapTest();
        ldap.init();
        //SearchResult sr = ldap.searchByUserName(ldap.root, "wzp");
        ldap.searchInformation(ldap.root);

    }
}

使用gvm来安装并管理golang环境

曾经折腾golang的时候,还很简单,mac上只要brew install go就可以了,自从golang1.5加入了自省以后,一切变的都不那么美好,写这篇文章的时候brew默认安装的已经是go1.6版本,安装后粗看上去都是好的,但是在配置交叉编译环境时,遇到了问题,总是提示找不到zversion.go的文件。

这里推荐一个叫做gvm:Go Version Manager 的工具来替代brew完成golang的安装与配置。
这个工具目前开源并托管在github上:https://github.com/moovweb/gvm ,具体的使用方法也可以参考官方github上的readme,下面我就将我的使用过程大概列举一下,作为备忘。
BTW:我的环境是MacOS 10.11.4

安装依赖

brew install mercurial bzr

安装gvm

bash < <(curl -s -S -L https://raw.githubusercontent.com/moovweb/gvm/master/binscripts/gvm-installer)

执行后,会有以下的提示:

Cloning from https://github.com/moovweb/gvm.git to /Users/tan9le/.gvm
No existing Go versions detected
Installed GVM v1.0.22

Please restart your terminal session or to get started right away run
 `source /Users/tan9le/.gvm/scripts/gvm`

这里关闭并重启开启终端,或者在当前终端执行source /Users/tan9le/.gvm/scripts/gvm命令就可以生效了。

使用gvm安装golang

gvm list   #列出已安装的golang环境
gvm listall  #列出所有的golang环境(包括未安装)
gvm install go1.4   #安装golang 1.4的环境,可以在gvm listall中找到所有的可用版本
gvm use go1.4 [--default] #将当前环境设置为golang 1.4
gvm pkgset create test #创建一个名为test的环境变量集,我们可以在环境变量集中设置相关的环境变量,比如为linux打包是一份环境变量,为windows打包又是一份环境变量等等
gvm pkgset use test #使用名为test的环境变量集
gvm pkgenv #修改当前使用的环境变量

这里要注意该死的go 1.5开始的自省,在安装golang版本>=1.5时,需要先安装golang 1.4

Go 1.5+ removed the C compilers from the toolchain and replaced them with one written in Go. Obviously, this creates a bootstrapping problem if you don't already have a working Go install. In order to compile Go 1.5+, make sure Go 1.4 is installed first.

当然,如果要手动安装golang 1.5/1.6也是可以的,先安装golang 1.4.3,然后在make之前需要指定环境变量$GOROOT_BOOTSTRAP,将其指向golang 1.4.3的安装目录即可