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

Golang pty.Start函数代码示例

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

本文整理汇总了Golang中github.com/kr/pty.Start函数的典型用法代码示例。如果您正苦于以下问题:Golang Start函数的具体用法?Golang Start怎么用?Golang Start使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



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

示例1: runCmd

// run command from basedir and print output to stdout.
func runCmd(baseDir string, env []string, command string, args ...string) error {
	cmd := exec.Command(command, args...)
	if baseDir != "" {
		cmd.Dir = baseDir
	}
	cmd.Env = env

	// print command being run
	fmt.Println("$", strings.Join(cmd.Args, " "))

	tty, err := pty.Start(cmd)
	if err != nil {
		return err
	}

	scanner := bufio.NewScanner(tty)
	var wg sync.WaitGroup
	wg.Add(1)
	go func() {
		defer wg.Done()
		for scanner.Scan() {
			out := scanner.Text()
			fmt.Printf("%s\n", fmtOutput(out))
		}
	}()

	err = cmd.Wait()
	if err != nil {
		return err
	}

	wg.Wait()

	return nil
}
开发者ID:mikkeloscar,项目名称:maze-build,代码行数:36,代码来源:util.go


示例2: Run

func (this *DockerServer) Run() {
	f, err := pty.Start(this.cmd)
	if err != nil {
		panic(err)
	}
	io.Copy(os.Stdout, f)
}
开发者ID:hugb,项目名称:beege-controller,代码行数:7,代码来源:server.go


示例3: establishPty

func establishPty(session *SessionConfig) error {
	defer trace.End(trace.Begin("initializing pty handling for session " + session.ID))

	// TODO: if we want to allow raw output to the log so that subsequent tty enabled
	// processing receives the control characters then we should be binding the PTY
	// during attach, and using the same path we have for non-tty here
	session.wait = &sync.WaitGroup{}

	var err error
	session.Pty, err = pty.Start(&session.Cmd)
	if session.Pty != nil {
		session.wait.Add(1)

		// TODO: do we need to ensure all reads have completed before calling Wait on the process?
		// it frees up all resources - does that mean it frees the output buffers?
		go func() {
			_, gerr := io.Copy(session.Outwriter, session.Pty)
			log.Debugf("PTY stdout copy: %s", gerr)

			session.wait.Done()
		}()
		go func() {
			_, gerr := io.Copy(session.Pty, session.Reader)
			log.Debugf("PTY stdin copy: %s", gerr)
		}()
	}

	return err
}
开发者ID:vmware,项目名称:vic,代码行数:29,代码来源:tether_linux.go


示例4: execHost

func (r *Reporter) execHost(req xfer.Request) xfer.Response {
	cmd := exec.Command(r.hostShellCmd[0], r.hostShellCmd[1:]...)
	cmd.Env = []string{"TERM=xterm"}
	ptyPipe, err := pty.Start(cmd)
	if err != nil {
		return xfer.ResponseError(err)
	}

	id, pipe, err := controls.NewPipeFromEnds(nil, ptyPipe, r.pipes, req.AppID)
	if err != nil {
		return xfer.ResponseError(err)
	}
	pipe.OnClose(func() {
		if err := cmd.Process.Kill(); err != nil {
			log.Errorf("Error stopping host shell: %v", err)
		}
		if err := ptyPipe.Close(); err != nil {
			log.Errorf("Error closing host shell's pty: %v", err)
		}
		log.Info("Host shell closed.")
	})
	go func() {
		if err := cmd.Wait(); err != nil {
			log.Errorf("Error waiting on host shell: %v", err)
		}
		pipe.Close()
	}()

	return xfer.Response{
		Pipe:   id,
		RawTTY: true,
	}
}
开发者ID:dilgerma,项目名称:scope,代码行数:33,代码来源:controls.go


示例5: Login

func (sshConfig *SSHConfig) Login() string {
	// beego.Debug(sshConfig.Agent.LoginName, sshConfig.Agent.Host)
	var err error
	sshConfig.WsPty.Cmd = exec.Command("ssh", "-o", "StrictHostKeyChecking=no", sshConfig.Agent.LoginName+"@"+sshConfig.Agent.Host)
	sshConfig.WsPty.Pty, err = pty.Start(sshConfig.WsPty.Cmd)
	if err != nil {
		beego.Error("Failed to start command: %s\n", err)
	}

	i := 0
	for {
		if i >= 10 {
			beego.Error("login error")
			sshConfig.WsPty.Pty.Close()
			return "login error"
		}
		buf := make([]byte, 1024)
		size, err := sshConfig.WsPty.Pty.Read(buf)
		if err != nil {
			beego.Error("login Read error")
		}

		if !strings.Contains(string([]byte(buf[:size])), "password") {
			i++
			continue
		}

		_, err = sshConfig.WsPty.Pty.Write([]byte(sshConfig.Agent.LoginPass + "\n"))
		if err != nil {
			beego.Error("login Write error")
		}
		return ""
	}
}
开发者ID:11101171,项目名称:violence,代码行数:34,代码来源:sshService.go


示例6: Start

// Start will create start cmd and return a PTY wrapping it. The PTY implements
// ReadWriteCloser and must be closed when execution is done.
//
// Note: This will overwrite stdio for cmd.
func Start(cmd *exec.Cmd) (*PTY, error) {
	f, err := pty.Start(cmd)
	if err != nil {
		return nil, err
	}
	return &PTY{f}, nil
}
开发者ID:taskcluster,项目名称:taskcluster-worker,代码行数:11,代码来源:pty_unix.go


示例7: TestExecInteractiveStdinClose

// regression test for #12546
func (s *DockerSuite) TestExecInteractiveStdinClose(c *check.C) {
	testRequires(c, DaemonIsLinux)
	out, _ := dockerCmd(c, "run", "-itd", "busybox", "/bin/cat")
	contID := strings.TrimSpace(out)

	cmd := exec.Command(dockerBinary, "exec", "-i", contID, "echo", "-n", "hello")
	p, err := pty.Start(cmd)
	if err != nil {
		c.Fatal(err)
	}

	b := bytes.NewBuffer(nil)
	go io.Copy(b, p)

	ch := make(chan error)
	go func() { ch <- cmd.Wait() }()

	select {
	case err := <-ch:
		if err != nil {
			c.Errorf("cmd finished with error %v", err)
		}
		if output := b.String(); strings.TrimSpace(output) != "hello" {
			c.Fatalf("Unexpected output %s", output)
		}
	case <-time.After(1 * time.Second):
		c.Fatal("timed out running docker exec")
	}
}
开发者ID:waterytowers,项目名称:global-hack-day-3,代码行数:30,代码来源:docker_cli_exec_unix_test.go


示例8: handleWS

func (app *App) handleWS(w http.ResponseWriter, r *http.Request) {
	log.Printf("New client connected: %s", r.RemoteAddr)

	if r.Method != "GET" {
		http.Error(w, "Method not allowed", 405)
		return
	}

	conn, err := app.upgrader.Upgrade(w, r, nil)
	if err != nil {
		log.Print("Failed to upgrade connection")
		return
	}

	cmd := exec.Command(app.options.Command[0], app.options.Command[1:]...)
	ptyIo, err := pty.Start(cmd)
	if err != nil {
		log.Print("Failed to execute command")
		return
	}
	log.Printf("Command is running for client %s with PID %d", r.RemoteAddr, cmd.Process.Pid)

	context := &clientContext{
		app:        app,
		request:    r,
		connection: conn,
		command:    cmd,
		pty:        ptyIo,
	}

	context.goHandleClient()
}
开发者ID:kryptBlue,项目名称:gotty,代码行数:32,代码来源:app.go


示例9: ptyExec

func ptyExec(test *testing.T, mux *pat.Router) {
	mux.Post("/exec", func(res http.ResponseWriter, req *http.Request) {
		test.Log("got exec")
		conn, rw, err := res.(http.Hijacker).Hijack()
		if err != nil {
			res.WriteHeader(http.StatusInternalServerError)
			res.Write([]byte(err.Error()))
			return
		}
		defer conn.Close()
		script := req.FormValue("cmd")
		if script == "" {
			test.Log("missing script")
			test.FailNow()
		}
		test.Log("executing", script)
		cmd := exec.Command("/bin/bash", "-c", script)
		file, err := pty.Start(cmd)
		if err != nil {
			test.Log(err)
			test.FailNow()
		}
		test.Log("copying from pty")
		go io.Copy(file, rw)
		io.Copy(conn, file)
		test.Log("finished running")
	})
}
开发者ID:sfermigier,项目名称:nanobox,代码行数:28,代码来源:exec_test.go


示例10: TestPtySanity

/**
Expect:
 - all of the input to come back out, because terminals default to echo mode.
 - then the grep'd string should come out, because the command recieved it and matched.
 - the grep'd string should come out surrounded by the escape codes for color, since grep's auto mode should detect that we're in a terminal.
*/
func TestPtySanity(t *testing.T) {
	assert := assrt.NewAssert(t)

	c := exec.Command("grep", "--color=auto", "bar")
	f, err := pty.Start(c)
	if err != nil {
		t.Fatal(err)
	}

	go func() {
		f.Write([]byte("foo\nbar\nbaz\n"))
		/*
			All of the input must be written in a single call to prevent this test from occationally failing nondeterministically, because:
			grep operates stream-wise and will start printing output before it has all of its input,
			and 3/4ths of the output lines are actually from the terminal operating in echo mode on the same channel.
			So there's actually a race between the terminal itself (somewhere down in kernel land I suppose?) and the output of grep.
		*/
		f.Write([]byte{4}) // EOT
	}()

	outBuffer := new(bytes.Buffer)
	io.Copy(outBuffer, f)
	out := string(outBuffer.Bytes())

	expected := // I have no idea where the CR characters come from.
		"foo\r\n" +
			"bar\r\n" +
			"baz\r\n" +
			"[01;31m[Kbar[m[K\r\n"

	assert.Equal(
		expected,
		out,
	)
}
开发者ID:nk23x,项目名称:siphon-cli,代码行数:41,代码来源:siphon_test.go


示例11: Login

func (this *SSH_Config) Login() error {
	var err error
	this.Command = exec.Command("ssh", "-o", "StrictHostKeyChecking=no", this.Username+"@"+this.Ip)
	this.Pty, err = pty.Start(this.Command)
	if err != nil {
		return err
	}
	i := 0
	for {
		if i >= 10 {

			return errors.New("login error")
		}
		buf := make([]byte, 1024)
		size, err2 := this.Pty.Read(buf)
		if err2 != nil {
			return err
		}

		if !strings.Contains(string([]byte(buf[:size])), "password") {
			i++
			continue
		}
		this.Pty.Write([]byte(this.Password + "\n"))
		if err != nil {
			panic(err)
		}
		if err != nil {
			return errors.New("login error")
		}
		return nil
	}
}
开发者ID:wuwenbao,项目名称:GoWebSSH,代码行数:33,代码来源:ssh_login.go


示例12: TestStartWithTty

func (s *RunVSuite) TestStartWithTty(c *check.C) {
	ctrName := "TestStartWithTty"
	spec := defaultTestSpec
	spec.Process.Terminal = true
	spec.Process.Args = []string{"sh"}
	c.Assert(s.addSpec(&spec), checker.IsNil)

	cmdArgs := []string{"--kernel", s.kernelPath, "--initrd", s.initrdPath}
	cmdArgs = append(cmdArgs, "start", "--bundle", s.bundlePath, ctrName)
	cmd := exec.Command(s.binaryPath, cmdArgs...)
	tty, err := pty.Start(cmd)
	c.Assert(err, checker.IsNil)
	defer tty.Close()

	_, err = tty.Write([]byte("uname && sleep 2 && exit\n"))
	c.Assert(err, checker.IsNil)

	chErr := make(chan error)
	go func() {
		chErr <- cmd.Wait()
	}()
	select {
	case err := <-chErr:
		c.Assert(err, checker.IsNil)
	case <-time.After(15 * time.Second):
		c.Fatal("timeout waiting for start to exit")
	}

	buf := make([]byte, 256)
	n, err := tty.Read(buf)
	c.Assert(err, checker.IsNil)
	c.Assert(bytes.Contains(buf, []byte("Linux")), checker.Equals, true, check.Commentf(string(buf[:n])))
}
开发者ID:hyperhq,项目名称:runv,代码行数:33,代码来源:start_test.go


示例13: TestExecTTY

func (s *DockerSuite) TestExecTTY(c *check.C) {
	testRequires(c, DaemonIsLinux, SameHostDaemon)
	dockerCmd(c, "run", "-d", "--name=test", "busybox", "sh", "-c", "echo hello > /foo && top")

	cmd := exec.Command(dockerBinary, "exec", "-it", "test", "sh")
	p, err := pty.Start(cmd)
	c.Assert(err, checker.IsNil)
	defer p.Close()

	_, err = p.Write([]byte("cat /foo && exit\n"))
	c.Assert(err, checker.IsNil)

	chErr := make(chan error)
	go func() {
		chErr <- cmd.Wait()
	}()
	select {
	case err := <-chErr:
		c.Assert(err, checker.IsNil)
	case <-time.After(3 * time.Second):
		c.Fatal("timeout waiting for exec to exit")
	}

	buf := make([]byte, 256)
	read, err := p.Read(buf)
	c.Assert(err, checker.IsNil)
	c.Assert(bytes.Contains(buf, []byte("hello")), checker.Equals, true, check.Commentf(string(buf[:read])))
}
开发者ID:docker,项目名称:docker,代码行数:28,代码来源:docker_cli_exec_unix_test.go


示例14: pipePty

func pipePty(cmd *exec.Cmd, handler *interactive.ShellHandler) error {
	// Start the shell as TTY
	f, err := pty.Start(cmd)
	if err == nil {
		// Connect pipes (close stderr as tty only has two streams)
		go ioext.CopyAndClose(f, handler.StdinPipe())
		go ioext.CopyAndClose(handler.StdoutPipe(), f)
		go handler.StderrPipe().Close()

		// Start communication
		handler.Communicate(func(cols, rows uint16) error {
			return setTTYSize(f, cols, rows)
		}, func() error {
			if cmd.Process != nil {
				return cmd.Process.Kill()
			}
			return nil
		})
	}
	// If pty wasn't supported for some reason we fall back to normal execution
	if err == pty.ErrUnsupported {
		return pipeCommand(cmd, handler)
	}
	if err != nil {
		handler.Communicate(nil, func() error {
			// If cmd.Start() failed, then we don't have a process, but we start
			// the communication flow anyways.
			if cmd.Process != nil {
				return cmd.Process.Kill()
			}
			return nil
		})
	}
	return err
}
开发者ID:taskcluster,项目名称:taskcluster-worker,代码行数:35,代码来源:pty_unix.go


示例15: NewPty

func NewPty(cmd *exec.Cmd) (*Pty, error) {
	cmdPty, err := pty.Start(cmd)
	if err != nil {
		return nil, err
	}
	return &Pty{cmdPty}, nil
}
开发者ID:clauswitt,项目名称:envy,代码行数:7,代码来源:hterm.go


示例16: startProcess

func startProcess(command string, stdin <-chan rune, stdout chan<- rune) {
	tty, _ := pty.Start(stringToCmd(command))

	input, _ := os.Create("/tmp/nutsh-input")
	output, _ := os.Create("/tmp/nutsh-output")

	go func() {
		for {
			r, ok := <-stdin
			if !ok {
				return
			}
			input.Write([]byte(string(r)))
			tty.Write([]byte(string(r)))
		}
	}()

	go func() {
		reader := bufio.NewReader(tty)
		for {
			r, _, err := reader.ReadRune()
			if err != nil {
				close(stdout)
				return
			}
			output.Write([]byte(string(r)))
			stdout <- r
		}
	}()
}
开发者ID:tubs-ips,项目名称:nutsh,代码行数:30,代码来源:process.go


示例17: TestRun

// FIXME find out why it fails with "inappropriate ioctl for device"
func (s *RunSuite) TestRun(c *C) {
	p := s.RandomProject()
	cmd := exec.Command(s.command, "-f", "./assets/run/docker-compose.yml", "-p", p, "run", "hello", "echo", "test")
	var b bytes.Buffer
	wbuf := bufio.NewWriter(&b)

	tty, err := pty.Start(cmd)

	_, err = io.Copy(wbuf, tty)
	if e, ok := err.(*os.PathError); ok && e.Err == syscall.EIO {
		// We can safely ignore this error, because it's just
		// the PTY telling us that it closed successfully.
		// See:
		// https://github.com/buildkite/agent/pull/34#issuecomment-46080419
		err = nil
	}
	c.Assert(cmd.Wait(), IsNil)
	output := string(b.Bytes())

	c.Assert(err, IsNil, Commentf("%s", output))

	name := fmt.Sprintf("%s_%s_run_1", p, "hello")
	cn := s.GetContainerByName(c, name)
	c.Assert(cn, NotNil)

	lines := strings.Split(output, "\r\n")
	lastLine := lines[len(lines)-2 : len(lines)-1][0]

	c.Assert(cn.State.Running, Equals, false)
	c.Assert(lastLine, Equals, "test")
}
开发者ID:datawolf,项目名称:libcompose,代码行数:32,代码来源:run_test.go


示例18: StartBash

// StartBash starts up a new bash subprocess for use in completions.
func StartBash() (b *Bash, err error) {
	f, err := ioutil.TempFile("", "smash-inputrc")
	if err != nil {
		return nil, err
	}
	io.WriteString(f, inputrc)
	f.Close()
	defer os.Remove(f.Name())

	b = &Bash{}
	b.cmd = exec.Command("bash", "-i")
	b.cmd.Env = append(b.cmd.Env, fmt.Sprintf("INPUTRC=%s", f.Name()))
	if b.pty, err = pty.Start(b.cmd); err != nil {
		return nil, err
	}
	b.lines = bufio.NewScanner(b.pty)
	if err = b.disableEcho(); err != nil {
		return nil, err
	}
	if err = b.setNarrow(); err != nil {
		return nil, err
	}
	if err = b.setupPrompt(); err != nil {
		return nil, err
	}
	return
}
开发者ID:evmar,项目名称:smash,代码行数:28,代码来源:complete.go


示例19: main

func main() {
	fmt.Print("hello from winmux\n")

	//	log.Print("hello!")

	// take a window id from the command line
	// I suppose it could come from the environment too

	//	log.Print(os.Args[0])

	var q Q
	var err error

	// Actually make this correspond to the real syntax.
	var window_id = flag.Int("id", -1, "Acme window id")
	var window_name = flag.String("name", "", "Acme window name")
	flag.Parse()

	cmd := "/usr/local/plan9/bin/rc"
	// cmd := "/usr/local/plan9/bin/cat"	// Safer for now.
	if args := flag.Args(); len(args) == 1 {
		cmd = args[0]
	} else if len(args) > 1 {
		log.Fatal(usage)
	}

	// TODO(rjkroege): look up a window by name if an argument is provided
	// and connect to it.
	// Hunt down an acme window
	log.Printf("asked for window %s\n", *window_name)
	if *window_id == -1 {
		q.Win, err = acme.New()
	} /* else open the named window. */
	if err != nil {
		log.Fatal("can't open the window? ", err.Error())
	}

	q.Win.Name("winmux-%s", cmd)
	q.Win.Fprintf("body", "hi rob\n")

	// TODO(rjkroege): start the function that receives from the pty and inserts into acme
	c := exec.Command(cmd)
	f, err := pty.Start(c)
	if err != nil {
		log.Fatalf("failed to start pty up: %s", err.Error())
	}

	echo := ttypair.Makecho()
	q.Tty = ttypair.New(f, echo)

	// A goroutine to read the output
	go childtoacme(&q, f, echo)

	// Read from the acme and send to child. (Rename?)
	acmetowin(&q, f, echo)

	q.Win.CloseFiles()
	fmt.Print("bye\n")
}
开发者ID:rjkroege,项目名称:winmux,代码行数:59,代码来源:winmux.go


示例20: NewIPset

// NewIPset starts ipset specified with path in interactive mode (ipset - ) and returns a new IPset.
func NewIPset(path string) *IPset {
	cmd := exec.Command(path, "-")
	f, _ := pty.Start(cmd)
	ipset := &IPset{pty: f, stdin: bufio.NewWriter(f), stdout: bufio.NewReader(f)}
	buf := make([]byte, 1000)
	ipset.stdout.Read(buf)
	return ipset
}
开发者ID:42wim,项目名称:ipsetd,代码行数:9,代码来源:ipset.go



注:本文中的github.com/kr/pty.Start函数示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
Golang text.Indent函数代码示例发布时间:2022-05-23
下一篇:
Golang pty.Open函数代码示例发布时间:2022-05-23
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

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

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

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