Commit c2380c7b authored by lihailei's avatar lihailei

add crypto module.

parent e79a03a3
package common
package crypto
import (
"crypto/md5"
"crypto/rand"
"encoding/base64"
"encoding/hex"
"io"
)
//生成32位md5字串
func GetMd5String(s string) string {
h := md5.New()
h.Write([]byte(s))
return hex.EncodeToString(h.Sum(nil))
}
//生成Guid字串
func UniqueId() string {
b := make([]byte, 48)
if _, err := io.ReadFull(rand.Reader, b); err != nil {
return ""
}
return GetMd5String(base64.URLEncoding.EncodeToString(b))
}
package common
import (
"fmt"
"log"
"net"
"os"
"path"
"time"
"github.com/pkg/sftp"
"golang.org/x/crypto/ssh"
"io"
"path/filepath"
"strings"
. "gitlab.33.cn/lihailei/chain33_sdk/src/models"
)
var (
//安装包所在路径
LocalFilePath = "chain33.tgz"
)
func SetLocalFilePath(path string) {
LocalFilePath = path
}
func GetLocalFilePath() string {
return LocalFilePath
}
type ScpInfo struct {
UserName string
PassWord string
HostIp string
Port int
LocalFilePath string
RemoteDir string
}
type CmdInfo struct {
userName string
passWord string
hostIp string
port int
cmd string
remoteDir string
}
type SshInfo struct {
userName string
passWord string
hostIp string
port int
}
type tomlConfig struct {
Title string
Servers map[string]ScpInfo
}
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,
//需要验证服务端,不做验证返回nil就可以
HostKeyCallback: func(hostname string, remote net.Addr, key ssh.PublicKey) error {
return nil
},
}
// 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,
//需要验证服务端,不做验证返回nil就可以
HostKeyCallback: func(hostname string, remote net.Addr, key ssh.PublicKey) error {
return nil
},
}
// 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 ScpFileFromLocalToRemote(si *ScpInfo) {
sftpClient, err := sftpconnect(si.UserName, si.PassWord, si.HostIp, si.Port)
if err != nil {
clog.Error(fmt.Sprintf("start sftpconnect, err:%s", err.Error()))
panic(err)
}
defer sftpClient.Close()
srcFile, err := os.Open(si.LocalFilePath)
if err != nil {
panic(err)
}
defer srcFile.Close()
var remoteFileName = path.Base(si.LocalFilePath)
fmt.Println("remoteFileName:", remoteFileName)
dstFile, err := sftpClient.Create(path.Join(si.RemoteDir, remoteFileName))
if err != nil {
clog.Error(fmt.Sprintf("sftpClient create file, err:%s", err.Error()))
}
defer dstFile.Close()
//bufReader := bufio.NewReader(srcFile)
//b := bytes.NewBuffer(make([]byte,0))
buf := make([]byte, 1024000)
for {
//n, err := bufReader.Read(buf)
n, _ := srcFile.Read(buf)
if err != nil && err != io.EOF {
panic(err)
}
if n == 0 {
break
}
dstFile.Write(buf[0:n])
}
clog.Info(fmt.Sprintf("copy %s to remote server finished!", remoteFileName))
//fmt.Println("copy file to remote server finished!")
}
func RemoteExec(cmdInfo *CmdInfo) error {
//A Session only accepts one call to Run, Start or Shell.
session, err := sshconnect(cmdInfo.userName, cmdInfo.passWord, cmdInfo.hostIp, cmdInfo.port)
if err != nil {
clog.Error(fmt.Sprintf("start ssh connect err:%s", err.Error()))
return err
}
defer session.Close()
data, err := session.Output(cmdInfo.cmd)
clog.Debug(fmt.Sprintf("remote exec cmd return info:%s", string(data)))
fmt.Println("remote exec cmd return info:", string(data))
if err != nil {
clog.Error(fmt.Sprintf("exec output err:%s", err.Error()))
return err
}
return nil
}
//远程查看进程是否存在
func RemoteViewProcIsExist(procName string, ssh SshInfo) (bool, error) {
session, err := sshconnect(ssh.userName, ssh.passWord, ssh.hostIp, ssh.port)
if err != nil {
return false, err
}
defer session.Close()
cmd := fmt.Sprintf("ps -ef | grep %s | grep -v grep| awk '{print $2}'", procName)
data, err := session.Output(cmd)
if string(data) != "" && err == nil {
return true, err
}
return false, nil
}
func remoteScp(si *ScpInfo, reqnum chan struct{}) {
defer func() {
reqnum <- struct{}{}
}()
ScpFileFromLocalToRemote(si)
//session, err := sshconnect("ubuntu", "Fuzamei#123456", "raft15258.chinacloudapp.cn", 22)
fmt.Println("remoteScp file sucessfully!:")
}
func getCurrentDirectory() string {
dir, err := filepath.Abs(filepath.Dir(os.Args[0]))
if err != nil {
log.Fatal(err)
}
fmt.Println(dir)
return strings.Replace(dir, "\\", "/", -1)
}
func pwd() string {
dir, err := filepath.Abs(filepath.Dir(os.Args[0]))
if err != nil {
panic(err)
}
return dir
}
func StartAll(servers ServerList) {
//fmt.Println(getCurrentDirectory())
arrMap := make(map[int]*CmdInfo)
//多协程启动部署
reqC := make(chan struct{}, len(servers.ServerList))
peersURL := ""
seeds := ""
for index, s := range servers.ServerList {
if s.SeedURL != "" {
if seeds == "" {
seeds = fmt.Sprintf("%s", s.SeedURL)
} else {
seeds = fmt.Sprintf("%s,%s", seeds, s.SeedURL)
}
}
if s.PeerURL != "" {
if peersURL == "" {
peersURL = fmt.Sprintf("%s", s.PeerURL)
} else {
peersURL = fmt.Sprintf("%s,%s", peersURL, s.PeerURL)
}
}
cmdInfo := &CmdInfo{
hostIp: s.HostIp,
userName: s.UserName,
port: s.Port,
passWord: s.PassWord,
cmd: fmt.Sprintf("mkdir -p %s", s.RemoteDir),
remoteDir: s.RemoteDir,
}
err := RemoteExec(cmdInfo)
if err != nil {
fmt.Println(err.Error())
break
}
sc := &ScpInfo{
HostIp: s.HostIp,
UserName: s.UserName,
Port: s.Port,
PassWord: s.PassWord,
LocalFilePath: GetLocalFilePath(),
RemoteDir: s.RemoteDir,
}
go remoteScp(sc, reqC)
arrMap[index] = cmdInfo
}
for i := 0; i < len(servers.ServerList); i++ {
<-reqC
}
for i, cmdInfo := range arrMap {
cmdInfo.cmd = fmt.Sprintf("cd %s;tar -xvf chain33.tgz;bash raft_conf.sh %d %v %v;bash run.sh start", cmdInfo.remoteDir, i+1, seeds, peersURL)
RemoteExec(cmdInfo)
}
}
func StopAll(servers ServerList) {
//执行速度快,不需要多起多协程工作
for _, s := range servers.ServerList {
cmdInfo := &CmdInfo{
hostIp: s.HostIp,
userName: s.UserName,
port: s.Port,
passWord: s.PassWord,
cmd: fmt.Sprintf("cd %s;bash run.sh stop", s.RemoteDir),
remoteDir: s.RemoteDir,
}
RemoteExec(cmdInfo)
}
}
func ClearAll(servers ServerList) {
for _, s := range servers.ServerList {
cmdInfo := &CmdInfo{
hostIp: s.HostIp,
userName: s.UserName,
port: s.Port,
passWord: s.PassWord,
cmd: fmt.Sprintf("cd %s;bash run.sh clear", s.RemoteDir),
remoteDir: s.RemoteDir,
}
RemoteExec(cmdInfo)
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment