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

Golang ssh.KeyboardInteractive函数代码示例

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

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



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

示例1: connect

func (d *ESX5Driver) connect() error {
	address := fmt.Sprintf("%s:%d", d.Host, d.Port)

	auth := []gossh.AuthMethod{
		gossh.Password(d.Password),
		gossh.KeyboardInteractive(
			ssh.PasswordKeyboardInteractive(d.Password)),
	}

	if d.PrivateKey != "" {
		signer, err := commonssh.FileSigner(d.PrivateKey)
		if err != nil {
			return err
		}

		auth = append(auth, gossh.PublicKeys(signer))
	}

	sshConfig := &ssh.Config{
		Connection: ssh.ConnectFunc("tcp", address),
		SSHConfig: &gossh.ClientConfig{
			User: d.Username,
			Auth: auth,
		},
	}

	comm, err := ssh.New(address, sshConfig)
	if err != nil {
		return err
	}

	d.comm = comm
	return nil
}
开发者ID:dantran,项目名称:packer,代码行数:34,代码来源:driver_esx5.go


示例2: SSHConfig

// SSHConfig returns a function that can be used for the SSH communicator
// config for connecting to the instance created over SSH using the private key
// or password.
func SSHConfig(username, password string) func(multistep.StateBag) (*ssh.ClientConfig, error) {
	return func(state multistep.StateBag) (*ssh.ClientConfig, error) {

		privateKey, hasKey := state.GetOk("privateKey")
		if hasKey {

			signer, err := ssh.ParsePrivateKey([]byte(privateKey.(string)))
			if err != nil {
				return nil, fmt.Errorf("Error setting up SSH config: %s", err)
			}
			return &ssh.ClientConfig{
				User: username,
				Auth: []ssh.AuthMethod{
					ssh.PublicKeys(signer),
				},
			}, nil

		} else {
			return &ssh.ClientConfig{
				User: username,
				Auth: []ssh.AuthMethod{
					ssh.Password(password),
					ssh.KeyboardInteractive(
						packerssh.PasswordKeyboardInteractive(password)),
				}}, nil
		}
	}
}
开发者ID:monkeylittleinc,项目名称:packer,代码行数:31,代码来源:ssh.go


示例3: connect

func (d *ESX5Driver) connect() error {
	address := fmt.Sprintf("%s:%d", d.Host, d.Port)

	auth := []gossh.AuthMethod{
		gossh.Password(d.Password),
		gossh.KeyboardInteractive(
			ssh.PasswordKeyboardInteractive(d.Password)),
	}

	// TODO(dougm) KeyPath support
	sshConfig := &ssh.Config{
		Connection: ssh.ConnectFunc("tcp", address),
		SSHConfig: &gossh.ClientConfig{
			User: d.Username,
			Auth: auth,
		},
	}

	comm, err := ssh.New(address, sshConfig)
	if err != nil {
		return err
	}

	d.comm = comm
	return nil
}
开发者ID:c12simple,项目名称:packer,代码行数:26,代码来源:driver_esx5.go


示例4: sshOnConn

func sshOnConn(conn net.Conn, h conf.Host) (*ssh.Client, error) {
	var auths []ssh.AuthMethod

	if h.Pass != "" {
		auths = append(auths, ssh.Password(h.Pass))
		auths = append(auths, ssh.KeyboardInteractive(kbdInteractive(h.Pass)))
	}

	if h.Key != "" {
		k := &keyring{}
		err := k.loadPEM([]byte(h.Key))
		if err != nil {
			return nil, err
		}
		for _, k := range k.keys {
			s, _ := ssh.NewSignerFromKey(k)
			auths = append(auths, ssh.PublicKeys(s))
		}
	}

	config := &ssh.ClientConfig{
		User: h.User,
		Auth: auths,
	}

	debugln("handshake & authenticate")
	cc, nc, reqs, err := ssh.NewClientConn(conn, conn.RemoteAddr().String(), config)
	if err != nil {
		return nil, err
	}
	client := ssh.NewClient(cc, nc, reqs)
	return client, nil
}
开发者ID:calmh,项目名称:mole,代码行数:33,代码来源:ssh.go


示例5: buildSSHClientConfig

func buildSSHClientConfig(opts sshClientConfigOpts) (*ssh.ClientConfig, error) {
	conf := &ssh.ClientConfig{
		User: opts.user,
	}

	if opts.privateKey != "" {
		pubKeyAuth, err := readPrivateKey(opts.privateKey)
		if err != nil {
			return nil, err
		}
		conf.Auth = append(conf.Auth, pubKeyAuth)
	}

	if opts.password != "" {
		conf.Auth = append(conf.Auth, ssh.Password(opts.password))
		conf.Auth = append(conf.Auth, ssh.KeyboardInteractive(
			PasswordKeyboardInteractive(opts.password)))
	}

	if opts.sshAgent != nil {
		conf.Auth = append(conf.Auth, opts.sshAgent.Auth())
	}

	return conf, nil
}
开发者ID:partamonov,项目名称:terraform,代码行数:25,代码来源:provisioner.go


示例6: sshConfig

func sshConfig(state multistep.StateBag) (*gossh.ClientConfig, error) {
	config := state.Get("config").(*Config)
	var privateKey string

	var auth []gossh.AuthMethod

	if config.Comm.SSHPassword != "" {
		auth = []gossh.AuthMethod{
			gossh.Password(config.Comm.SSHPassword),
			gossh.KeyboardInteractive(
				ssh.PasswordKeyboardInteractive(config.Comm.SSHPassword)),
		}
	}

	if config.Comm.SSHPrivateKey != "" {
		if priv, ok := state.GetOk("privateKey"); ok {
			privateKey = priv.(string)
		}
		signer, err := gossh.ParsePrivateKey([]byte(privateKey))
		if err != nil {
			return nil, fmt.Errorf("Error setting up SSH config: %s", err)
		}
		if err != nil {
			return nil, err
		}

		auth = append(auth, gossh.PublicKeys(signer))
	}
	return &gossh.ClientConfig{
		User: config.Comm.SSHUsername,
		Auth: auth,
	}, nil
}
开发者ID:arizvisa,项目名称:packer,代码行数:33,代码来源:ssh.go


示例7: sshConfig

func sshConfig(comm *communicator.Config) func(state multistep.StateBag) (*gossh.ClientConfig, error) {
	return func(state multistep.StateBag) (*gossh.ClientConfig, error) {
		if comm.SSHPrivateKey != "" {
			// key based auth
			bytes, err := ioutil.ReadFile(comm.SSHPrivateKey)
			if err != nil {
				return nil, fmt.Errorf("Error setting up SSH config: %s", err)
			}
			privateKey := string(bytes)

			signer, err := gossh.ParsePrivateKey([]byte(privateKey))
			if err != nil {
				return nil, fmt.Errorf("Error setting up SSH config: %s", err)
			}

			return &gossh.ClientConfig{
				User: comm.SSHUsername,
				Auth: []gossh.AuthMethod{
					gossh.PublicKeys(signer),
				},
			}, nil
		} else {
			// password based auth
			return &gossh.ClientConfig{
				User: comm.SSHUsername,
				Auth: []gossh.AuthMethod{
					gossh.Password(comm.SSHPassword),
					gossh.KeyboardInteractive(
						ssh.PasswordKeyboardInteractive(comm.SSHPassword)),
				},
			}, nil
		}
	}
}
开发者ID:c12simple,项目名称:packer,代码行数:34,代码来源:comm.go


示例8: connectToRemoteHost

func connectToRemoteHost(auth ssh.AuthMethod, user, host string, port int64) (*ssh.Client, error) {
	clientConfig := &ssh.ClientConfig{
		User: user,
		Auth: []ssh.AuthMethod{auth, ssh.KeyboardInteractive(kic)},
	}

	return ssh.Dial("tcp", fmt.Sprintf("%s:%d", host, port), clientConfig)
}
开发者ID:gooops,项目名称:goscp,代码行数:8,代码来源:main.go


示例9: main

func main() {
	listen := flag.String("listen", ":2022", "listen address")
	dest := flag.String("dest", ":22", "destination address")
	key := flag.String("key", "host_key", "rsa key to use")
	flag.Parse()

	privateBytes, err := ioutil.ReadFile(*key)
	if err != nil {
		panic("Failed to load private key")
	}

	private, err := ssh.ParsePrivateKey(privateBytes)
	if err != nil {
		panic("Failed to parse private key")
	}

	sessions := map[net.Addr]map[string]interface{}{}

	config := &ssh.ServerConfig{
		PasswordCallback: func(c ssh.ConnMetadata, pass []byte) (*ssh.Permissions, error) {
			fmt.Printf("Login attempt: %s, user %s password: %s\n", c.RemoteAddr(), c.User(), string(pass))

			sessions[c.RemoteAddr()] = map[string]interface{}{
				"username": c.User(),
				"password": string(pass),
			}

			clientConfig := &ssh.ClientConfig{
				User: c.User(),
				Auth: []ssh.AuthMethod{
					ssh.KeyboardInteractive(func(user, instruction string, questions []string, echos []bool) ([]string, error) {
						if len(questions) == 1 && questions[0] == "Password:" {
							return []string{string(pass)}, nil
						}
						return []string{}, nil
					}),
				},
			}
			client, err := ssh.Dial("tcp", *dest, clientConfig)
			if err != nil {
				return nil, err
			}
			sessions[c.RemoteAddr()]["client"] = client
			return nil, nil
		},
	}
	config.AddHostKey(private)

	sshproxy.ListenAndServe(*listen, config, func(c ssh.ConnMetadata) (*ssh.Client, error) {
		meta, ok := sessions[c.RemoteAddr()]
		if !ok {
			return nil, fmt.Errorf("session not found")
		}
		client := meta["client"].(*ssh.Client)
		fmt.Printf("Connection accepted from: %s", c.RemoteAddr())
		return client, nil
	}, nil, nil)
}
开发者ID:creack,项目名称:sshproxy,代码行数:58,代码来源:main.go


示例10: NewClientConfig

// NewClientConfig creates a barebones ssh.ClientConfig to be used with ssh.Dial.
func NewClientConfig(name string) *ssh.ClientConfig {
	return &ssh.ClientConfig{
		User: name,
		Auth: []ssh.AuthMethod{
			ssh.KeyboardInteractive(func(user, instruction string, questions []string, echos []bool) (answers []string, err error) {
				return
			}),
		},
	}
}
开发者ID:dream1986,项目名称:ssh-chat,代码行数:11,代码来源:client.go


示例11: openLog

func openLog(path string) (io.WriteCloser, error) {
	m := scpPathRe.FindStringSubmatch(path)
	if m == nil {
		return os.OpenFile(path, os.O_WRONLY|os.O_CREATE, 0600)
	} else {
		user, pass, host, port, path := m[1], m[2], m[3], m[4], m[5]
		if path == "" {
			return nil, errors.New("blank remote file path")
		}
		if port == "" {
			port = "22"
		} else {
			port = port[1:]
		}
		config := ssh.ClientConfig{
			User: user,
			Auth: []ssh.AuthMethod{ssh.KeyboardInteractive(sshKeyboardAuth)},
		}
		if pass != "" {
			config.Auth = append([]ssh.AuthMethod{ssh.Password(pass[1:])}, config.Auth...)
		} else {
			config.Auth = append([]ssh.AuthMethod{ssh.PasswordCallback(func() (string, error) {
				fmt.Printf("Password: ")
				pass, err := readPass(0)
				fmt.Println()
				return string(pass), err
			})}, config.Auth...)
		}
		client, err := ssh.Dial("tcp", net.JoinHostPort(host, port), &config)
		if err != nil {
			return nil, err
		}
		session, err := client.NewSession()
		if err != nil {
			return nil, err
		}
		inputStream, err := session.StdinPipe()
		if err != nil {
			session.Close()
			return nil, err
		}
		cmd := fmt.Sprintf("cat > %s", shellEscape(path))
		if err := session.Start(cmd); err != nil {
			session.Close()
			return nil, err
		}
		return inputStream, nil
	}
}
开发者ID:lunixbochs,项目名称:yoink,代码行数:49,代码来源:logging.go


示例12: SSHConfig

// SSHConfig returns a function that can be used for the SSH communicator
// config for connecting to the instance created over SSH using the private key
// or password.
func SSHConfig(useAgent bool, username, password string) func(multistep.StateBag) (*ssh.ClientConfig, error) {
	return func(state multistep.StateBag) (*ssh.ClientConfig, error) {
		if useAgent {
			authSock := os.Getenv("SSH_AUTH_SOCK")
			if authSock == "" {
				return nil, fmt.Errorf("SSH_AUTH_SOCK is not set")
			}

			sshAgent, err := net.Dial("unix", authSock)
			if err != nil {
				return nil, fmt.Errorf("Cannot connect to SSH Agent socket %q: %s", authSock, err)
			}

			return &ssh.ClientConfig{
				User: username,
				Auth: []ssh.AuthMethod{
					ssh.PublicKeysCallback(agent.NewClient(sshAgent).Signers),
				},
			}, nil
		}

		privateKey, hasKey := state.GetOk("privateKey")
		if hasKey {

			signer, err := ssh.ParsePrivateKey([]byte(privateKey.(string)))
			if err != nil {
				return nil, fmt.Errorf("Error setting up SSH config: %s", err)
			}
			return &ssh.ClientConfig{
				User: username,
				Auth: []ssh.AuthMethod{
					ssh.PublicKeys(signer),
				},
			}, nil

		} else {
			return &ssh.ClientConfig{
				User: username,
				Auth: []ssh.AuthMethod{
					ssh.Password(password),
					ssh.KeyboardInteractive(
						packerssh.PasswordKeyboardInteractive(password)),
				}}, nil
		}
	}
}
开发者ID:rnaveiras,项目名称:packer,代码行数:49,代码来源:ssh.go


示例13: main

func main() {

	// Show the current version:
	log.Println(`SSHTunnel v1.3.0`)

	// Allow Go to use all CPUs:
	runtime.GOMAXPROCS(runtime.NumCPU())

	// Read the configuration from the command-line args:
	readFlags()

	// Check if the password was provided:
	for true {
		if password == `` {
			// Promt for the password:
			fmt.Println(`Please provide the password for the connection:`)
			if pass, errPass := gopass.GetPasswd(); errPass != nil {
				log.Println(`There was an error reading the password securely: ` + errPass.Error())
				os.Exit(1)
				return
			} else {
				password = string(pass)
			}
		} else {
			break
		}
	}

	// Create the SSH configuration:
	Tunnel.SetPassword4Callback(password)
	config := &ssh.ClientConfig{
		User: username,
		Auth: []ssh.AuthMethod{
			ssh.Password(password),
			ssh.PasswordCallback(Tunnel.PasswordCallback),
			ssh.KeyboardInteractive(Tunnel.KeyboardInteractiveChallenge),
		},
	}

	// Create the local end-point:
	localListener := Tunnel.CreateLocalEndPoint(localAddrString)

	// Accept client connections (will block forever):
	Tunnel.AcceptClients(localListener, config, serverAddrString, remoteAddrString)
}
开发者ID:cnhup,项目名称:SSHTunnel,代码行数:45,代码来源:Main.go


示例14: sshConfig

func sshConfig(state multistep.StateBag) (*gossh.ClientConfig, error) {
	config := state.Get("config").(*Config)

	auth := []gossh.AuthMethod{
		gossh.Password(config.Comm.SSHPassword),
		gossh.KeyboardInteractive(
			ssh.PasswordKeyboardInteractive(config.Comm.SSHPassword)),
	}

	if config.Comm.SSHPrivateKey != "" {
		signer, err := commonssh.FileSigner(config.Comm.SSHPrivateKey)
		if err != nil {
			return nil, err
		}

		auth = append(auth, gossh.PublicKeys(signer))
	}

	return &gossh.ClientConfig{
		User: config.Comm.SSHUsername,
		Auth: auth,
	}, nil
}
开发者ID:jbweber,项目名称:packer-builder-qemuipxe,代码行数:23,代码来源:ssh.go


示例15: sshBastionConfig

func sshBastionConfig(config *Config) (*gossh.ClientConfig, error) {
	auth := make([]gossh.AuthMethod, 0, 2)
	if config.SSHBastionPassword != "" {
		auth = append(auth,
			gossh.Password(config.SSHBastionPassword),
			gossh.KeyboardInteractive(
				ssh.PasswordKeyboardInteractive(config.SSHBastionPassword)))
	}

	if config.SSHBastionPrivateKey != "" {
		signer, err := commonssh.FileSigner(config.SSHBastionPrivateKey)
		if err != nil {
			return nil, err
		}

		auth = append(auth, gossh.PublicKeys(signer))
	}

	return &gossh.ClientConfig{
		User: config.SSHBastionUsername,
		Auth: auth,
	}, nil
}
开发者ID:c12simple,项目名称:packer,代码行数:23,代码来源:step_connect_ssh.go


示例16: SSHConfigFunc

func SSHConfigFunc(config SSHConfig) func(multistep.StateBag) (*gossh.ClientConfig, error) {
	return func(state multistep.StateBag) (*gossh.ClientConfig, error) {
		auth := []gossh.AuthMethod{
			gossh.Password(config.Comm.SSHPassword),
			gossh.KeyboardInteractive(
				ssh.PasswordKeyboardInteractive(config.Comm.SSHPassword)),
		}

		if config.SSHKeyPath != "" {
			signer, err := commonssh.FileSigner(config.Comm.SSHPrivateKey)
			if err != nil {
				return nil, err
			}

			auth = append(auth, gossh.PublicKeys(signer))
		}

		return &gossh.ClientConfig{
			User: config.Comm.SSHUsername,
			Auth: auth,
		}, nil
	}
}
开发者ID:vvchik,项目名称:packer,代码行数:23,代码来源:ssh.go


示例17: sshConfig

func sshConfig(state multistep.StateBag) (*ssh.ClientConfig, error) {
	config := state.Get("config").(config)
	privateKey := state.Get("ssh_private_key").(string)

	auth := []ssh.AuthMethod{
		ssh.Password(config.SSHPassword),
		ssh.KeyboardInteractive(
			packerssh.PasswordKeyboardInteractive(config.SSHPassword)),
	}

	if privateKey != "" {
		signer, err := ssh.ParsePrivateKey([]byte(privateKey))
		if err != nil {
			return nil, fmt.Errorf("Error setting up SSH config: %s", err)
		}

		auth = append(auth, ssh.PublicKeys(signer))
	}

	return &ssh.ClientConfig{
		User: config.SSHUsername,
		Auth: auth,
	}, nil
}
开发者ID:larstobi,项目名称:packer-cloudstack,代码行数:24,代码来源:ssh.go


示例18: main

func main() {
	flag.Parse()
	logger, cl := makeLogger()

	if flagTrace {
		cl.SetMinLevel(colog.LTrace)
	} else if flagVerbose {
		cl.SetMinLevel(colog.LDebug)
	} else if flagQuiet {
		cl.SetMinLevel(colog.LWarning)
	} else {
		cl.SetMinLevel(colog.LInfo)
	}

	if len(flagAllowedSourceIPs) > 0 {
		log.Println("info: Allowed source IPs:")
		for _, host := range flagAllowedSourceIPs {
			log.Printf("  - %s", host)
		}
	}

	if len(flagAllowedDestinationIPs) > 0 {
		log.Println("info: Allowed destination IPs:")
		for _, host := range flagAllowedDestinationIPs {
			log.Printf("  - %s", host)
		}
	}

	addr := fmt.Sprintf("%s:%d", flagHost, flagPort)

	// Create a SOCKS5 server
	conf := &socks5.Config{
		Rules:  Rules{},
		Logger: logger,
	}
	server, err := socks5.New(conf)
	if err != nil {
		log.Fatalf("error: could not create SOCKS server: %s", err)
	}

	// Create the listener
	var (
		l          net.Listener
		listenHost string
	)

	if flagRemoteListener != "" {
		u, err := url.Parse(flagRemoteListener)
		if err != nil {
			log.Fatalf("error: error parsing url: %s", err)
		}
		if u.Scheme != "ssh" {
			log.Fatalf("error: url is not an SSH url: %s", flagRemoteListener)
		}
		if u.User == nil {
			log.Fatalf("error: no username provided in remote listener", err)
		}
		if u.Path != "" || u.RawQuery != "" || u.Fragment != "" {
			log.Printf("warning: path, query, and fragment have no meaning in remote listener URL")
		}

		listenHost = u.Host

		// TODO: uber-hack atm find a better way, pass as cmd line argument
		answers := keyboardInteractive(map[string]string{
			"Verification code: ": "",
		})

		config := &ssh.ClientConfig{
			User: u.User.Username(),
			//User: "bmb",
			Auth: []ssh.AuthMethod{
				SSHAgent(),
				ssh.KeyboardInteractive(answers.Challenge),
			},
		}

		sshConn, err := ssh.Dial("tcp", u.Host, config)
		if err != nil {
			log.Fatalf("error: error dialing remote host: %s", err)
		}
		defer sshConn.Close()

		l, err = sshConn.Listen("tcp", addr)
		if err != nil {
			log.Fatalf("error: error listening on remote host: %s", err)
		}
	} else {
		// Listen on a local port
		listenHost = "localhost"
		l, err = net.Listen("tcp", addr)
	}

	defer l.Close()

	log.Printf("info: starting socks proxy on: %s (proxy addr: %s)", listenHost, addr)
	if err := server.Serve(l); err != nil {
		log.Fatalf("error: could not serve socks proxy: %s", err)
	}

//.........这里部分代码省略.........
开发者ID:bmbernie,项目名称:socks,代码行数:101,代码来源:main.go


示例19: runMain

func runMain(cmd *cobra.Command, args []string) {
	if len(args) != 1 {
		log.Printf("error: invalid number of arguments (expected 1, got %d)", len(args))
		os.Exit(1)
	}

	sshHost := args[0]

	// Add a default ':22' after the end if we don't have a colon.
	if !strings.Contains(sshHost, ":") {
		sshHost += ":22"
	}

	config := &ssh.ClientConfig{
		User: flagSSHUsername,
		Auth: nil,
	}

	// Password auth or prompt callback
	if flagSSHPassword != "" {
		log.Println("trace: adding password auth")
		config.Auth = append(config.Auth, ssh.Password(flagSSHPassword))
	} else {
		log.Println("trace: adding password callback auth")
		config.Auth = append(config.Auth, ssh.PasswordCallback(func() (string, error) {
			prompt := fmt.Sprintf("%[email protected]%s's password: ", flagSSHUsername, sshHost)
			return speakeasy.Ask(prompt)
		}))
	}

	// Key auth
	if flagSSHIdentityFile != "" {
		auth, err := loadPrivateKey(flagSSHIdentityFile)
		if err != nil {
			log.Fatalf("error: could not load identity file '%s': %s",
				flagSSHIdentityFile, err)
		}

		log.Println("trace: adding identity file auth")
		config.Auth = append(config.Auth, auth)
	}

	// SSH agent auth
	if agentConn, err := net.Dial("unix", os.Getenv("SSH_AUTH_SOCK")); err != nil {
		log.Println("trace: adding ssh agent auth")
		config.Auth = append(config.Auth,
			ssh.PublicKeysCallback(agent.NewClient(agentConn).Signers))
	}

	config.Auth = append(config.Auth,
		ssh.KeyboardInteractive(func(user, instruction string, questions []string, echos []bool) (answers []string, err error) {
			var (
				ans string
				b   []byte
			)

			for i, q := range questions {
				prompt := fmt.Sprintf("[question %d/%d] %s", i+1, len(questions), q)

				if echos[i] {
					fmt.Print(prompt)
					bio := bufio.NewReader(os.Stdin)
					b, _, err = bio.ReadLine()
					ans = string(b)
				} else {
					ans, err = speakeasy.Ask(prompt)
				}
				if err != nil {
					return
				}

				answers = append(answers, ans)
			}

			return
		}))

	// TODO: keyboard-interactive auth, e.g. for two-factor

	// Dial the SSH connection
	log.Printf("debug: attempting %d authentication methods (%+v)", len(config.Auth), config.Auth)
	sshConn, err := ssh.Dial("tcp", sshHost, config)
	if err != nil {
		log.Fatalf("error: error dialing remote host: %s", err)
	}
	defer sshConn.Close()

	// Listen on remote
	l, err := sshConn.Listen("tcp", flagAddr)
	if err != nil {
		log.Fatalf("error: error listening on remote host: %s", err)
	}

	// Start accepting shell connections
	log.Printf("info: listening for connections on %s (remote listen address: %s)", sshHost, flagAddr)
	for {
		conn, err := l.Accept()
		if err != nil {
			log.Printf("error: error accepting connection: %s", err)
			continue
//.........这里部分代码省略.........
开发者ID:andrew-d,项目名称:rssh,代码行数:101,代码来源:main.go


示例20: main

func main() {

	// Show the current version:
	log.Println(`Sync v1.2.0`)

	// Allow Go to use all CPUs:
	runtime.GOMAXPROCS(runtime.NumCPU())

	// Read the configuration from the command-line args:
	readFlags()

	// Check if the directories are provided:
	if localDir == `` || remoteDir == `` {
		log.Println(`Please provide the local and remote directory.`)
		os.Exit(1)
		return
	}

	// Should I use the current working dir?
	if localDir == `.` {
		if currentWD, currentWDError := os.Getwd(); currentWDError != nil {
			log.Println("Cannot use the current working directory as local directory: " + currentWDError.Error())
			os.Exit(2)
			return
		} else {
			log.Println("I use the current working directory as local directory: " + currentWD)
			localDir = currentWD
		}
	}

	// Remove trailing separators from both directories
	localDir = correctPath(localDir)
	remoteDir = correctPath(remoteDir)

	// Check if local dir exist
	if dirInfo, dirError := os.Stat(localDir); dirError != nil {
		log.Println("There is an error with the local directory: " + dirError.Error())
		os.Exit(3)
		return
	} else {
		if !dirInfo.IsDir() {
			log.Println("There is an error with the local directory: You provided a file instead!")
			os.Exit(4)
			return
		}
	}

	// Check if the password was provided:
	for true {
		if password == `` {
			// Promt for the password:
			fmt.Print(`Please provide the password for the connection: `)
			if pass, errPass := gopass.GetPasswd(); errPass != nil {
				log.Println(`There was an error reading the password securely: ` + errPass.Error())
				os.Exit(5)
				return
			} else {
				password = string(pass)
			}
		} else {
			break
		}
	}

	// Give some information about the state
	if supervised {
		log.Println("I use the supervised mode.")
	} else {
		log.Println("I do not use the supervised mode.")
	}

	if pushOnly {
		log.Println("I use the push only mode i.e. backup mode. Any remote change will be ignored.")
	} else {
		log.Println("I use the full mode and consider also remote changes.")
	}

	// Create the SSH configuration:
	Sync.SetPassword4Callback(password)
	config := &ssh.ClientConfig{
		User: username,
		Auth: []ssh.AuthMethod{
			ssh.Password(password),
			ssh.PasswordCallback(Sync.PasswordCallback),
			ssh.KeyboardInteractive(Sync.KeyboardInteractiveChallenge),
		},
	}

	// Connect to the SSH server:
	ssh := Sync.ConnectSSH(config, serverAddrString)
	if ssh == nil {
		log.Println(`It was not possible to connect to the SSH server.`)
		os.Exit(6)
		return
	}

	defer ssh.Close()
	Sync.Synchronise(ssh, supervised, pushOnly, localDir, remoteDir)
	log.Println("Synchronising done.")
}
开发者ID:SommerEngineering,项目名称:Sync,代码行数:100,代码来源:Main.go



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
Golang ssh.Marshal函数代码示例发布时间:2022-05-28
下一篇:
Golang ssh.DiscardRequests函数代码示例发布时间: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