本文整理汇总了Golang中golang.org/x/crypto/ssh.Channel.Close方法的典型用法代码示例。如果您正苦于以下问题:Golang Channel.Close方法的具体用法?Golang Channel.Close怎么用?Golang Channel.Close使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类golang.org/x/crypto/ssh.Channel
的用法示例。
在下文中一共展示了Channel.Close方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: handleSessionRequests
func handleSessionRequests(logger log.Logger, channel ssh.Channel, requests <-chan *ssh.Request, system datamodel.System, user datamodel.User) {
defer channel.Close()
// Sessions have out-of-band requests such as "shell",
// "pty-req" and "env". Here we handle only the
// "shell" request.
for req := range requests {
ok := false
switch req.Type {
case "shell":
ok = true
if len(req.Payload) > 0 {
fmt.Println(string(req.Payload))
// We don't accept any
// commands, only the
// default shell.
ok = false
}
case "pty-req":
// Responding 'ok' here will let the client
// know we have a pty ready for input
ok = true
go startTerminal(logger, channel, system, user)
default:
// fmt.Println("default req: ", req)
}
req.Reply(ok, nil)
}
}
示例2: pipeRequests
func pipeRequests(psChannel, sChannel ssh.Channel, psRequests, sRequests <-chan *ssh.Request) {
defer func() {
return
if r := recover(); r != nil {
fmt.Println("Recovered in f", r)
}
}()
defer sChannel.Close()
defer psChannel.Close()
for {
select {
case lRequest, ok := <-psRequests:
if !ok {
return
}
if err := forwardRequest(lRequest, sChannel); err != nil {
fmt.Println("Error: " + err.Error())
continue
}
case rRequest, ok := <-sRequests:
if !ok {
return
}
if err := forwardRequest(rRequest, psChannel); err != nil {
fmt.Println("Error: " + err.Error())
continue
}
}
}
}
示例3: 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
}
示例4: ProxyRequests
func ProxyRequests(logger lager.Logger, channelType string, reqs <-chan *ssh.Request, channel ssh.Channel) {
logger = logger.Session("proxy-requests", lager.Data{
"channel-type": channelType,
})
logger.Info("started")
defer logger.Info("completed")
defer channel.Close()
for req := range reqs {
logger.Info("request", lager.Data{
"type": req.Type,
"wantReply": req.WantReply,
"payload": req.Payload,
})
success, err := channel.SendRequest(req.Type, req.WantReply, req.Payload)
if err != nil {
logger.Error("send-request-failed", err)
continue
}
if req.WantReply {
req.Reply(success, nil)
}
}
}
示例5: startTerminal
func (s *shellHandler) startTerminal(parentTomb tomb.Tomb, sshConn *ssh.ServerConn, channel ssh.Channel) error {
defer channel.Close()
prompt := ">>> "
term := terminal.NewTerminal(channel, prompt)
// // Try to make the terminal raw
// oldState, err := terminal.MakeRaw(0)
// if err != nil {
// logger.Warn("Error making terminal raw: ", err.Error())
// }
// defer terminal.Restore(0, oldState)
// Get username
username, ok := sshConn.Permissions.Extensions["username"]
if !ok {
username = "user"
}
// Write ascii text
term.Write([]byte(fmt.Sprintf("\r\n Nice job, %s! You are connected!\r\n", username)))
defer term.Write([]byte(fmt.Sprintf("\r\nGoodbye, %s!\r\n", username)))
// Start REPL
for {
select {
case <-parentTomb.Dying():
return nil
default:
s.logger.Info("Reading line...")
input, err := term.ReadLine()
if err != nil {
fmt.Errorf("Readline() error")
return err
}
// Process line
line := strings.TrimSpace(input)
if len(line) > 0 {
// Log input and handle exit requests
if line == "exit" || line == "quit" {
s.logger.Info("Closing connection")
return nil
}
// Echo input
channel.Write(term.Escape.Green)
channel.Write([]byte(line + "\r\n"))
channel.Write(term.Escape.Reset)
}
}
}
return nil
}
示例6: handleRequests
func (s *sshServer) handleRequests(channel ssh.Channel, in <-chan *ssh.Request) error {
env := make(map[string]string)
for req := range in {
switch req.Type {
default:
log.Printf("unrecognized ssh request type=%q payload=%s wantreply=%t", req.Type, req.Payload, req.WantReply)
req.Reply(false, nil) // unhandled; tell them so
case "env":
var e envReq
if err := ssh.Unmarshal(req.Payload, &e); err != nil {
req.Reply(false, nil)
return err
}
req.Reply(true, nil)
env[string(e.Key)] = string(e.Val)
case "exec":
var e execReq
if err := ssh.Unmarshal(req.Payload, &e); err != nil {
req.Reply(false, nil)
return err
}
req.Reply(true, nil)
var cmdbuf bytes.Buffer
for k, v := range env {
cmdbuf.WriteString(k)
cmdbuf.WriteByte('=')
cmdbuf.WriteString(v)
cmdbuf.WriteByte(' ')
}
cmdbuf.Write(e.Command)
log.Printf("Running command %q", cmdbuf.String())
cmd := &packer.RemoteCmd{Command: cmdbuf.String()}
cmd.Stdout = channel
cmd.Stderr = channel.Stderr()
var rc int
if err := s.comm.Start(cmd); err != nil {
rc = 255 // TODO: What is a better choice here?
} else {
cmd.Wait()
rc = cmd.ExitStatus
}
channel.CloseWrite()
channel.SendRequest("exit-status", false, []byte{0, 0, 0, byte(rc)})
channel.Close()
}
}
return nil
}
示例7: Handle
func (s *shellHandler) Handle(parentTomb tomb.Tomb, sshConn *ssh.ServerConn, channel ssh.Channel, requests <-chan *ssh.Request) error {
defer channel.Close()
users, err := s.system.Users()
if err != nil {
return err
}
user, err := users.Get(sshConn.Permissions.Extensions["username"])
if err != nil {
return err
}
// Create tomb for terminal goroutines
var t tomb.Tomb
// Sessions have out-of-band requests such as "shell",
// "pty-req" and "env". Here we handle only the
// "shell" request.
for {
select {
case <-parentTomb.Dying():
t.Kill(nil)
return t.Wait()
case req := <-requests:
ok := false
switch req.Type {
case "shell":
ok = true
if len(req.Payload) > 0 {
fmt.Println(string(req.Payload))
// We don't accept any
// commands, only the
// default shell.
ok = false
}
case "pty-req":
// Responding 'ok' here will let the client
// know we have a pty ready for input
ok = true
go s.startTerminal(t, channel, s.system, user)
default:
// fmt.Println("default req: ", req)
}
req.Reply(ok, nil)
}
}
return nil
}
示例8: Handle
func (s *shellHandler) Handle(parentTomb tomb.Tomb, sshConn *ssh.ServerConn, channel ssh.Channel, requests <-chan *ssh.Request) error {
defer channel.Close()
s.logger.Info("WooHoo!!! Inside Handler!")
// Create tomb for terminal goroutines
var t tomb.Tomb
// Sessions have out-of-band requests such as "shell",
// "pty-req" and "env". Here we handle only the
// "shell" request.
t.Go(func() error {
OUTER:
for {
select {
case <-parentTomb.Dying():
t.Kill(nil)
break OUTER
case req := <-requests:
if req == nil {
break OUTER
}
ok := false
switch req.Type {
case "shell":
ok = true
if len(req.Payload) > 0 {
// fmt.Println(string(req.Payload))
// We don't accept any
// commands, only the
// default shell.
ok = false
}
case "pty-req":
// Responding 'ok' here will let the client
// know we have a pty ready for input
ok = true
t.Go(func() error {
return s.startTerminal(t, sshConn, channel)
})
}
req.Reply(ok, nil)
}
}
return nil
})
return t.Wait()
}
示例9: handleChannelRequests
func handleChannelRequests(logger log.Logger, channel ssh.Channel, requests <-chan *ssh.Request, system datamodel.System, user datamodel.User) {
defer channel.Close()
for req := range requests {
if req.Type == "skl" {
logger.Info("SKL request", "request", string(req.Payload))
req.Reply(true, nil)
} else {
if req.WantReply {
req.Reply(false, nil)
}
}
}
}
示例10: proxy
func proxy(reqs1, reqs2 <-chan *ssh.Request, channel1, channel2 ssh.Channel) {
var closer sync.Once
closeFunc := func() {
channel1.Close()
channel2.Close()
}
defer closer.Do(closeFunc)
closerChan := make(chan bool, 1)
go func() {
io.Copy(channel1, channel2)
closerChan <- true
}()
go func() {
io.Copy(channel2, channel1)
closerChan <- true
}()
for {
select {
case req := <-reqs1:
if req == nil {
return
}
b, err := channel2.SendRequest(req.Type, req.WantReply, req.Payload)
if err != nil {
return
}
req.Reply(b, nil)
case req := <-reqs2:
if req == nil {
return
}
b, err := channel1.SendRequest(req.Type, req.WantReply, req.Payload)
if err != nil {
return
}
req.Reply(b, nil)
case <-closerChan:
return
}
}
}
示例11: handleChannel
func (sshd *SSHD) handleChannel(channel ssh.Channel, requests <-chan *ssh.Request, container string) {
cmd := exec.Command("docker", "exec", "-i", "-t", container, "/bin/bash")
closeChannel := func() {
channel.Close()
_, err := cmd.Process.Wait()
if err != nil {
log.Errorf("failed to exit docker exec (%s)", err)
}
}
fp, err := pty.Start(cmd)
if err != nil {
log.Error("pty.Start: ", err)
closeChannel()
return
}
go func() {
for req := range requests {
log.Debugf("new request: %s", req.Type)
switch req.Type {
case "shell":
if len(req.Payload) == 0 {
req.Reply(true, nil)
}
case "pty-req":
termLen := req.Payload[3]
w, h := sshd.parseDims(req.Payload[termLen+4:])
sshd.setWinsize(fp.Fd(), w, h)
req.Reply(true, nil)
case "window-change":
w, h := sshd.parseDims(req.Payload)
sshd.setWinsize(fp.Fd(), w, h)
case "env":
}
}
}()
var once sync.Once
cp := func(dst io.Writer, src io.Reader) {
io.Copy(dst, src)
once.Do(closeChannel)
}
go cp(channel, fp)
go cp(fp, channel)
}
示例12: handleExec
// Payload: int: command size, string: command
func handleExec(ch ssh.Channel, req *ssh.Request) {
command := string(req.Payload[4:])
gitCmds := []string{"git-receive-pack", "git-upload-pack"}
valid := false
for _, cmd := range gitCmds {
if strings.HasPrefix(command, cmd) {
valid = true
}
}
if !valid {
ch.Write([]byte("command is not a GIT command\r\n"))
ch.Close()
return
}
ch.Write([]byte("well done!\r\n"))
ch.Close()
}
示例13: handleChannel
func handleChannel(ch ssh.Channel) {
term := terminal.NewTerminal(ch, "> ")
serverTerm := &ssh.ServerTerminal{
Term: term,
Channel: ch,
}
ch.Accept()
defer ch.Close()
for {
line, err := serverTerm.ReadLine()
if err == io.EOF {
return
}
if err != nil {
log.Println("handleChannel readLine err:", err)
continue
}
fmt.Println(line)
}
}
示例14: handleChannelRequests
/* handleChannelRequests handles proxying requests read from reqs to the SSH
channel c. info is used for logging. */
func handleChannelRequests(
reqs <-chan *ssh.Request,
c ssh.Channel,
info string,
) {
for r := range reqs {
go handleRequest(
r,
func( /* Ugh, a closure */
name string,
wantReply bool,
payload []byte,
) (bool, []byte, error) {
b, e := c.SendRequest(name, wantReply, payload)
return b, nil, e
},
func() error { return c.Close() }, /* Another? */
info,
)
}
}
示例15: handleExec
// Payload: int: command size, string: command
func handleExec(ch ssh.Channel, req *ssh.Request) {
command := string(req.Payload[4:])
client, session, err := connectUpstream()
if err != nil {
ch.Write([]byte("fail to connect upstream: " + err.Error() + "\r\n"))
ch.Close()
return
}
exitStatus, err := pipe(ch, client, session, command)
if err != nil {
ch.Write([]byte("fail to pipe command:" + err.Error()))
ch.Close()
return
}
exitStatusBuffer := make([]byte, 4)
binary.PutUvarint(exitStatusBuffer, uint64(exitStatus))
log.Println("forward exit-code", exitStatus, "to client")
_, err = ch.SendRequest("exit-status", false, exitStatusBuffer)
if err != nil {
log.Println("Failed to forward exit-status to client:", err)
}
ch.Close()
client.Close()
log.Println("End of exec")
}