如何使用read系统调用以交互方式输入密码。

huangapple go评论81阅读模式
英文:

how do I use read system call to take password interactively

问题

你好!以下是使用系统调用在Golang中实现上述命令行的方法:

package main

import (
	"fmt"
	"golang.org/x/term"
	"os"
)

func main() {
	fmt.Print("Enter Password: ")
	password, err := term.ReadPassword(int(os.Stdin.Fd()))
	if err != nil {
		fmt.Println("Error reading password:", err)
		return
	}
	fmt.Println("\nPassword entered:", string(password))
}

在上面的代码中,我们使用了golang.org/x/term包中的ReadPassword函数来读取密码。该函数会禁止输入回显,并且只能通过交互方式提供输入。

希望对你有帮助!如果你有任何其他问题,请随时提问。

英文:

how do I implement the following command line using system calls in golang?

read -s -p "Enter Password: " mypassword

that is, what additional options to set while reading the password to avoid the input to be echoed and force the input to be provided only interactively.

thanks.

答案1

得分: 4

你可以使用terminal包中的terminal.ReadPassword()函数。

func ReadPassword(fd int) ([]byte, error)

ReadPassword函数从终端读取一行输入,但不会在本地回显。这通常用于输入密码和其他敏感数据。返回的切片不包括\n

terminal包提供了处理终端的支持函数,通常在UNIX系统上使用。

更多信息:

英文:

You can use terminal.ReadPassword() from package terminal.

func ReadPassword(fd int) ([]byte, error)

ReadPassword reads a line of input from a terminal without local echo. This is commonly used for inputting passwords and other sensitive data. The slice returned does not include the \n.

Package terminal provides support functions for dealing with terminals, as commonly found on UNIX systems.

More on it:

答案2

得分: -2

你可以使用expect命令来进行交互式密码输入:

expect "Enter Password:" {

send -- "$PASSWORD_VALUE\r"

例如,在使用sftp时使用以下脚本
#####sh expect.sh #########
PASSWORD_VALUE="password"

spawn -noecho sftp username@ip

expect "Enter Password:" {

send -- "$PASSWORD_VALUE\r"
###########################

英文:

You may use expect command for password interactively :

expect "Enter Password:" {

send -- "$PASSWORD_VALUE\r"

e.g - while using sftp use below script
#####sh expect.sh #########
PASSWORD_VALUE="password"

spawn -noecho sftp username@ip

expect "Enter Password:" {

send -- "$PASSWORD_VALUE\r"
###########################

huangapple
  • 本文由 发表于 2014年1月3日 14:27:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/20897895.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定