Created
September 9, 2018 13:26
-
-
Save proclaim/12acb1923c1caa02daa82891545199c2 to your computer and use it in GitHub Desktop.
helper for creating a sftpclient
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package sftpclient | |
import ( | |
"fmt" | |
"github.com/pkg/sftp" | |
"golang.org/x/crypto/ssh" | |
"net" | |
"time" | |
) | |
// SFTPClient contains the actual client and ssh connection | |
type SFTPClient struct { | |
Client *sftp.Client | |
connection *ssh.Client | |
} | |
type SSHServer struct { | |
Address string // host:port | |
Host string // IP address | |
Port int // port | |
IsSSH bool // true if server is running SSH on address:port | |
Banner string // banner text, if any | |
Cert ssh.Certificate // server's certificate | |
Hostname string // hostname | |
PublicKey ssh.PublicKey // server's public key | |
} | |
type HostAuthorityCallBack func(ssh.PublicKey, string) bool | |
type IsRevokedCallback func(cert *ssh.Certificate) bool | |
// New will construct sftp client to be consumed | |
func New(user, pass, host string, port int) (*SFTPClient, error) { | |
s := &SSHServer{ | |
Host: host, | |
Port: port, | |
} | |
certCheck := &ssh.CertChecker{ | |
IsHostAuthority: hostAuthCallback(), | |
IsRevoked: certCallback(s), | |
HostKeyFallback: hostCallback(s), | |
} | |
cf := &ssh.ClientConfig{ | |
User: user, | |
Auth: []ssh.AuthMethod{ | |
ssh.Password(pass), | |
}, | |
Timeout: 30 * time.Second, | |
Config: ssh.Config{ | |
Ciphers: []string{"aes128-ctr", "aes192-ctr", "aes256-ctr"}, | |
}, | |
HostKeyCallback: certCheck.CheckHostKey, | |
} | |
addr := fmt.Sprintf("%s:%d", host, port) | |
conn, err := ssh.Dial("tcp", addr, cf) | |
if err != nil { | |
return nil, err | |
} | |
sftpClient, err := sftp.NewClient(conn) | |
if err != nil { | |
return nil, err | |
} | |
var sftpConsole SFTPClient | |
sftpConsole.connection = conn | |
sftpConsole.Client = sftpClient | |
return &sftpConsole, nil | |
} | |
// Close will assist closing all connections | |
func (sf *SFTPClient) Close() { | |
sf.connection.Close() | |
sf.Client.Close() | |
} | |
func hostAuthCallback() HostAuthorityCallBack { | |
return func(p ssh.PublicKey, addr string) bool { | |
return true | |
} | |
} | |
func certCallback(s *SSHServer) IsRevokedCallback { | |
return func(cert *ssh.Certificate) bool { | |
s.Cert = *cert | |
s.IsSSH = true | |
return false | |
} | |
} | |
func hostCallback(s *SSHServer) ssh.HostKeyCallback { | |
return func(hostname string, remote net.Addr, key ssh.PublicKey) error { | |
s.Hostname = hostname | |
s.PublicKey = key | |
return nil | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment