本文整理匯總了Golang中code/google/com/p/go/crypto/ssh.Dial函數的典型用法代碼示例。如果您正苦於以下問題:Golang Dial函數的具體用法?Golang Dial怎麽用?Golang Dial使用的例子?那麽, 這裏精選的函數代碼示例或許可以為您提供幫助。
在下文中一共展示了Dial函數的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。
示例1: getConn
func getConn(host *host.Host) (*ssh.ClientConn, error) {
hostkey := host.Id
if con, ok := conns[hostkey]; ok {
return con, nil
}
if host.User == "" {
return nil, fmt.Errorf("user not set")
}
for _, keyfile := range host.Keyfiles {
// TODO add key to global keyring, ok?
if err := keys.loadPEM(keyfile); err != nil {
return nil, fmt.Errorf("unable to load %s: %v", keyfile, err)
}
}
config := &ssh.ClientConfig{
User: host.User,
Auth: []ssh.ClientAuth{
ssh.ClientAuthKeyring(keys),
},
}
conn, err := ssh.Dial("tcp", host.ConnStr(), config)
if err != nil {
return nil, fmt.Errorf("unable to connect to %s: %v", host, err)
}
conns[hostkey] = conn
return conn, nil
}
示例2: runCmd
func (h *RemoteHelper) runCmd(host, cmd string) string {
client, err := ssh.Dial("tcp", fmt.Sprintf("%s:22", host), h.config)
if err != nil {
log.Fatalf("Failed to dial: " + err.Error())
}
defer client.Close()
session, err := client.NewSession()
if err != nil {
log.Fatal("unable to create session: %s", err)
}
defer session.Close()
err = session.RequestPty("xterm", 80, 40, ssh.TerminalModes{})
if err != nil {
log.Fatal("request for pseudo terminal failed: %s", err)
}
var b bytes.Buffer
session.Stdout = &b
err = session.Run(cmd)
if err != nil {
log.Fatal("Failed to run: " + err.Error())
}
return strings.Replace(strings.Replace(b.String(), "\n", "", -1), "\r", "", -1)
}
示例3: forward
func forward(localConn net.Conn, config *ssh.ClientConfig, serverAddrString, remoteAddrString string) {
// Setup sshClientConn (type *ssh.ClientConn)
sshClientConn, err := ssh.Dial("tcp", serverAddrString, config)
if err != nil {
log.Fatalf("ssh.Dial failed: %s", err)
}
//defer sshClientConn.Close()
// Setup sshConn (type net.Conn)
sshConn, err := sshClientConn.Dial("tcp", remoteAddrString)
if err != nil {
log.Fatalf("sshClientConn.Dial failed: %s", err)
}
//defer sshConn.Close()
// Copy localConn.Reader to sshConn.Writer
go func() {
_, err = io.Copy(sshConn, localConn)
if err != nil {
log.Printf("io.Copy from local to remote failed: %v", err)
}
}()
// Copy sshConn.Reader to localConn.Writer
go func() {
_, err = io.Copy(localConn, sshConn)
if err != nil {
log.Printf("io.Copy from remote to local failed: %v", err)
}
}()
}
示例4: TestSshCmd
func TestSshCmd(t *testing.T) {
kc := new(keychain)
kc.load()
config := &ssh.ClientConfig{
User: os.Getenv("USER"),
Auth: []ssh.ClientAuth{
ssh.ClientAuthKeyring(kc),
},
}
client, err := ssh.Dial("tcp", "localhost: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())
}
log.Printf("Result of running whoami via ssh: %s\n", b)
//fmt.Println(b.String())
}
示例5: dialClient
// Dials to setup tcp connection to remote host, used for memory information
func dialClient() {
t_key, _ := getKeyFile()
if err != nil {
panic(err)
}
key = t_key
config := &ssh.ClientConfig{
User: remote_host_user,
Auth: []ssh.AuthMethod{
ssh.PublicKeys(key),
},
}
t_client, err := ssh.Dial("tcp", remote_host+":"+ssh_port, config)
if err != nil {
fmt.Println("\n", "Failed to dial: "+err.Error())
fmt.Println("Unable to establish connection to remote machine.")
fmt.Println("Make sure that password-less connection is possible.")
fmt.Println("************************************")
mem_flag = false
return
}
ssh_client = t_client
}
示例6: remoteCmdOutput
// remoteCmdOutput runs the given command on a remote server at the given hostname as the given user.
func remoteCmdOutput(username, hostname, cmd string, privateKey []byte) (b []byte, err error) {
p, err := ssh.ParseRawPrivateKey(privateKey)
if err != nil {
return b, err
}
s, err := ssh.NewSignerFromKey(p)
if err != nil {
return b, err
}
pub := ssh.PublicKeys(s)
clientConfig := &ssh.ClientConfig{
User: username,
Auth: []ssh.AuthMethod{pub},
}
client, err := ssh.Dial("tcp", hostname, clientConfig)
if err != nil {
return b, errors.New("ERROR: Failed to dial: " + err.Error())
}
defer client.Close()
session, err := client.NewSession()
if err != nil {
return b, errors.New("ERROR: Failed to create session: " + err.Error())
}
defer session.Close()
b, err = session.Output(cmd)
if err != nil {
return b, fmt.Errorf("ERROR: Failed to run cmd on host %s: %s", hostname, err.Error())
}
return b, nil
}
示例7: ExecuteCmd
func ExecuteCmd(cmd, hostname string, config *ssh.ClientConfig, stdout chan string, stderr chan error) {
conn, err := ssh.Dial("tcp", hostname+":22", config)
if err != nil {
stderr <- err
return
}
session, err := conn.NewSession()
defer session.Close()
if err != nil {
stderr <- err
return
}
pipe, _ := session.StdoutPipe()
session.Start(cmd)
buffer := bufio.NewReader(pipe)
for {
line, err := buffer.ReadString('\n')
if len(line) > 0 {
stdout <- line
}
if err != nil {
if err == io.EOF {
close(stdout)
return
} else {
stderr <- err
return
}
}
}
}
示例8: main
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)
}
}
}
示例9: NewTranportSSH
func NewTranportSSH(target string, config *ssh.ClientConfig) (*TransportSSH, error) {
if !strings.Contains(target, ":") {
target = fmt.Sprintf("%s:%d", target, SSH_DEFAULT_PORT)
}
conn, err := ssh.Dial("tcp", target, config)
if err != nil {
return nil, err
}
sess, err := conn.NewSession()
if err != nil {
return nil, err
}
si, err := sess.StdinPipe()
if err != nil {
return nil, err
}
so, err := sess.StdoutPipe()
if err != nil {
return nil, err
}
if err := sess.RequestSubsystem(SSH_NETCONF_SUBSYSTEM); err != nil {
return nil, err
}
return &TransportSSH{sshConn: conn, sshSession: sess, sshStdin: si, sshStdout: so}, nil
}
示例10: Connect
func (s *Command) Connect() error {
host := helpers.StringOrDefault(s.Host, "localhost")
user := helpers.StringOrDefault(s.User, "root")
port := helpers.StringOrDefault(s.Port, "22")
methods, err := s.getSSHAuthMethods()
if err != nil {
return err
}
config := &ssh.ClientConfig{
User: user,
Auth: methods,
}
connectRetries := s.ConnectRetries
if connectRetries == 0 {
connectRetries = 3
}
var finalError error
for i := 0; i < connectRetries; i++ {
client, err := ssh.Dial("tcp", host+":"+port, config)
if err == nil {
s.client = client
return nil
}
time.Sleep(sshRetryInterval * time.Second)
finalError = err
}
return finalError
}
示例11: remoteCmdOutput
func remoteCmdOutput(username, hostname, privateKey, cmd string) []byte {
block, _ := pem.Decode([]byte(privateKey))
rsakey, _ := x509.ParsePKCS1PrivateKey(block.Bytes)
clientKey := &keychain{rsakey}
clientConfig := &ssh.ClientConfig{
User: username,
Auth: []ssh.ClientAuth{
ssh.ClientAuthKeyring(clientKey),
},
}
client, err := ssh.Dial("tcp", hostname, clientConfig)
if err != nil {
log.Println("ERROR: Failed to dial: " + err.Error())
return []byte{}
}
session, err := client.NewSession()
if err != nil {
log.Println("ERROR: Failed to create session: " + err.Error())
return []byte{}
}
defer session.Close()
output, err := session.Output(cmd)
if err != nil {
log.Printf("ERROR: Failed to run cmd on host %s: %s", hostname, err.Error())
return []byte{}
}
return output
}
示例12: getConnection
func getConnection(hostname string) (conn *ssh.ClientConn, err error) {
connectedHostsMutex.Lock()
conn = connectedHosts[hostname]
connectedHostsMutex.Unlock()
if conn != nil {
return
}
defer func() {
if msg := recover(); msg != nil {
err = errors.New("Panic: " + fmt.Sprint(msg))
}
}()
conn, err = ssh.Dial("tcp", hostname+":22", makeConfig())
if err != nil {
return
}
sendProxyReply(&ConnectionProgress{ConnectedHost: hostname})
connectedHostsMutex.Lock()
connectedHosts[hostname] = conn
connectedHostsMutex.Unlock()
return
}
示例13: main
func main() {
key, err := getKeyFile()
if err != nil {
panic(err)
}
config := &ssh.ClientConfig{
User: "jaibheemsen",
Auth: []ssh.AuthMethod{ssh.PublicKeys(key)},
}
client, err := ssh.Dial("tcp", "localhost:22", config)
if err != nil {
panic(err)
}
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(err.Error())
}
fmt.Println(b.String())
} //godoc -http=:1989 -index=true
示例14: DialInConsole
//TODO 某種認證方法隻有一個會被使用,需要多次猜測
func DialInConsole(addr string, username string) (client *ssh.Client, err error) {
//find cert file
pathList := certFilePathList()
authList := []ssh.AuthMethod{}
for _, path := range pathList {
clientKeyBytes, err := ioutil.ReadFile(path)
if err != nil {
if !os.IsNotExist(err) {
return nil, fmt.Errorf("[DialInConsole] ioutil.ReadFile() err:%s", err)
}
} else {
signer, err := ssh.ParsePrivateKey(clientKeyBytes)
if err != nil {
return nil, fmt.Errorf("[DialInConsole] ssh.ParsePrivateKey err:%s", err)
}
//clientKey := &keychain{signer}
authList = append(authList, ssh.PublicKeys(signer))
}
}
authList = append(authList, ssh.PasswordCallback(func() (secret string, err error) {
fmt.Printf("[ssh] password for %[email protected]%s", username, addr)
secret = string(gopass.GetPasswd())
return
}))
clientConfig := &ssh.ClientConfig{
User: username,
Auth: authList,
}
client, err = ssh.Dial("tcp", addr, clientConfig)
if err != nil {
return nil, fmt.Errorf("[DialInConsole] Failed to dial: %s", err.Error())
}
return
}
示例15: getSftpClient
func getSftpClient(conf Config) []*sftp.Client {
// process the keyfile
buf, err := ioutil.ReadFile(conf.KeyFile)
if err != nil {
log.Fatalf("error in reading private key file %s\n", err)
}
key, err := ssh.ParsePrivateKey(buf)
if err != nil {
log.Fatalf("error in parsing private key %s\n", key)
}
// client config
config := &ssh.ClientConfig{
User: conf.User,
Auth: []ssh.AuthMethod{ssh.PublicKeys(key)},
}
// connection
clients := make([]*sftp.Client, 0)
for _, r := range conf.Remotes {
c, err := ssh.Dial("tcp", r, config)
if err != nil {
log.Fatalf("error in ssh connection %s\n", err)
}
// sftp handler
sftp, err := sftp.NewClient(c)
if err != nil {
log.Fatalf("error in sftp connection %s\n", err)
}
clients = append(clients, sftp)
}
return clients
}