• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Golang ssh.Session类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



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

示例1: pipe

func pipe(ch ssh.Channel, client *ssh.Client, session *ssh.Session, command string) (int, error) {
	targetStderr, err := session.StderrPipe()
	if err != nil {
		return -1, errors.New("fail to pipe stderr: " + err.Error())
	}
	targetStdout, err := session.StdoutPipe()
	if err != nil {
		return -1, errors.New("fail to pipe stdout: " + err.Error())
	}
	targetStdin, err := session.StdinPipe()
	if err != nil {
		return -1, errors.New("fail to pipe stdin: " + err.Error())
	}

	go io.Copy(targetStdin, ch)
	go io.Copy(ch.Stderr(), targetStderr)
	go io.Copy(ch, targetStdout)

	err = session.Start(command)
	if err != nil {
		ch.Write([]byte("Error when starting '" + command + "': " + err.Error()))
		ch.Close()
	}

	err = session.Wait()
	if err != nil {
		if err, ok := err.(*ssh.ExitError); ok {
			return err.ExitStatus(), nil
		} else {
			return -1, errors.New("failed to wait ssh command: " + err.Error())
		}
	}

	return 0, nil
}
开发者ID:psihodelik,项目名称:go-ssh-examples,代码行数:35,代码来源:server.go


示例2: 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


示例3: send_script

/*
	Expected to be invoked as a goroutine which runs in parallel to sending the ssh command to the
	far side. This function reads from the input buffer reader br and writes to the target stripping
	blank and comment lines as it goes.
*/
func send_script(sess *ssh.Session, argv0 string, env_file string, br *bufio.Reader) {

	target, err := sess.StdinPipe() // we create the pipe here so that we can close here
	if err != nil {
		fmt.Fprintf(os.Stderr, "unable to create stdin for session: %s\n", err)
		return
	}
	defer target.Close()

	if argv0 != "" {
		target.Write([]byte("ARGV0=\"" + argv0 + "\"\n")) // $0 isn't valid using this, so simulate $0 with argv0
	}

	if env_file != "" { // must push out the environment first
		env_file, err = find_file(env_file) // find it in the path if not a qualified name
		if err == nil {
			ef, err := os.Open(env_file)

			if err != nil {
				fmt.Fprintf(os.Stderr, "ssh_broker: could not open environment file: %s: %s\n", env_file, err)
			} else {
				ebr := bufio.NewReader(ef) // get a buffered reader for the file
				send_file(ebr, target)
				ef.Close()
			}
		} else {
			fmt.Fprintf(os.Stderr, "ssh_broker: could not find  environment file: %s: %s\n", env_file, err)
		}
	}

	send_file(br, target)
}
开发者ID:prydeep,项目名称:gopkgs,代码行数:37,代码来源:ssh_broker.go


示例4: runSudoCommand

func (s *sshConn) runSudoCommand(sess *ssh.Session, stdin io.Writer, cmd string) error {
	// Wrap the output
	if s.DebugEnabled() {
		debugOutWriter := util.NewDebugLogWriter("SSH OUT:", s.Context)
		if sess.Stdout != nil {
			sess.Stdout = io.MultiWriter(sess.Stdout, debugOutWriter)
		} else {
			sess.Stdout = debugOutWriter
		}
		debugErrWriter := util.NewDebugLogWriter("SSH ERR:", s.Context)
		if sess.Stderr != nil {
			sess.Stderr = io.MultiWriter(sess.Stderr, debugErrWriter)
		} else {
			sess.Stderr = debugErrWriter
		}
	}
	// We need a checker to enter the password
	passwordTyper := util.NewExpectListener(stdin, shell.SudoPasswordPromptMatch, s.server.SSH.Pass+"\n")

	if sess.Stdout == nil {
		sess.Stdout = passwordTyper
	} else {
		sess.Stdout = io.MultiWriter(sess.Stdout, passwordTyper)
	}
	if sess.Stderr == nil {
		sess.Stderr = passwordTyper
	} else {
		sess.Stderr = io.MultiWriter(sess.Stderr, passwordTyper)
	}
	if err := sess.Run("sudo -S " + cmd); err != nil {
		return fmt.Errorf("Error running command %v: %v", cmd, err)
	}
	return nil
}
开发者ID:cretz,项目名称:systrument,代码行数:34,代码来源:ssh.go


示例5: StartCommand

func (cmd *command) StartCommand() (error, *ssh.Session) {
	var (
		session *ssh.Session
		err     error
	)

	z := cmd.zh

	// open ssh link
	if z.client == nil {
		if err = z.dialSSH(); err != nil {
			return err, nil
		}
	}

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

	// setup env, stdin, stdout, stderr
	if err = prepareCommand(session, cmd); err != nil {
		return err, nil
	}

	// start remote command
	err = session.Start(cmd.Path)
	if err == nil {
		return err, session
	}
	return err, nil
}
开发者ID:edillmann,项目名称:go-zfs,代码行数:32,代码来源:sshutils.go


