Exemplo n.º 1
0
Arquivo: main.go Projeto: cv3/sftp
func main() {
	var auths []ssh.AuthMethod
	if aconn, err := net.Dial("unix", os.Getenv("SSH_AUTH_SOCK")); err == nil {
		auths = append(auths, ssh.PublicKeysCallback(agent.NewClient(aconn).Signers))

	}
	if *PASS != "" {
		auths = append(auths, ssh.Password(*PASS))
	}

	config := ssh.ClientConfig{
		User: *USER,
		Auth: auths,
	}
	addr := fmt.Sprintf("%s:%d", *HOST, *PORT)
	conn, err := ssh.Dial("tcp", addr, &config)
	if err != nil {
		log.Fatalf("unable to connect to [%s]: %v", addr, err)
	}
	defer conn.Close()

	c, err := sftp.NewClient(conn, sftp.MaxPacket(*SIZE))
	if err != nil {
		log.Fatalf("unable to start sftp subsytem: %v", err)
	}
	defer c.Close()

	w, err := c.OpenFile("/dev/null", syscall.O_WRONLY)
	if err != nil {
		log.Fatal(err)
	}
	defer w.Close()

	f, err := os.Open("/dev/zero")
	if err != nil {
		log.Fatal(err)
	}
	defer f.Close()

	const size int64 = 1e9

	log.Printf("writing %v bytes", size)
	t1 := time.Now()
	n, err := io.Copy(w, io.LimitReader(f, size))
	if err != nil {
		log.Fatal(err)
	}
	if n != size {
		log.Fatalf("copy: expected %v bytes, got %d", size, n)
	}
	log.Printf("wrote %v bytes in %s", size, time.Since(t1))
}
Exemplo n.º 2
0
func sshConn(bak *Backup) {
	fmt.Println("--------------------------------------------------------")

	client := gossh.New(host, user)
	defer client.Close()
	client.SetPassword(password)

	// client.DebugWriter = MakeLogger("[DEBUG]")
	client.InfoWriter = MakeLogger("[INFO]")
	client.ErrorWriter = MakeLogger("[ERROR]")

	client.Info("正在执行命令: 备份【" + bak.fileName + "】,请耐心等待.")
	rsp, err := client.Execute(bak.cmd)
	if rsp.Success() {
		client.Info("执行命令: 备份【" + bak.fileName + "】成功.")
	} else {
		checkError(err)
	}

	conn, err := client.Connection()
	checkError(err)
	defer conn.Close()

	sftpConn, err := sftp.NewClient(conn, sftp.MaxPacket(1<<15))
	checkError(err)

	var filePath string
	if bak.fileName == "zentaopms.tar.gz" {
		srcSqlPath = "/var/www"
		filePath = bak.pathName + "/"
	} else {
		filePath = MkBakDir(bak.pathName + "/SQL/")
	}

	srcFile, err := sftpConn.Open(srcSqlPath + "/" + bak.fileName)
	defer srcFile.Close()
	checkError(err)

	info, _ := srcFile.Stat()
	dstFile, err := os.Create(filePath + bak.fileName)
	defer dstFile.Close()
	checkError(err)

	client.Info("正在下载备份的文件【" + bak.fileName + "】,请耐心等待.")
	_, err = io.Copy(dstFile, io.LimitReader(srcFile, info.Size()))
	checkError(err)

	client.Info("下载备份文件【" + bak.fileName + "】完成.\n")
}
Exemplo n.º 3
0
func (file *UploadFile) UploadiManFile() (err error) {
	file.client.Host = file.Host
	file.client.User = file.User
	file.client.SetPassword(file.Passwd)
	if file.Debug {
		file.client.DebugWriter = file.MakeLogger("[DEBUG]")
	}

	file.client.InfoWriter = file.MakeLogger("[INFO]")
	file.client.ErrorWriter = file.MakeLogger("[ERROR]")

	defer file.client.Close()

	// 建立一个conn
	conn, err := file.client.Connection()

	// 创建 sftp 连接
	sftpConn, err := sftp.NewClient(conn, sftp.MaxPacket(1<<15))
	file.CheckError("unable to start sftp subsytem: 10.10.2.222", err)
	defer sftpConn.Close()

	// 本地文件路径
	f, err := os.Open(file.UpgradeFile)
	file.CheckError("打开上传文件["+file.UpgradeFile+"]失败", err)
	defer f.Close()

	// 上传到的位置
	w, err := sftpConn.Create(file.DestFile)
	file.CheckError("创建上传文件["+file.DestFile+"]失败", err)
	defer w.Close()

	// 要上传的文件信息
	info, err := f.Stat()
	file.CheckError("获取上传文件["+file.UpgradeFile+"]信息失败", err)

	// 上传计时
	timeNow := time.Now()

	// 流的方式上传
	n, err := io.Copy(w, io.LimitReader(f, info.Size()))
	file.CheckError("上传文件["+file.UpgradeFile+"]失败.", err)
	if n != info.Size() {
		return errors.New("上传文件[" + file.UpgradeFile + "]总大小为 " + fmt.Sprint(info.Size()) + " bytes, 已上传 " + fmt.Sprint(n) + " bytes,上传失败.")
	}

	file.client.InfoWriter("上传文件[" + file.UpgradeFile + "]成功, 总大小为 " + fmt.Sprint(info.Size()) + ", 用时 " + fmt.Sprint(time.Since(timeNow)))

	return nil
}
Exemplo n.º 4
0
func main() {
	client := gossh.New("10.10.2.222", "root")
	// my default agent authentication is used. use
	client.SetPassword("hpiman")
	// for password authentication
	client.DebugWriter = MakeLogger("DEBUG")
	client.InfoWriter = MakeLogger("INFO ")
	client.ErrorWriter = MakeLogger("ERROR")
	client.Execute("mysqldump -R -uroot -p123456 hupunac >/root/cody_develop/sql/hupunac.sql")

	conn, _ := client.Connection()
	c, err := sftp.NewClient(conn, sftp.MaxPacket(5e9))
	c.OpenFile("/root/cody_develop/sql", "hupunac.sql")

	defer client.Close()

}
Exemplo n.º 5
0
func main() {
	var auths []ssh.AuthMethod
	if aconn, err := net.Dial("unix", os.Getenv("SSH_AUTH_SOCK")); err == nil {
		auths = append(auths, ssh.PublicKeysCallback(agent.NewClient(aconn).Signers))

	}
	if *PASS != "" {
		auths = append(auths, ssh.Password(*PASS))
	}

	config := ssh.ClientConfig{
		User: *USER,
		Auth: auths,
	}
	addr := fmt.Sprintf("%s:%d", *HOST, *PORT)
	conn, err := ssh.Dial("tcp", addr, &config)
	if err != nil {
		log.Fatalf("unable to connect to [%s]: %v", addr, err)
	}
	defer conn.Close()

	c, err := sftp.NewClient(conn, sftp.MaxPacket(*SIZE))
	if err != nil {
		log.Fatalf("unable to start sftp subsytem: %v", err)
	}
	defer c.Close()

	r, err := c.Open("/root/")
	if err != nil {
		log.Fatal(err)
	}
	defer r.Close()

	const size = 1024
	t1 := time.Now()
	n, err := io.ReadFull(r, make([]byte, size))
	if err != nil {
		log.Fatal(err)
	}
	if n != size {
		log.Fatalf("copy: expected %v bytes, got %d", size, n)
	}
	log.Printf("read %v bytes in %s", size, time.Since(t1))
	log.Println(string(n))
}
Exemplo n.º 6
0
func CopyFile(conn *ssh.Client, FileName, DirectoryPath string) bool {
	defer conn.Close()
	if !strings.HasSuffix(DirectoryPath, "/") {
		DirectoryPath = DirectoryPath + "/"
	}
	con, err := sftp.NewClient(conn, sftp.MaxPacket(5e9))
	if err != nil {
		if debug {
			fmt.Println(err)
		}
		return false
	}
	sFile, _ := os.Open(FileName)
	defer sFile.Close()
	dFile := DirectoryPath + FileName
	File, err := con.OpenFile(dFile, os.O_CREATE|os.O_TRUNC|os.O_RDWR)
	if err != nil {
		if debug {
			fmt.Println(err)
		}
		return false
	}
	defer File.Close()
	for {
		buf := make([]byte, 1024)
		n, err := sFile.Read(buf)
		if err != nil {
			if err.Error() == "EOF" {
				break
			}
			return false
		}
		File.Write(buf[:n])
	}
	return true
}
Exemplo n.º 7
0
func sshCmd(sqlcmd, srcdir, desdir string, debug bool) {

	client := gossh.New("10.10.2.222", "root")
	// my default agent authentication is used. use
	client.SetPassword("hpiman")
	// for password authentication
	if debug {
		client.DebugWriter = MakeLogger("[DEBUG]")
	}

	client.InfoWriter = MakeLogger("[INFO]")
	client.ErrorWriter = MakeLogger("[ERROR]")

	defer client.Close()

	// 获取备份数据库的名字
	pc, _, _, _ := runtime.Caller(1)

	funcname := runtime.FuncForPC(pc).Name()

	switch funcname {
	case "main.JavaBackup":
		backName = "hupunac.sql"
	case "main.RegisterBackup":
		backName = "licensemanager.sql"
	case "main.WebSiteBackup":
		backName = "hupuwebsite.sql"
	case "main.BusinessBackup":
		backName = "hupuerp.sql"
	case "main.ProcutBackup":
		backName = "hupu.sql"
	case "main.BbsBackup":
		backName = "hupubbs.sql"
	}

	rsp, err := client.Execute(sqlcmd)
	if rsp.Success() {
		client.InfoWriter("执行命令: [备份" + backName + "] 成功.")
	} else {
		checkError(sqlcmd, err)
	}
	defer client.Close()

	conn, err := client.Connection()
	defer conn.Close()

	c, err := sftp.NewClient(conn, sftp.MaxPacket(1<<15))
	checkError("unable to start sftp subsytem: 10.10.2.222", err)
	defer c.Close()

	wr, err := c.Open(srcdir + backName)
	checkError("unable open the linux file: "+srcdir+backName, err)
	defer wr.Close()

	info, _ := wr.Stat()

	filelocal, err := os.Create(desdir + backName)
	checkError("unable down the file: "+desdir+backName, err)
	defer filelocal.Close()

	client.InfoWriter("正在下载备份文件[" + backName + "]")
	_, err = io.Copy(filelocal, io.LimitReader(wr, info.Size()))
	checkError("unable copy the file: "+desdir+backName, err)

	client.InfoWriter("下载备份文件[" + backName + "]完成\n")
}
Exemplo n.º 8
0
func (file *UploadFile) UploadiManFile() (err error) {
	client := NewConn()
	client.Host = file.Host
	client.User = file.User
	client.SetPassword(file.Passwd)
	if file.Debug {
		client.DebugWriter = file.MakeLogger("[DEBUG]")
	}

	client.InfoWriter = file.MakeLogger("[INFO]")
	client.ErrorWriter = file.MakeLogger("[ERROR]")

	// 建立一个conn
	conn, err := client.Connection()
	if err != nil {
		client.ErrorWriter("连接SSH失败," + err.Error())
		return
	}
	defer conn.Close()

	// 创建 sftp 连接
	sftpConn, err := sftp.NewClient(conn, sftp.MaxPacket(1<<15))
	if err != nil {
		client.ErrorWriter("创建SFTP失败," + err.Error())
		return
	}
	defer sftpConn.Close()

	// 本地文件路径
	f, err := os.Open(file.LocalFilePath)
	if err != nil {
		client.ErrorWriter("打开上传文件【" + file.LocalFilePath + "】失败" + err.Error())
		return
	}
	defer f.Close()

	// 要上传的文件信息
	_, file.UpgradeFileName = filepath.Split(file.LocalFilePath)
	info, err := f.Stat()
	if err != nil {
		client.ErrorWriter("获取上传文件【" + file.UpgradeFileName + "】信息失败" + err.Error())
		return
	}
	// 判断文件是否问解压脚本
	if file.UpgradeFileName == "decompress_pack.sh" {
		return errors.New("[ERROR] 升级文件【" + file.UpgradeFileName + "】是非法文件,禁止上传.")
		client.Close()
	}

	// 上传计时
	timeNow := time.Now()

	// 流的方式上传
	client.InfoWriter("正在上传【" + file.UpgradeFileName + "】升级文件,请稍等...")

	size := info.Size()
	unit := "byte"
	switch {
	case size < 1024:
	case size >= 1024 && size < 1024*1024:
		size = size / 1024
		unit = "KB"
	case size >= 1024*1024 && size < 1024*1024*200:
		size = size / 1024 / 1024
		unit = "MB"
	case size >= 1024*1024*200:
		if size < 1024*1024*1024 {
			size = size / 1024 / 1024
			unit = "MB"
		} else {
			size = size / 1024 / 1024 / 1024
			unit = "GB"

		}

		return errors.New("[ERROR] 升级文件【" + file.UpgradeFileName + "】总大小为 " + fmt.Sprint(size) + " " + unit +
			",超过上传文件的最大限制.")
		client.Close()
	}

	// 服务器升级路径
	destFile := file.UploadFilePath + "/" + file.UpgradeFileName

	w, err := sftpConn.Create(destFile)
	if err != nil {
		client.ErrorWriter("创建上传文件【" + file.UpgradeFileName + "】失败" + err.Error())
		return
	}
	defer w.Close()

	// 开始通过流的方式上传
	n, err := io.Copy(w, io.LimitReader(f, info.Size()))
	if err != nil {
		client.ErrorWriter("获取上传文件【" + file.UpgradeFileName + "】信息失败" + err.Error())
		return
	}
	if n != info.Size() {
		return errors.New("[ERROR] 升级文件【" + file.UpgradeFileName + "】总大小为 " + fmt.Sprint(size) + " " + unit +
			",已上传 " + fmt.Sprint(n) + " bytes,上传失败.")
	}

	file.timeout = time.Since(timeNow)
	client.InfoWriter("升级文件【" + file.UpgradeFileName + "】上传成功, 总大小为 " + fmt.Sprint(size) + " " + unit +
		", 用时 " + fmt.Sprint(file.timeout) + ".")

	return nil
}