作者:VukDuki
项目:gotill
func (c *SftpClient) Connect() error {
auth := []ssh.AuthMethod{}
if c.authMethod == "key" {
key, _ := c.GetKey(c.keyPath)
auth = []ssh.AuthMethod{
ssh.PublicKeys(key),
}
} else if c.authMethod == "password" {
auth = []ssh.AuthMethod{
ssh.Password(c.password),
}
}
config := &ssh.ClientConfig{
User: c.username,
Auth: auth,
}
sHost := strings.Join([]string{c.hostname, strconv.FormatInt(c.port, 10)}, ":")
sshClient, err := ssh.Dial("tcp", sHost, config)
if err != nil {
return err
}
sftpClient, err := sftp.NewClient(sshClient)
if err == nil {
c.Client = sftpClient
}
return err
}
作者:jakecoffma
项目:ssh
func main() {
if len(os.Args) < 2 {
usage()
return
}
username, hostnames, pass := parse()
config := &ssh.ClientConfig{
User: username,
Auth: []ssh.AuthMethod{
ssh.Password(string(pass)),
},
}
hosts := []*Host{}
for _, host := range hostnames {
client, err := ssh.Dial("tcp", host+":22", config)
if err != nil {
log.Fatal("Failed to dial: ", err)
}
hosts = append(hosts, &Host{host, client})
}
lock := make(chan string)
for {
fmt.Print("$ ")
reader := bufio.NewReader(os.Stdin)
input, err := reader.ReadString('\n')
if err != nil {
log.Fatal("Error getting user input: ", err)
}
for _, host := range hosts {
go func(host *Host) {
// Each ClientConn can support multiple interactive sessions,
// represented by a Session.
session, err := host.client.NewSession()
if err != nil {
log.Fatal("Failed to create session: ", err)
}
// Once a Session is created, you can execute a single command on
// the remote side using the Run method.
var b bytes.Buffer
session.Stdout = &b
if err := session.Run(input); err != nil {
lock <- fmt.Sprintf("%v\n%v", host.hostname, err)
} else {
lock <- fmt.Sprintf("%v\n%v", host.hostname, b.String())
}
}(host)
}
for _ = range hosts {
fmt.Println(<-lock)
}
}
}
作者:hnakamu
项目:packe
func TestNew_Invalid(t *testing.T) {
clientConfig := &ssh.ClientConfig{
User: "user",
Auth: []ssh.AuthMethod{
ssh.Password("i-am-invalid"),
},
}
address := newMockLineServer(t)
conn := func() (net.Conn, error) {
conn, err := net.Dial("tcp", address)
if err != nil {
t.Errorf("Unable to accept incoming connection: %v", err)
}
return conn, err
}
config := &Config{
Connection: conn,
SSHConfig: clientConfig,
}
_, err := New(address, config)
if err == nil {
t.Fatal("should have had an error connecting")
}
}
作者:hnakamu
项目:packe
func TestStart(t *testing.T) {
clientConfig := &ssh.ClientConfig{
User: "user",
Auth: []ssh.AuthMethod{
ssh.Password("pass"),
},
}
address := newMockLineServer(t)
conn := func() (net.Conn, error) {
conn, err := net.Dial("tcp", address)
if err != nil {
t.Fatalf("unable to dial to remote side: %s", err)
}
return conn, err
}
config := &Config{
Connection: conn,
SSHConfig: clientConfig,
}
client, err := New(address, config)
if err != nil {
t.Fatalf("error connecting to SSH: %s", err)
}
var cmd packer.RemoteCmd
stdout := new(bytes.Buffer)
cmd.Command = "echo foo"
cmd.Stdout = stdout
client.Start(&cmd)
}
作者:JasonGiedymi
项目:terrafor
// PrepareConfig is used to turn the *SSHConfig provided into a
// usable *Config for client initialization.
func PrepareConfig(conf *SSHConfig) (*Config, error) {
sshConf := &ssh.ClientConfig{
User: conf.User,
}
if conf.KeyFile != "" {
key, err := ioutil.ReadFile(conf.KeyFile)
if err != nil {
return nil, fmt.Errorf("Failed to read key file '%s': %v", conf.KeyFile, err)
}
signer, err := ssh.ParsePrivateKey(key)
if err != nil {
return nil, fmt.Errorf("Failed to parse key file '%s': %v", conf.KeyFile, err)
}
sshConf.Auth = append(sshConf.Auth, ssh.PublicKeys(signer))
}
if conf.Password != "" {
sshConf.Auth = append(sshConf.Auth,
ssh.Password(conf.Password))
sshConf.Auth = append(sshConf.Auth,
ssh.KeyboardInteractive(PasswordKeyboardInteractive(conf.Password)))
}
host := fmt.Sprintf("%s:%d", conf.Host, conf.Port)
config := &Config{
SSHConfig: sshConf,
Connection: ConnectFunc("tcp", host),
}
return config, nil
}
作者:antoinelavai
项目:packe
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,
},
NoPty: true,
}
comm, err := ssh.New(address, sshConfig)
if err != nil {
return err
}
d.comm = comm
return nil
}
作者:rphillip
项目:loo
// connect is a private function to set up the ssh connection. It is called at the beginning of every public
// function.
func (config *Config) connect() (*ssh.Session, error) {
sshconfig := &ssh.ClientConfig{
User: config.User,
}
if config.User == "" {
u, err := user.Current()
if err != nil {
return nil, err
}
sshconfig.User = u.Username
}
if config.Password != "" {
sshconfig.Auth = append(sshconfig.Auth, ssh.Password(config.Password))
}
// By default, we try to include ~/.ssh/id_rsa. It is not an error if this file
// doesn't exist.
keyfile := os.Getenv("HOME") + "/.ssh/id_rsa"
pkey, err := parsekey(keyfile)
if err == nil {
sshconfig.Auth = append(sshconfig.Auth, ssh.PublicKeys(pkey))
}
// Include any additional key files
for _, keyfile = range config.KeyFiles {
pkey, err = parsekey(keyfile)
if err != nil {
if config.AbortOnError == true {
log.Fatalf("%s", err)
}
return nil, err
}
sshconfig.Auth = append(sshconfig.Auth, ssh.PublicKeys(pkey))
}
host := config.Host
if strings.Contains(host, ":") == false {
host = host + ":22"
}
client, err := ssh.Dial("tcp", host, sshconfig)
if err != nil {
if config.AbortOnError == true {
log.Fatalf("%s", err)
}
return nil, err
}
session, err := client.NewSession()
if err != nil {
if config.AbortOnError == true {
log.Fatalf("%s", err)
}
return nil, err
}
return session, err
}
作者:nttmc
项目:go-netcon
// SSHConfigPassword is a convience function that takes a username and password
// and returns a new ssh.ClientConfig setup to pass that username and password.
func SSHConfigPassword(user string, pass string) *ssh.ClientConfig {
return &ssh.ClientConfig{
User: user,
Auth: []ssh.AuthMethod{
ssh.Password(pass),
},
}
}
作者:AdrianoJ
项目:gitlab-ci-multi-runne
func (s *Command) getSSHAuthMethods() []ssh.AuthMethod {
var methods []ssh.AuthMethod
if s.Password != nil {
methods = append(methods, ssh.Password(*s.Password))
}
return methods
}
作者:kelixi
项目:sshb
/* Make an attempt from the template. The attempt will eventually go back on
d to the hostmaster, and will be executed against h. */
func (t Template) Attempt(d chan *Attempt, h string) *Attempt {
a := &Attempt{DoneChan: d, Host: h, Pass: t.Pass}
a.Config = &ssh.ClientConfig{User: t.User,
ClientVersion: *gc.Sshvs,
Auth: []ssh.AuthMethod{
ssh.Password(t.Pass),
},
}
return a
}
作者:stephenchen
项目:packer-builder-vult
func sshConfig(state multistep.StateBag) (*ssh.ClientConfig, error) {
config := state.Get("config").(config)
clientConfig := ssh.ClientConfig{User: config.SSHUsername}
if config.OsSnapshot == "" && config.IpxeUrl == "" {
// default case where vultr generated the password
password := state.Get("default_password").(string)
clientConfig.Auth = []ssh.AuthMethod{ssh.Password(password)}
} else if config.SSHPassword != "" {
// special case but we got a password
clientConfig.Auth = []ssh.AuthMethod{ssh.Password(config.SSHPassword)}
} else {
// special case and we got a key
signer, err := ssh.ParsePrivateKey([]byte(config.SSHPrivateKey))
if err != nil {
return nil, fmt.Errorf("Error setting up SSH config: %s", err)
}
clientConfig.Auth = []ssh.AuthMethod{ssh.PublicKeys(signer)}
}
return &clientConfig, nil
}
作者:kelixi
项目:sshb
/* New makes a new attempt from a template with Pass and Config filled in, and
a version string of v. */
func (t template) New(p, v string) attempt {
n := attempt{User: t.User, Pass: p, Host: t.Host, Err: nil}
n.Config = &ssh.ClientConfig{
User: n.User,
Auth: []ssh.AuthMethod{
ssh.Password(n.Pass),
},
ClientVersion: v,
}
return n
}
作者:simonfuhre
项目:packer-builder-xenserver-
func ExecuteHostSSHCmd(state multistep.StateBag, cmd string) (stdout string, err error) {
config := state.Get("commonconfig").(CommonConfig)
// Setup connection config
sshConfig := &gossh.ClientConfig{
User: config.Username,
Auth: []gossh.AuthMethod{
gossh.Password(config.Password),
},
}
return doExecuteSSHCmd(cmd, config.HostIp+":22", sshConfig)
}
作者:jmptrade
项目:runcm
func NewRemotePassAuthRunner(user, host, password string) (*Remote, error) {
config := &ssh.ClientConfig{
User: user,
Auth: []ssh.AuthMethod{ssh.Password(password)},
}
server, err := ssh.Dial("tcp", host, config)
if err != nil {
return nil, err
}
return &Remote{server}, nil
}
作者:golang-alex-alex2006h
项目:launche
func (self *Script) Execute(host *Host, out io.Writer) error {
usr, err := user.Current()
if err != nil {
return err
}
if host.User == "" {
host.User = usr.Username
}
cfg := &ssh.ClientConfig{
User: host.User,
}
if host.Password != "" {
cfg.Auth = []ssh.AuthMethod{
ssh.Password(host.Password),
}
} else {
content, err := ioutil.ReadFile(usr.HomeDir + "/.ssh/id_rsa")
if err != nil {
content, err = ioutil.ReadFile(usr.HomeDir + "/.ssh/id_dsa")
if err != nil {
return err
}
}
key, err := ssh.ParsePrivateKey(content)
if err != nil {
return err
}
cfg.Auth = []ssh.AuthMethod{ssh.PublicKeys(key)}
}
client, err := ssh.Dial("tcp", host.Name+":"+strconv.Itoa(host.Port), cfg)
if err != nil {
fmt.Fprintln(out, err.Error())
return err
}
session, err := client.NewSession()
if err != nil {
fmt.Fprintln(out, err.Error())
return err
}
defer session.Close()
session.Stdout = out
session.Stderr = out
if !self.HideBoundaries {
fmt.Fprintln(out, "---------------------- script started ----------------------")
}
if err := session.Run(self.Content); err != nil {
return err
}
if !self.HideBoundaries {
fmt.Fprintln(out, "---------------------- script finished ----------------------")
}
return nil
}
作者:keysonZZ
项目:km
func DialWithPassword(addr string, username string, password string) (client *ssh.Client, err error) {
clientConfig := &ssh.ClientConfig{
User: username,
Auth: []ssh.AuthMethod{
ssh.Password(password),
},
}
client, err = ssh.Dial("tcp", addr, clientConfig)
if err != nil {
return nil, fmt.Errorf("[DialWithPassword] Failed to dial: %s", err.Error())
}
return
}
作者:heligh
项目:helight_cod
func main() {
// signer, err := ssh.ParsePrivateKey([]byte(pemBytes))
// if err != nil {
// panic(err)
// }
// clientKey := &keychain{signer}
password := "helightxu"
authMethods := []ssh.AuthMethod{}
keyboardInteractiveChallenge := func(
user,
instruction string,
questions []string,
echos []bool,
) (answers []string, err error) {
if len(questions) == 0 {
return []string{}, nil
}
return []string{password}, nil
}
authMethods = append(authMethods, ssh.KeyboardInteractive(keyboardInteractiveChallenge))
authMethods = append(authMethods, ssh.Password(password))
config := &ssh.ClientConfig{
User: "helight",
Auth: authMethods,
}
c, err := ssh.Dial("tcp", "127.0.0.1:22", config)
if err != nil {
log.Println("unable to dial remote side:", err)
}
defer c.Close()
// Create a session
session, err := c.NewSession()
if err != nil {
log.Fatalf("unable to create session: %s", err)
}
defer session.Close()
b, err := session.Output("ls /data/ -l")
if err != nil {
log.Fatalf("failed to execute: %s", err)
}
log.Println("Output: ", string(b))
return
}
作者:lauborge
项目:gopistran
//returns a new deployment
func newDeploy() (d *deploy, err error) {
cfg := &ssh.ClientConfig{
User: user,
Auth: []ssh.AuthMethod{
ssh.Password(pass),
},
}
fmt.Println("SSH-ing into " + hostname)
cl, err := ssh.Dial("tcp", hostname+":22", cfg)
d = &deploy{cl: cl}
return
}
作者:EZTABL
项目:terrafor
// PrepareConfig is used to turn the *SSHConfig provided into a
// usable *Config for client initialization.
func PrepareConfig(conf *SSHConfig) (*Config, error) {
sshConf := &ssh.ClientConfig{
User: conf.User,
}
if conf.KeyFile != "" {
fullPath, err := homedir.Expand(conf.KeyFile)
if err != nil {
return nil, fmt.Errorf("Failed to expand home directory: %v", err)
}
key, err := ioutil.ReadFile(fullPath)
if err != nil {
return nil, fmt.Errorf("Failed to read key file '%s': %v", conf.KeyFile, err)
}
// We parse the private key on our own first so that we can
// show a nicer error if the private key has a password.
block, _ := pem.Decode(key)
if block == nil {
return nil, fmt.Errorf(
"Failed to read key '%s': no key found", conf.KeyFile)
}
if block.Headers["Proc-Type"] == "4,ENCRYPTED" {
return nil, fmt.Errorf(
"Failed to read key '%s': password protected keys are\n"+
"not supported. Please decrypt the key prior to use.", conf.KeyFile)
}
signer, err := ssh.ParsePrivateKey(key)
if err != nil {
return nil, fmt.Errorf("Failed to parse key file '%s': %v", conf.KeyFile, err)
}
sshConf.Auth = append(sshConf.Auth, ssh.PublicKeys(signer))
}
if conf.Password != "" {
sshConf.Auth = append(sshConf.Auth,
ssh.Password(conf.Password))
sshConf.Auth = append(sshConf.Auth,
ssh.KeyboardInteractive(PasswordKeyboardInteractive(conf.Password)))
}
host := fmt.Sprintf("%s:%d", conf.Host, conf.Port)
config := &Config{
SSHConfig: sshConf,
Connection: ConnectFunc("tcp", host),
}
return config, nil
}
作者:zhongxingzh
项目:gitlab-ci-multi-runne
func (s *Command) getSSHAuthMethods() ([]ssh.AuthMethod, error) {
var methods []ssh.AuthMethod
if s.Password != nil {
methods = append(methods, ssh.Password(*s.Password))
}
if s.IdentityFile != nil {
key, err := s.getSSHKey(*s.IdentityFile)
if err != nil {
return nil, err
}
methods = append(methods, ssh.PublicKeys(key))
}
return methods, nil
}