示例6: Run

func (c *command) Run(arg ...string) ([][]string, error) {

	var err error
	var cmd waitable
	var session *ssh.Session

	joinedArgs := strings.Join(arg, " ")
	c.Path = c.Command + " " + joinedArgs
	c.Env = []string{"LC_CTYPE=C", "LANG=en_US.UTF-8"}
	id := uuid.New()
	logger.Log([]string{"ID:" + id, "START", c.Path})
	if c.zh.Local {
		lcmd := c.LocalPrepare(arg...)
		err = lcmd.Start()
		cmd = lcmd
	} else {
		err, session = c.StartCommand()
		if session != nil {
			defer func() {
				session.Close()
			}()
		}
		cmd = session
	}

	logger.Log([]string{"ID:" + id, "DONE"})

	if err != nil {
		return nil, &Error{
			Err:    err,
			Debug:  strings.Join([]string{c.Command, joinedArgs}, " "),
			Stderr: c.stderr.String(),
		}
	}

	if err = cmd.Wait(); err != nil {
		return nil, &Error{
			Err:    err,
			Stderr: c.stderr.String(),
			Debug:  strings.Join([]string{c.Command, joinedArgs}, " "),
		}
	}

	// assume if you passed in something for stdout, that you know what to do with it
	if c.Stdout != nil {
		return nil, nil
	}

	lines := strings.Split(c.stdout.String(), "\n")
	//last line is always blank
	lines = lines[0 : len(lines)-1]
	output := make([][]string, len(lines))

	for i, l := range lines {
		output[i] = strings.Fields(l)
	}
	return output, err

}
开发者ID:edillmann,项目名称:go-zfs,代码行数:59,代码来源:utils.go


示例7: execLine

func execLine(session *ssh.Session, cmd string) {
	out, err := session.CombinedOutput(cmd)
	if err != nil {
		// panic(err)
		log.Fatal(err.Error())
	}
	fmt.Println(string(out))
}
开发者ID:grengojbo,项目名称:sw-cli,代码行数:8,代码来源:commands.go


示例8: NewSSHClientSession

//NewSSHClientSession creates a new ssh session instance
func NewSSHClientSession(s *ssh.Session, in io.Reader) *SSHClientSession {
	out := new(bytes.Buffer)
	err := new(bytes.Buffer)
	s.Stdin = in
	s.Stdout = out
	s.Stderr = err
	return &SSHClientSession{s, in, out, err}
}
开发者ID:influx6,项目名称:goproj,代码行数:9,代码来源:formats.go


示例9: RequestAgentForwarding

// RequestAgentForwarding sets up agent forwarding for the session.
// ForwardToAgent or ForwardToRemote should be called to route
// the authentication requests.
func RequestAgentForwarding(session *ssh.Session) error {
	ok, err := session.SendRequest("[email protected]", true, nil)
	if err != nil {
		return err
	}
	if !ok {
		return errors.New("forwarding request denied")
	}
	return nil
}
开发者ID:Clarifai,项目名称:kubernetes,代码行数:13,代码来源:forward.go


示例10: 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


示例11: configureSessionEnv

func configureSessionEnv(session *ssh.Session, env map[string]string) error {
	fmt.Println("Setting environment variables")

	for key, value := range env {
		if err := session.Setenv(key, value); err != nil {
			fmt.Printf("Unable to set environment %s = %s\n", key, value)
			return err
		}
	}

	fmt.Println("Done setting environment variables")
	return nil
}
开发者ID:abhigupta912,项目名称:learngo,代码行数:13,代码来源:executor.go


示例12: RunCommand

// RunCommand runs a shell command in a vagrant node and returns it's exit status
func (n *VagrantNode) RunCommand(cmd string) error {
	var (
		s   *ssh.Session
		err error
	)

	if s, err = n.client.NewSession(); err != nil {
		return err
	}
	defer s.Close()

	return s.Run(newCmdStrWithSource(cmd))
}
开发者ID:balajisiva,项目名称:netplugin,代码行数:14,代码来源:vagrantnode.go


示例13: prepareCommand

func (client *clientSSH) prepareCommand(session *ssh.Session, cmd *sshCommand) error {
	for _, env := range cmd.env {
		variable := strings.Split(env, "=")
		if len(variable) != 2 {
			continue
		}

		if err := session.Setenv(variable[0], variable[1]); err != nil {
			return err
		}
	}

	return nil
}
开发者ID:ccirello,项目名称:gochatbot,代码行数:14,代码来源:ssh.go


示例14: RunCommandWithOutput

