本文整理汇总了Golang中golang.org/x/crypto/ssh.Session.Run方法的典型用法代码示例。如果您正苦于以下问题:Golang Session.Run方法的具体用法?Golang Session.Run怎么用?Golang Session.Run使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类golang.org/x/crypto/ssh.Session
的用法示例。
在下文中一共展示了Session.Run方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: sshExecNative
func sshExecNative(c conf.ServerInfo, cmd string, sudo bool, log ...*logrus.Entry) (result sshResult) {
logger := getSSHLogger(log...)
cmd = decolateCmd(c, cmd, sudo)
logger.Debugf("Command: %s",
strings.Replace(maskPassword(cmd, c.Password), "\n", "", -1))
var client *ssh.Client
var err error
client, err = sshConnect(c)
defer client.Close()
var session *ssh.Session
if session, err = client.NewSession(); err != nil {
logger.Errorf("Failed to new session. err: %s, c: %s",
err,
pp.Sprintf("%v", c))
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 {
logger.Errorf("Failed to request for pseudo terminal. err: %s, c: %s",
err,
pp.Sprintf("%v", c))
result.ExitStatus = 999
return
}
var stdoutBuf, stderrBuf bytes.Buffer
session.Stdout = &stdoutBuf
session.Stderr = &stderrBuf
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.Host = c.Host
result.Port = c.Port
logger.Debugf(
"SSH executed. cmd: %s, err: %#v, status: %d\nstdout: \n%s\nstderr: \n%s",
maskPassword(cmd, c.Password), err, result.ExitStatus, result.Stdout, result.Stderr)
return
}
示例2: copy
func (this *Scp) copy(size int64, mode os.FileMode, fileName string, contents io.Reader, destination string) error {
var (
session *ssh.Session
err error
)
ParallelController[this.Server].Session <- token
session, err = this.client.NewSession()
if nil != err {
return errors.New("Failed to create new session" + err.Error())
}
go func() {
w, _ := session.StdinPipe()
defer w.Close()
fmt.Fprintf(w, "C%#o %d %s\n", mode, size, fileName)
io.Copy(w, contents)
fmt.Fprint(w, "\x00")
<-ParallelController[this.Server].Session
}()
cmd := fmt.Sprintf("scp -t %s", destination)
if err := session.Run(cmd); nil != err {
return err
}
session.Close()
return nil
}
示例3: runToHost
func runToHost(user, pass, host, cmd string) {
sshConfig := &ssh.ClientConfig{
User: user,
Auth: []ssh.AuthMethod{ssh.Password(pass)},
}
sshConfig.SetDefaults()
client, err := ssh.Dial("tcp", host, sshConfig)
if err != nil {
// errors.Wrap(err, err.Error())
fmt.Println(err.Error())
}
var session *ssh.Session
session, err = client.NewSession()
if err != nil {
// errors.Wrap(err, err.Error())
fmt.Println(err.Error())
}
defer session.Close()
var stdoutBuf bytes.Buffer
session.Stdout = &stdoutBuf
session.Run(cmd)
fmt.Println(stdoutBuf.String())
}
示例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
}
示例5: executeCommand
func (config *Config) executeCommand(s *ssh.Session, cmd string, sudo bool) ([]byte, error) {
if s.Stdout != nil {
return nil, errors.New("ssh: Stdout already set")
}
if s.Stderr != nil {
return nil, errors.New("ssh: Stderr already set")
}
b := newSingleWriterReader()
s.Stdout = &b
s.Stderr = &b
done := make(chan bool)
if sudo {
stdInWriter, err := s.StdinPipe()
if err != nil {
if config.AbortOnError == true {
log.Fatalf("%s", err)
}
return nil, err
}
go config.injectSudoPasswordIfNecessary(done, &b, stdInWriter)
}
err := s.Run(cmd)
close(done)
return b.Bytes(), err
}
示例6: 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
}
示例7: 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))
}
示例8: 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
}
示例9: copy
func copy(size int64, mode os.FileMode, fileName string, contents io.Reader, destination string, session *ssh.Session) error {
defer session.Close()
go func() {
w, _ := session.StdinPipe()
defer w.Close()
fmt.Fprintf(w, "C%#o %d %s\n", mode, size, fileName)
io.Copy(w, contents)
fmt.Fprint(w, "\x00")
}()
cmd := fmt.Sprintf("scp -t %s", destination)
if err := session.Run(cmd); err != nil {
return err
}
return nil
}
示例10: 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()
if err := s.RequestPty("vt100", 80, 25, ssh.TerminalModes{}); err != nil {
fmt.Println(err)
return err
}
return s.Run(newCmdStrWithSource(cmd))
}
示例11: RunCommand
func (client *SSHClient) RunCommand(cmd *SSHCommand) error {
var (
session *ssh.Session
err error
)
if session, err = client.newSession(); err != nil {
return err
}
defer session.Close()
if err = client.prepareCommand(session, cmd); err != nil {
return err
}
err = session.Run(cmd.Path)
return err
}
示例12: writeFileToHost
func writeFileToHost(session *ssh.Session, host *Host, file string, fileReader *os.File, fileInfo os.FileInfo, destination string, sessionWaitGroup *sync.WaitGroup) {
defer sessionWaitGroup.Done()
defer session.Close()
sessionWaitGroup.Add(1)
go func() {
defer sessionWaitGroup.Done()
mode := uint32(fileInfo.Mode().Perm())
header := fmt.Sprintf("C%04o %d %s\n", mode, fileInfo.Size(), filepath.Base(file))
OutputLocal(fmt.Sprintf("copy %s (%dMB) to %s:%s", file, fileInfo.Size()/1024/2014, host.Host, destination))
stdinPipe, _ := session.StdinPipe()
defer stdinPipe.Close()
_, err := stdinPipe.Write([]byte(header))
if err != nil {
return
}
_, err = io.Copy(stdinPipe, fileReader)
if err != nil {
return
}
_, err = stdinPipe.Write([]byte{0})
if err != nil {
return
}
}()
if err := session.Run("/usr/bin/scp -trv " + destination); err != nil {
fmt.Println("in here")
fmt.Println(err.Error())
os.Exit(1)
}
}
示例13: execCmd
func (sshTransport *SSHTransport) execCmd(session *ssh.Session, cmd string) (*bytes.Buffer, error) {
modes := ssh.TerminalModes{
ECHO: 0,
TTY_OP_ISPEED: 14400,
TTY_OP_OSPEED: 14400,
}
if err := session.RequestPty("xterm", 100, 80, modes); err != nil {
return nil, HenchErr(err, nil, "request for psuedo terminal failed")
}
var stdoutbuf bytes.Buffer
session.Stdout = &stdoutbuf
err := session.Run(cmd)
if err != nil {
return nil, HenchErr(err, map[string]interface{}{
"output": string(stdoutbuf.String()),
}, "While retrieving output from ssh")
}
return &stdoutbuf, nil
}
示例14:
BeforeEach(func() {
var sessionErr error
session, sessionErr = client.NewSession()
Expect(sessionErr).NotTo(HaveOccurred())
})
It("can use the session to execute a command with stdout and stderr", func() {
stdout, err := session.StdoutPipe()
Expect(err).NotTo(HaveOccurred())
stderr, err := session.StderrPipe()
Expect(err).NotTo(HaveOccurred())
err = session.Run("/bin/echo -n Hello; /bin/echo -n Goodbye >&2")
Expect(err).NotTo(HaveOccurred())
stdoutBytes, err := ioutil.ReadAll(stdout)
Expect(err).NotTo(HaveOccurred())
Expect(stdoutBytes).To(Equal([]byte("Hello")))
stderrBytes, err := ioutil.ReadAll(stderr)
Expect(err).NotTo(HaveOccurred())
Expect(stderrBytes).To(Equal([]byte("Goodbye")))
})
It("returns when the process exits", func() {
stdin, err := session.StdinPipe()
Expect(err).NotTo(HaveOccurred())
示例15:
BeforeEach(func() {
var sessionErr error
session, sessionErr = client.NewSession()
Expect(sessionErr).NotTo(HaveOccurred())
})
FIt("can use the session to execute a command with stdout and stderr", func() {
stdout, err := session.StdoutPipe()
Expect(err).NotTo(HaveOccurred())
stderr, err := session.StderrPipe()
Expect(err).NotTo(HaveOccurred())
// err = session.Run("echo Hello && echo Goodbye >&2")
err = session.Run("dir\r\n")
Expect(err).NotTo(HaveOccurred())
stdoutBytes, err := ioutil.ReadAll(stdout)
Expect(err).NotTo(HaveOccurred())
Expect(stdoutBytes).To(Equal([]byte("Hello\n")))
stderrBytes, err := ioutil.ReadAll(stderr)
Expect(err).NotTo(HaveOccurred())
Expect(stderrBytes).To(Equal([]byte("Goodbye\n")))
})
It("returns when the process exits", func() {
stdin, err := session.StdinPipe()
Expect(err).NotTo(HaveOccurred())