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

golang执行远程ssh命令,以及scp文件

// main.go
package main

import (
    "fmt"
    "log"
    "os"
    "path"
    "time"

    "github.com/pkg/sftp"
    "golang.org/x/crypto/ssh"
)

func sshconnect(user, password, host string, port int) (*ssh.Session, error) {
    var (
        auth         []ssh.AuthMethod
        addr         string
        clientConfig *ssh.ClientConfig
        client       *ssh.Client
        session      *ssh.Session
        err          error
    )
    // get auth method
    auth = make([]ssh.AuthMethod, 0)
    auth = append(auth, ssh.Password(password))

    clientConfig = &ssh.ClientConfig{
        User:    user,
        Auth:    auth,
        Timeout: 30 * time.Second,
    }

    // connet to ssh
    addr = fmt.Sprintf("%s:%d", host, port)

    if client, err = ssh.Dial("tcp", addr, clientConfig); err != nil {
        return nil, err
    }

    // create session
    if session, err = client.NewSession(); err != nil {
        return nil, err
    }

    return session, nil
}

func sftpconnect(user, password, host string, port int) (*sftp.Client, error) {
    var (
        auth         []ssh.AuthMethod
        addr         string
        clientConfig *ssh.ClientConfig
        sshClient    *ssh.Client
        sftpClient   *sftp.Client
        err          error
    )
    // get auth method
    auth = make([]ssh.AuthMethod, 0)
    auth = append(auth, ssh.Password(password))

    clientConfig = &ssh.ClientConfig{
        User:    user,
        Auth:    auth,
        Timeout: 30 * time.Second,
    }

    // connet to ssh
    addr = fmt.Sprintf("%s:%d", host, port)

    if sshClient, err = ssh.Dial("tcp", addr, clientConfig); err != nil {
        return nil, err
    }

    // create sftp client
    if sftpClient, err = sftp.NewClient(sshClient); err != nil {
        return nil, err
    }

    return sftpClient, nil
}

func main() {

    session, err := sshconnect("用户名", "密码", "IP地址", 端口)
    if err != nil {
        log.Fatal(err)
    }
    defer session.Close()
    session.Stdout = os.Stdout
    session.Stderr = os.Stderr
    session.Run("ls")
    fmt.Println("upload file test:")

    var (
        sftpClient *sftp.Client
    )

    // 这里换成实际的 SSH 连接的 用户名,密码,主机名或IP,SSH端口
    sftpClient, err = sftpconnect("用户名", "密码", "IP地址", 端口)
    if err != nil {
        log.Fatal(err)
    }
    defer sftpClient.Close()

    // 用来测试的本地文件路径 和 远程机器上的文件夹
    var localFilePath = "main.go"
    var remoteDir = "/root/"
    srcFile, err := os.Open(localFilePath)
    if err != nil {
        log.Fatal(err)
    }
    defer srcFile.Close()

    var remoteFileName = path.Base(localFilePath)
    dstFile, err := sftpClient.Create(path.Join(remoteDir, remoteFileName))
    if err != nil {
        log.Fatal(err)
    }
    defer dstFile.Close()

    buf := make([]byte, 1024)
    for {
        n, _ := srcFile.Read(buf)
        if n == 0 {
            break
        }
        dstFile.Write(buf[0:n])
    }

    fmt.Println("copy file to remote server finished!")
}

Python某系统登录后自动提交

自己能看懂就行 ^_^

#!/usr/bin/env python
# -*- coding: UTF-8 -*-
__author__ = 'tan9le'

import requests
import datetime
import random

host = '服务器地址+端口'
Origin = 'http://服务器地址+端口/'
indexURL = Origin + 'attp/www/index.html'
loginURL = Origin + 'attp/login/login.do'
operURL = Origin + 'attp/attendance/entryForJsp'
user_name = '用户名'
password = '密码'

today = datetime.date.today()
working_days = ['2016-09-17','2016-10-08','2016-10-09']
holidays = ['2016-10-03','2016-10-04','2016-10-04','2016-10-06','2016-10-07']

#通用header
header_base = {
    'Accept':'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
    'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36',
    'Host': host,
    'Origin':Origin,
    'Connection':'keep-alive',
    'Referer':indexURL
}
#登录时引用的header
loginHeader = header_base.copy()
loginHeader["Content-Type"] = 'application/json;charset=UTF-8'
#操作时引用的header
operHeader = header_base.copy()

#全局request session,用来解决重复请求时的session、cookeis问题
s = requests.session()

def init():
    #得到日期对应的字符串
    todaystr = today.strftime("%Y-%m-%d")
    #得到日期是星期几,0代表周一
    dayofweek = today.weekday()
    #判断是否应该打卡
    if dayofweek < 6:
        if(todaystr in holidays):
            operflag = False
            print("工作日放假^_^")
        else:
            operflag = True
            print("正常上班,需要打卡")
    else:
        if(todaystr in working_days):
            operflag = True
            print("周末正常上班,需要打卡")
        else:
            operflag = False
            print("周末正常休息^_^")
    return operflag

#登录请求
def login():
    loginHeader['request-type'] = 'angular/api'
    login_param = {"login_id":user_name,"password":password,"roleType":"0"}
    #登录
    s.headers = loginHeader
    s.post(loginURL,json=login_param)
    #访问初始界面
    r = s.get(Origin + 'attp/attendance/initPage')
    #登录成功后,将header还原
    s.headers = header_base
    return r

#出勤
def chuqin(yearmonth,begin_time):
    operHeader['Referer'] = Origin + 'attp/attendance/initAttForJsp'
    oper_param = {"staff_code":user_name,"yearmonth":yearmonth,"project_id":"-1","projectname":" ","projectcode":"-1","area_id":"南京市","actualArea":"江苏省 南京市","create_user":user_name,"begin_time":begin_time}
    s.headers = operHeader
    r = s.post(operURL, json=oper_param)
    # 操作成功后,将header还原
    s.headers = header_base
    return r

#退勤
def tuiqin(yearmonth,end_time):
    operHeader['Referer'] = Origin + 'attp/attendance/initAttForJsp'
    oper_param = {"staff_code":user_name,"yearmonth":yearmonth,"project_id":"-1","projectname":" ","projectcode":"-1","area_id":"南京市","actualArea":"江苏省 南京市","create_user":user_name,"end_time":end_time}
    s.headers = operHeader
    r = s.post(operURL, json=oper_param)
    # 操作成功后,将header还原
    s.headers = header_base
    return r

#获取HH:MM样式的随机时间
def randmontime(beginHH,endHH,beginMM,endMM):
    HH = random.randint(beginHH, endHH)
    MM = random.randint(beginMM, endMM)
    if(HH<10):
        HHstr = '0' + str(HH)
    else:
        HHstr = str(HH)
    if (MM < 10):
        MMstr = '0' + str(MM)
    else:
        MMstr = str(MM)
    return HHstr + ':' + MMstr

if __name__ == '__main__':
    flag = init()
    print(flag)
    if flag:
        todaystr = today.strftime("%Y-%m-%d")
        chuqintime = randmontime(7,8,15,45)
        tuiqintime = randmontime(19,20,30,59)
        login()
        print(chuqin(todaystr,chuqintime).text)
        print(tuiqin(todaystr,tuiqintime).text)

自动登录深信服上网控制-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)