// RunCommandWithOutput runs a shell command in a vagrant node and returns it's
// exit status and output
func (n *VagrantNode) RunCommandWithOutput(cmd string) (string, error) {
	var (
		s   *ssh.Session
		err error
	)

	if s, err = n.client.NewSession(); err != nil {
		return "", err
	}
	defer s.Close()

	output, err := s.CombinedOutput(newCmdStrWithSource(cmd))
	return string(output), err
}
开发者ID:balajisiva,项目名称:netplugin,代码行数:16,代码来源:vagrantnode.go


示例15: NewClient

// NewClient creates a new SFTP client on top of an already created
// ssh.Session.
func NewClient(s *ssh.Session) (*Client, error) {
	stdin, err := s.StdinPipe()
	if err != nil {
		return nil, err
	}
	stdout, err := s.StdoutPipe()
	if err != nil {
		return nil, err
	}
	stderr, err := s.StderrPipe()
	if err != nil {
		return nil, err
	}

	if err := s.RequestSubsystem("sftp"); err != nil {
		return nil, err
	}
	sftp := &Client{
		stdin:   stdin,
		stdout:  stdout,
		stderr:  stderr,
		chans:   &fxpChanList{},
		session: s,
	}

	if err := sftp.init(); err != nil {
		return nil, err
	}
	return sftp, nil
}
开发者ID:CodyGuo,项目名称:gosftp,代码行数:32,代码来源:client.go


示例16: executeCommand

// Executes a command on an SSH session struct, return an error if there is one
func executeCommand(cmd string, session *ssh.Session) (string, error) {
	//Runs CombinedOutput, which takes cmd and returns stderr and stdout of the command
	out, err := session.CombinedOutput(cmd)
	if err != nil {
		return "", err
	}

	// Convert our output to a string
	tmpOut := string(out)
	tmpOut = strings.Replace(tmpOut, "\n", "<br>", -1)

	// Return a string version of our result
	return tmpOut, nil
}
开发者ID:CroweCybersecurity,项目名称:go-sshscan,代码行数:15,代码来源:main.go


示例17: RunCommand

func (client *SSHClient) RunCommand(cmd *SSHCommand) (error, interface{}) {
	rescueStdout := os.Stdout
	r, w, _ := os.Pipe()
	cmd.Stdout = w

	var (
		session *ssh.Session
		err     error
	)
	fmt.Println("Session creation")
	if session, err = client.newSession(); err != nil {
		fmt.Println("Session creation  err", err)
		return err, nil
	}
	defer session.Close()

	if err = client.prepareCommand(session, cmd); err != nil {
		return err, nil
	}

	fmt.Println("Session run", cmd.Path)
	if err = session.Run(cmd.Path); err != nil {
		fmt.Println("Session run err", err)
		return err, nil
	}
	print(cmd.Stdout)

	w.Close()

	out, _ := ioutil.ReadAll(r)
	os.Stdout = rescueStdout

	if strings.Contains(cmd.Path, "providerLib") {

		s1 := string([]byte(out))

		return err, s1
	} else if strings.Contains(cmd.Path, "build") {
		fmt.Printf("-->%s<--", string([]byte(out)))

		s1 := string([]byte(out))

		return err, s1
	}
	defer w.Close()
	defer r.Close()

	return err, nil
}
开发者ID:nerfmiester,项目名称:repofinder,代码行数:49,代码来源:repofinder.go


示例18: RunCommandAndWait

func (client *SSHClient) RunCommandAndWait(cmd *SSHCommand) ([]byte, error) {
	var (
		session *ssh.Session
		err     error
		baData  []byte
	)

	if session, err = client.newSession(); err != nil {
		return nil, err
	}
	defer session.Close()

	baData, err = session.Output(cmd.Path)
	return baData, err
}
开发者ID:jpeters71,项目名称:gtailer,代码行数:15,代码来源:sshclient.go


示例19: runCommand

func (client *clientSSH) runCommand(cmd *sshCommand) ([]byte, error) {
	var session *ssh.Session
	var err error

	if session, err = client.newSession(); err != nil {
		return []byte{}, err
	}
	defer session.Close()

	if err = client.prepareCommand(session, cmd); err != nil {
		return []byte{}, err
	}

	return session.CombinedOutput(cmd.command)
}
开发者ID:ccirello,项目名称:gochatbot,代码行数:15,代码来源:ssh.go


示例20: logSession

func logSession(session *ssh.Session) {
	{
		r, err := session.StdoutPipe()
		if err != nil {
			exitf("failed to get stdoutPipe: %s", err)
		}
		go io.Copy(os.Stdout, r)
	}
	{
		r, err := session.StderrPipe()
		if err != nil {
			exitf("failed to get StderrPipe: %s", err)
		}
		go io.Copy(os.Stderr, r)
	}
}
开发者ID:BrianNewsom,项目名称:harp,代码行数:16,代码来源:migration.go



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Golang agent.ForwardToAgent函数代码示例发布时间:2022-05-28
下一篇:
Golang ssh.ServerConn类代码示例发布时间:2022-05-28
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap