本文整理汇总了Golang中golang.org/x/crypto/ssh.Dial函数的典型用法代码示例。如果您正苦于以下问题:Golang Dial函数的具体用法?Golang Dial怎么用?Golang Dial使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了Dial函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: SSHClient
// SSHClient returns an ssh.Client object that could be used to ssh to the
// server. Requires that port 22 is accessible for SSH.
func (s *Server) SSHClient() (*ssh.Client, error) {
s.mutex.Lock()
defer s.mutex.Unlock()
if s.sshclient == nil {
if s.provider.PrivateKey() == "" {
log.Printf("resource file %s did not contain the ssh key\n", s.provider.savePath)
return nil, errors.New("missing ssh key")
}
// parse private key and make config
key, err := ssh.ParsePrivateKey([]byte(s.provider.PrivateKey()))
if err != nil {
log.Printf("failure to parse the private key: %s\n", err)
return nil, err
}
sshConfig := &ssh.ClientConfig{
User: s.UserName,
Auth: []ssh.AuthMethod{
ssh.PublicKeys(key),
},
}
// dial in to the server, allowing certain errors that indicate that the
// network or server isn't really ready for ssh yet; wait for up to
// 5mins for success
hostAndPort := s.IP + ":22"
s.sshclient, err = ssh.Dial("tcp", hostAndPort, sshConfig)
if err != nil {
limit := time.After(5 * time.Minute)
ticker := time.NewTicker(1 * time.Second)
DIAL:
for {
select {
case <-ticker.C:
s.sshclient, err = ssh.Dial("tcp", hostAndPort, sshConfig)
if err != nil && (strings.HasSuffix(err.Error(), "connection timed out") || strings.HasSuffix(err.Error(), "no route to host") || strings.HasSuffix(err.Error(), "connection refused")) {
continue DIAL
}
// worked, or failed with a different error: stop trying
ticker.Stop()
break DIAL
case <-limit:
ticker.Stop()
err = errors.New("giving up waiting for ssh to work")
break DIAL
}
}
if err != nil {
return nil, err
}
}
}
return s.sshclient, nil
}
示例2: Connect
func (S *SshParm) Connect() (*ssh.Client, error) {
var (
cfg *ssh.ClientConfig
)
if S.SSHAuthType == SSHAuthType_Certificate {
cfg = &ssh.ClientConfig{
User: S.SSHUser,
Auth: []ssh.AuthMethod{
PublicKeyFile(S.SSHKeyLocation),
},
}
} else {
cfg = &ssh.ClientConfig{
User: S.SSHUser,
Auth: []ssh.AuthMethod{
ssh.Password(S.SSHPassword),
},
}
}
client, e := ssh.Dial("tcp", S.SSHHost, cfg)
return client, e
}
示例3: dialSuccess
func (client NativeClient) dialSuccess() bool {
if _, err := ssh.Dial("tcp", fmt.Sprintf("%s:%d", client.Hostname, client.Port), &client.Config); err != nil {
log.Debugf("Error dialing TCP: %s", err)
return false
}
return true
}
示例4: waitForVmSsh
// Simply waits for ssh to come up
func waitForVmSsh(d *schema.ResourceData) error {
l := log.New(os.Stderr, "", 0)
l.Printf("Waiting for VM ssh: %s", d.Get("name"))
config := &ssh.ClientConfig{
User: "root",
Auth: []ssh.AuthMethod{
ssh.Password(d.Get("root_password").(string)),
},
}
for {
select {
case <-time.After(waitForVM * time.Second):
return fmt.Errorf("VM ssh wasn't up in %d seconds", waitForVM)
case <-time.Tick(vmCheckInterval * time.Second):
conn, err := ssh.Dial("tcp", fmt.Sprintf("%s:22", d.Get("ipv4")), config)
if err != nil {
if strings.Contains(err.Error(), "connection refused") {
l.Println("SSH isn't up yet")
continue
} else {
l.Printf("SSH Error, ignored: %s", err.Error())
continue
}
}
conn.Close()
l.Println("SSH alive and kicking")
return nil
}
}
return errors.New("Ssh wait should never get here")
}
示例5: NewVagrantNode
//NewVagrantNode intializes a node in vagrant testbed
func NewVagrantNode(name, port, privKeyFile string) (*VagrantNode, error) {
var (
vnode *VagrantNode
err error
signer ssh.Signer
privateKey []byte
)
if privateKey, err = ioutil.ReadFile(privKeyFile); err != nil {
return nil, err
}
if signer, err = ssh.ParsePrivateKey(privateKey); err != nil {
return nil, err
}
config := &ssh.ClientConfig{
User: "vagrant",
Auth: []ssh.AuthMethod{
ssh.PublicKeys(signer),
},
}
vnode = &VagrantNode{Name: name}
if vnode.client, err = ssh.Dial("tcp", fmt.Sprintf("127.0.0.1:%s", port), config); err != nil {
return nil, err
}
return vnode, nil
}
示例6: Init
func (this *Scp) Init(target_server, user, identity string) (*Scp, error) {
this.Server = target_server
this.User = user
this.Identity = identity
AuthKey, err := PublicKeyFile(this.Identity)
if nil != err {
return nil, err
}
this.clientConfig = &ssh.ClientConfig{
User: this.User,
Auth: []ssh.AuthMethod{AuthKey},
}
ParallelController[this.Server].Connection <- token
this.client, err = ssh.Dial("tcp", this.Server+":22", this.clientConfig)
if nil != err {
return nil, errors.New("Failed to dial: " + err.Error())
}
return this, nil
}
示例7: ExampleSession_RequestPty
func ExampleSession_RequestPty() {
// Create client config
config := &ssh.ClientConfig{
User: "username",
Auth: []ssh.AuthMethod{
ssh.Password("password"),
},
}
// Connect to ssh server
conn, err := ssh.Dial("tcp", "localhost:22", config)
if err != nil {
log.Fatalf("unable to connect: %s", err)
}
defer conn.Close()
// Create a session
session, err := conn.NewSession()
if err != nil {
log.Fatalf("unable to create session: %s", err)
}
defer session.Close()
// Set up terminal modes
modes := ssh.TerminalModes{
ssh.ECHO: 0, // disable echoing
ssh.TTY_OP_ISPEED: 14400, // input speed = 14.4kbaud
ssh.TTY_OP_OSPEED: 14400, // output speed = 14.4kbaud
}
// Request pseudo terminal
if err := session.RequestPty("xterm", 80, 40, modes); err != nil {
log.Fatalf("request for pseudo terminal failed: %s", err)
}
// Start remote shell
if err := session.Shell(); err != nil {
log.Fatalf("failed to start shell: %s", err)
}
}
示例8: ExampleDial
func ExampleDial() {
// An SSH client is represented with a ClientConn. Currently only
// the "password" authentication method is supported.
//
// To authenticate with the remote server you must pass at least one
// implementation of AuthMethod via the Auth field in ClientConfig.
config := &ssh.ClientConfig{
User: "username",
Auth: []ssh.AuthMethod{
ssh.Password("yourpassword"),
},
}
client, err := ssh.Dial("tcp", "yourserver.com:22", config)
if err != nil {
panic("Failed to dial: " + err.Error())
}
// Each ClientConn can support multiple interactive sessions,
// represented by a Session.
session, err := client.NewSession()
if err != nil {
panic("Failed to create session: " + err.Error())
}
defer session.Close()
// 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("/usr/bin/whoami"); err != nil {
panic("Failed to run: " + err.Error())
}
fmt.Println(b.String())
}
示例9: NewConnection
func NewConnection(host string, port int, username string, password string, key_path string) (*ssh.Client, error) {
var config *ssh.ClientConfig
if USEKEY {
public_key, err := getKeyFromFile(key_path)
if err != nil {
log.Panic(err)
}
config = &ssh.ClientConfig{
User: username,
Auth: []ssh.AuthMethod{
ssh.PublicKeys(public_key),
},
}
} else {
config = &ssh.ClientConfig{
User: username,
Auth: []ssh.AuthMethod{
ssh.Password(password),
},
}
}
client, err := ssh.Dial("tcp", host+":"+strconv.Itoa(port), config)
if err != nil {
panic("Failed to dial: " + err.Error())
}
// Each ClientConn can support multiple interactive sessions,
// represented by a Session.
return client, err
}
示例10: DownLoadDirectoryRecurrsively
func DownLoadDirectoryRecurrsively(hostAndPort string, username string,
password string, remoteSourceDirectory string, localTargetDirectory string) error {
remoteSourceDirectoryLength := len(remoteSourceDirectory)
authMethodSlice := make([]ssh.AuthMethod, 0)
authMethodSlice = append(authMethodSlice, ssh.Password(password))
clientConfig := ssh.ClientConfig{
User: username,
Auth: authMethodSlice,
}
connection, err := ssh.Dial("tcp", hostAndPort, &clientConfig)
if err != nil {
return err
}
defer connection.Close()
// open an SFTP session over an existing ssh connection.
client, err := sftp.NewClient(connection)
if err != nil {
return err
}
defer client.Close()
// walk a directory
walk := client.Walk(remoteSourceDirectory)
for walk.Step() {
if err := walk.Err(); err != nil {
return err
}
if walk.Stat().IsDir() {
directoryPath := localTargetDirectory + walk.Path()[remoteSourceDirectoryLength:]
if err := os.MkdirAll(directoryPath, os.ModePerm); err != nil {
return err
}
} else {
filePath := localTargetDirectory + walk.Path()[remoteSourceDirectoryLength:]
file, err := client.Open(walk.Path())
if err != nil {
return err
}
defer file.Close()
outputFile, err := os.OpenFile(filePath, os.O_CREATE|os.O_WRONLY, os.ModePerm)
if err != nil {
return err
}
defer outputFile.Close()
_, err = file.WriteTo(outputFile)
if err != nil {
return err
}
}
}
return nil
}
示例11: TestClientConnection
func (suite *ServerSuite) TestClientConnection() {
// Get signer
signer, err := ssh.ParsePrivateKey([]byte(clientPrivateKey))
if err != nil {
suite.Fail("Private key could not be parsed" + err.Error())
}
// Configure client connection
config := &ssh.ClientConfig{
User: "admin",
Auth: []ssh.AuthMethod{
ssh.PublicKeys(signer),
},
}
// Create client connection
client, err := ssh.Dial("tcp", "127.0.0.1:9022", config)
if err != nil {
suite.Fail(err.Error())
return
}
defer client.Close()
// Open channel
channel, requests, err := client.OpenChannel("/echo", []byte{})
if err != nil {
suite.Fail(err.Error())
return
}
go ssh.DiscardRequests(requests)
defer channel.Close()
}
示例12: TestHandlerError
func (suite *ServerSuite) TestHandlerError() {
// Configure client connection
config := &ssh.ClientConfig{
User: "jonny.quest",
Auth: []ssh.AuthMethod{
ssh.Password("bandit"),
},
}
// Create client connection
client, err := ssh.Dial("tcp", "127.0.0.1:9022", config)
if err != nil {
suite.Fail(err.Error())
return
}
defer client.Close()
// Open channel
channel, requests, err := client.OpenChannel("/bad", []byte{})
if err != nil {
suite.Fail(err.Error())
return
}
go ssh.DiscardRequests(requests)
defer channel.Close()
}
示例13: TestUnknownChannel
func (suite *ServerSuite) TestUnknownChannel() {
// Get signer
signer, err := ssh.ParsePrivateKey([]byte(clientPrivateKey))
if err != nil {
suite.Fail("Private key could not be parsed" + err.Error())
}
// Configure client connection
config := &ssh.ClientConfig{
User: "admin",
Auth: []ssh.AuthMethod{
ssh.PublicKeys(signer),
},
}
// Create client connection
client, err := ssh.Dial("tcp", "127.0.0.1:9022", config)
if err != nil {
suite.Fail(err.Error())
return
}
defer client.Close()
// Open channel
_, _, err = client.OpenChannel("/shell", []byte{})
suite.NotNil(err, "server should not accept shell channels")
}
示例14: main
func main() {
config := &ssh.ClientConfig{
User: "meuUsuario",
Auth: []ssh.AuthMethod{
ssh.Password("minhaSenha"),
},
}
client, err := ssh.Dial("tcp", "meuservidor.com:22", config)
if err != nil {
panic("Failed to dial: " + err.Error())
}
session, err := client.NewSession()
if err != nil {
panic("Failed to create session: " + err.Error())
}
defer session.Close()
var b bytes.Buffer
session.Stdout = &b
if err := session.Run("/usr/bin/whoami"); err != nil {
panic("Failed to run: " + err.Error())
}
fmt.Println(b.String())
}
示例15: connect
// Creates a ssh connection between the local machine and the remote server.
func (p *project) connect(config *ssh.ClientConfig) {
fmt.Println("Trying connection...")
conn, err := ssh.Dial("tcp", fmt.Sprintf("%s:%s", p.hostname.name, p.port.name), config)
errorUtil.CheckError("Failed to dial: ", err)
fmt.Println("Connection established.")
session, err := conn.NewSession()
errorUtil.CheckError("Failed to build session: ", err)
defer session.Close()
// Loops over the slice of commands to be executed on the remote.
for step := range p.typ.program.setup {
if p.typ.program.setup[step] == "post-update configuration" {
p.secureCopy(conn)
} else if p.typ.program.setup[step] == p.projectname.name+".dev" {
p.makeDirOnLocal(step)
} else if p.typ.program.setup[step] == "git clone" {
p.gitOnLocal(step)
} else {
p.installOnRemote(step, conn)
}
}
}