当前位置: 首页>>代码示例>>Golang>>正文


Golang Client.NewSession方法代码示例

本文整理汇总了Golang中golang.org/x/crypto/ssh.Client.NewSession方法的典型用法代码示例。如果您正苦于以下问题:Golang Client.NewSession方法的具体用法?Golang Client.NewSession怎么用?Golang Client.NewSession使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在golang.org/x/crypto/ssh.Client的用法示例。


在下文中一共展示了Client.NewSession方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。

示例1: installOnRemote

func (p *Project) installOnRemote(step int, conn *ssh.Client) {

	// Git and some other programs can send us an unsuccessful exit (< 0)
	// even if the command was successfully executed on the remote shell.
	// On these cases, we want to ignore those errors and move onto the next step.
	ignoredError := "Reason was:  ()"

	// Creates a session over the ssh connection to execute the commands
	session, err := conn.NewSession()
	if err != nil {
		log.Fatal("Failed to build session: ", err)
	}

	defer session.Close()

	var stdoutBuf bytes.Buffer
	session.Stdout = &stdoutBuf

	fmt.Println(p.typ.program.setup[step])

	err = session.Run(p.typ.program.setup[step])

	if err != nil && !strings.Contains(err.Error(), ignoredError) {
		log.Printf("Command '%s' failed on execution", p.typ.program.setup[step])
		log.Fatal("Error on command execution: ", err.Error())
	}
}
开发者ID:alesr,项目名称:k-env-setup,代码行数:27,代码来源:k-installer.go

示例2: tailFilesOnClient

func tailFilesOnClient(client *ssh.Client, files []string, sudo bool, linec chan<- string, errc chan<- error) {
	var sessions []*ssh.Session
	closeSessions := func() {
		for _, session := range sessions {
			_ = session.Signal(ssh.SIGKILL)
			_ = session.Close()
		}
	}

	var wg sync.WaitGroup
	for _, file := range files {
		session, err := client.NewSession()
		if err != nil {
			closeSessions()
			errc <- fmt.Errorf("can't open session: %v", err)
			return
		}
		sessions = append(sessions, session)

		wg.Add(1)
		go func(file string) {
			defer wg.Done()
			err := tailFile(session, file, sudo, linec)
			if err != nil {
				errc <- err
			}
		}(file)

	}

	wg.Wait()
}
开发者ID:aybabtme,项目名称:multisshtail,代码行数:32,代码来源:main.go

示例3: ExecuteCmd

func ExecuteCmd(client *ssh.Client, command string, stdout *string, stderr *string) error {
	session, err := client.NewSession()
	if err != nil {
		panic("Failed to create session: " + err.Error())
	}
	defer session.Close()
	//session.Setenv("PATH", "/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin:/root/bin") //apparently needs serverside support
	// Once a Session is created, you can execute a single command on
	// the remote side using the Run method.
	var b bytes.Buffer
	var a bytes.Buffer
	session.Stdout = &b
	session.Stderr = &a
	log.Printf("CMD: %s\n", command)
	if err := session.Run(command); err != nil {
		return err
	}

	if stdout != nil {
		*stdout = b.String()
	}
	if stderr != nil {
		*stderr = a.String()
	}

	return err
}
开发者ID:newxan,项目名称:gopistrano,代码行数:27,代码来源:client.go

示例4: scpAndRun

func scpAndRun(client ssh.Client) {
	scpSession, err := client.NewSession()
	if err != nil {
		panic("Failed to create SCP session: " + err.Error())
	}
	defer scpSession.Close()

	scriptContents := `#!/bin/bash

echo "this script is located at $dirname $0"
`
	scriptReader := strings.NewReader(scriptContents)
	scpError := copy(int64(len(scriptContents)), os.FileMode(0777), "test-script", scriptReader, "/tmp/scripts/", scpSession)
	if scpError != nil {
		panic(scpError)
	}

	execSession, err := client.NewSession()
	if err != nil {
		panic("Failed to create session: " + err.Error())
	}
	defer execSession.Close()

	var stdoutBytes bytes.Buffer
	execSession.Stdout = &stdoutBytes
	if err := execSession.Run("/tmp/scripts/test-script"); err != nil {
		panic("Failed to run: " + err.Error())
	}
}
开发者ID:rosenhouse,项目名称:proctor,代码行数:29,代码来源:shell.go

示例5: sshExec

func sshExec(client *ssh.Client, cmd string) (string, string, int, error) {
	framework.Logf("Executing '%s' on %v", cmd, client.RemoteAddr())
	session, err := client.NewSession()
	if err != nil {
		return "", "", 0, fmt.Errorf("error creating session to host %s: '%v'", client.RemoteAddr(), err)
	}
	defer session.Close()

	// Run the command.
	code := 0
	var bout, berr bytes.Buffer

	session.Stdout, session.Stderr = &bout, &berr
	err = session.Run(cmd)
	if err != nil {
		// Check whether the command failed to run or didn't complete.
		if exiterr, ok := err.(*ssh.ExitError); ok {
			// If we got an ExitError and the exit code is nonzero, we'll
			// consider the SSH itself successful (just that the command run
			// errored on the host).
			if code = exiterr.ExitStatus(); code != 0 {
				err = nil
			}
		} else {
			// Some other kind of error happened (e.g. an IOError); consider the
			// SSH unsuccessful.
			err = fmt.Errorf("failed running `%s` on %s: '%v'", cmd, client.RemoteAddr(), err)
		}
	}
	return bout.String(), berr.String(), code, err
}
开发者ID:nak3,项目名称:kubernetes,代码行数:31,代码来源:addon_update.go

示例6: runCommands

//Execute ssh commands until "exit" is entered
func runCommands(client *ssh.Client) {
	var cmd string
	for strings.ToLower(cmd) != "exit" {
		//Creates a new session.  Only one command per session
		session, err := client.NewSession()
		if err != nil {
			panic("Failed to create session: " + err.Error())
		}

		defer session.Close()

		fmt.Scanf("%s", &cmd)

		var b bytes.Buffer
		session.Stdout = &b
		err1 := session.Run(cmd)
		if err1 != nil {
			fmt.Print("You used an invalid command.")
			err1 = nil
		}
		fmt.Println(b.String())
	}
	//clear the terminal and display conn closed
	clear := exec.Command("clear")
	clear.Stdout = os.Stdout
	clear.Run()
	fmt.Println("\n\nConnection Closed")
}
开发者ID:ZacharyJacobCollins,项目名称:GO-SSH,代码行数:29,代码来源:main.go

示例7: getClientAndSession

func (n *SSHNode) getClientAndSession() (*ssh.Client, *ssh.Session, error) {
	var client *ssh.Client
	var s *ssh.Session
	var err error

	// Retry few times if ssh connection fails
	for i := 0; i < MaxSSHRetries; i++ {
		client, err = n.dial()
		if err != nil {
			time.Sleep(SSHRetryDelay)
			continue
		}

		s, err = client.NewSession()
		if err != nil {
			client.Close()
			time.Sleep(SSHRetryDelay)
			continue
		}

		return client, s, nil
	}

	return nil, nil, err
}
开发者ID:karamsivia,项目名称:netplugin,代码行数:25,代码来源:sshnode.go

示例8: CopyLocalFileToRemote

func CopyLocalFileToRemote(client *ssh.Client, localFilePath string, filename string) error {
	// Each ClientConn can support multiple interactive sessions,
	// represented by a Session.
	session, err := client.NewSession()
	if err != nil {
		log.Fatal("Failed to create session: " + err.Error())
	}
	defer session.Close()

	writer, err := session.StdinPipe()
	if err != nil {
		return err
	}
	defer writer.Close()

	go func() {
		fileContents, _ := ioutil.ReadFile(localFilePath + "/" + filename)
		content := string(fileContents)
		fmt.Fprintln(writer, "C0644", len(content), filename)
		fmt.Fprint(writer, content)
		fmt.Fprintln(writer, "\x00") // transfer end with \x00\
	}()

	session.Run("/usr/bin/scp -t ./")
	return nil
}
开发者ID:kkirsche,项目名称:go-scp,代码行数:26,代码来源:sshClient.go

示例9: NewClient

func NewClient(conn *ssh.Client, readLimitBytesPerSecond, writeLimitBytesPerSecond int64, opts ...func(*sftp.Client) error) (*sftp.Client, error) {
	s, err := conn.NewSession()
	if err != nil {
		return nil, err
	}
	if err := s.RequestSubsystem("sftp"); err != nil {
		return nil, err
	}
	pw, err := s.StdinPipe()
	if err != nil {
		return nil, err
	}
	pr, err := s.StdoutPipe()
	if err != nil {
		return nil, err
	}

	if readLimitBytesPerSecond > 0 {
		pr = flowrate.NewReader(pr, readLimitBytesPerSecond)
	}
	if writeLimitBytesPerSecond > 0 {
		pw = flowrate.NewWriter(pw, writeLimitBytesPerSecond)
	}
	return sftp.NewClientPipe(pr, pw, opts...)
}
开发者ID:hnakamur,项目名称:rate_limited_sftp,代码行数:25,代码来源:client.go

示例10: getClientAndSession

func (n *SSHNode) getClientAndSession() (*ssh.Client, *ssh.Session, error) {
	var client *ssh.Client
	var s *ssh.Session
	var err error

	// Retry few times if ssh connection fails
	for i := 0; i < MaxSSHRetries; i++ {
		client, err = n.dial()
		if err != nil {
			time.Sleep(SSHRetryDelay)
			continue
		}

		s, err = client.NewSession()
		if err != nil {
			client.Close()
			time.Sleep(SSHRetryDelay)
			continue
		}
		modes := ssh.TerminalModes{
			ssh.ECHO:          0,
			ssh.TTY_OP_ISPEED: 14400,
			ssh.TTY_OP_OSPEED: 14400,
		}
		// Request pseudo terminal
		if err := s.RequestPty("xterm", 40, 80, modes); err != nil {
			return nil, nil, fmt.Errorf("failed to get pseudo-terminal: %v", err)
		}

		return client, s, nil
	}

	return nil, nil, err
}
开发者ID:contiv,项目名称:remotessh,代码行数:34,代码来源:sshnode.go

示例11: sshExecNative

func sshExecNative(c conf.ServerInfo, cmd string, sudo bool) (result execResult) {
	result.Servername = c.ServerName
	result.Host = c.Host
	result.Port = c.Port

	var client *ssh.Client
	var err error
	if client, err = sshConnect(c); err != nil {
		result.Error = err
		result.ExitStatus = 999
		return
	}
	defer client.Close()

	var session *ssh.Session
	if session, err = client.NewSession(); err != nil {
		result.Error = fmt.Errorf(
			"Failed to create a new session. servername: %s, err: %s",
			c.ServerName, err)
		result.ExitStatus = 999
		return
	}
	defer session.Close()

	// http://blog.ralch.com/tutorial/golang-ssh-connection/
	modes := ssh.TerminalModes{
		ssh.ECHO:          0,     // disable echoing
		ssh.TTY_OP_ISPEED: 14400, // input speed = 14.4kbaud
		ssh.TTY_OP_OSPEED: 14400, // output speed = 14.4kbaud
	}
	if err = session.RequestPty("xterm", 400, 256, modes); err != nil {
		result.Error = fmt.Errorf(
			"Failed to request for pseudo terminal. servername: %s, err: %s",
			c.ServerName, err)
		result.ExitStatus = 999
		return
	}

	var stdoutBuf, stderrBuf bytes.Buffer
	session.Stdout = &stdoutBuf
	session.Stderr = &stderrBuf

	cmd = decolateCmd(c, cmd, sudo)
	if err := session.Run(cmd); err != nil {
		if exitErr, ok := err.(*ssh.ExitError); ok {
			result.ExitStatus = exitErr.ExitStatus()
		} else {
			result.ExitStatus = 999
		}
	} else {
		result.ExitStatus = 0
	}

	result.Stdout = stdoutBuf.String()
	result.Stderr = stderrBuf.String()
	result.Cmd = strings.Replace(cmd, "\n", "", -1)
	return
}
开发者ID:ymomoi,项目名称:vuls,代码行数:58,代码来源:sshutil.go

示例12: RunCommand

func RunCommand(c *ssh.Client, cmd string) error {
	s, err := c.NewSession()
	defer s.Close()
	if err != nil {
		return errors.Wrap(err, "Error creating new session for ssh client")
	}

	return s.Run(cmd)
}
开发者ID:gashcrumb,项目名称:gofabric8,代码行数:9,代码来源:sshutil.go

示例13: RunCommand

func RunCommand(c *ssh.Client, cmd string) error {
	s, err := c.NewSession()
	defer s.Close()
	if err != nil {
		return err
	}

	return s.Run(cmd)
}
开发者ID:rawlingsj,项目名称:gofabric8,代码行数:9,代码来源:sshutil.go

示例14: combined

func combined(c *ssh.Client, cmd string) ([]byte, error) {
	s, err := c.NewSession()
	if err != nil {
		return nil, err
	}
	defer s.Close()

	return s.CombinedOutput(cmd)
}
开发者ID:rwcarlsen,项目名称:cloudlus,代码行数:9,代码来源:condorbots.go

示例15: createSession

func createSession(client *ssh.Client) (*ssh.Session, error) {
	fmt.Println("Creating new session")
	session, err := client.NewSession()
	if err != nil {
		fmt.Println("Failed to create session")
		fmt.Println("Error : ", err.Error())
		return nil, err
	}

	return session, nil
}
开发者ID:abhigupta912,项目名称:learngo,代码行数:11,代码来源:executor.go


注:本文中的golang.org/x/crypto/ssh.Client.NewSession方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。