Documentation ¶
Overview ¶
Package sshlib is a library to easily connect with ssh by go. You can perform multiple proxy, x11 forwarding, PKCS11 authentication, etc...
Example simple ssh shell ¶
It is example code. simple connect ssh shell. You can also do tab completion, send sigint signal(Ctrl+C).
package main import ( "fmt" "os" sshlib "github.com/blacknon/go-sshlib" "golang.org/x/crypto/ssh" ) var ( host = "target.com" port = "22" user = "user" password = "password" termlog = "./test_termlog" ) func main() { // Create sshlib.Connect con := &sshlib.Connect{ // If you use x11 forwarding, please set to true. ForwardX11: false, // If you use ssh-agent forwarding, please set to true. // And after, run `con.ConnectSshAgent()`. ForwardAgent: false, } // Create ssh.AuthMethod authMethod := sshlib.CreateAuthMethodPassword(password) // If you use ssh-agent forwarding, uncomment it. // con.ConnectSshAgent() // Connect ssh server err := con.CreateClient(host, port, user, []ssh.AuthMethod{authMethod}) if err != nil { fmt.Println(err) os.Exit(1) } // Set terminal log con.SetLog(termlog, false) // Start ssh shell con.Shell() }
Example simple ssh proxy shell ¶
Multple proxy by ssh connection is also available. Please refer to the sample code for usage with http and socks5 proxy.
package main import ( "fmt" "os" sshlib "github.com/blacknon/go-sshlib" "golang.org/x/crypto/ssh" ) var ( // Proxy ssh server host1 = "proxy.com" port1 = "22" user1 = "user" password1 = "password" // Target ssh server host2 = "target.com" port2 = "22" user2 = "user" password2 = "password" termlog = "./test_termlog" ) func main() { // ========== // proxy connect // ========== // Create proxy sshlib.Connect proxyCon := &sshlib.Connect{} // Create proxy ssh.AuthMethod proxyAuthMethod := sshlib.CreateAuthMethodPassword(password1) // Connect proxy server err := proxyCon.CreateClient(host1, port1, user1, []ssh.AuthMethod{proxyAuthMethod}) if err != nil { fmt.Println(err) os.Exit(1) } // ========== // target connect // ========== // Create target sshlib.Connect targetCon := &sshlib.Connect{ ProxyDialer: proxyCon.Client, } // Create target ssh.AuthMethod targetAuthMethod := sshlib.CreateAuthMethodPassword(password2) // Connect target server err = targetCon.CreateClient(host2, port2, user2, []ssh.AuthMethod{targetAuthMethod}) if err != nil { fmt.Println(err) os.Exit(1) } // Set terminal log targetCon.SetLog(termlog, false) // Start ssh shell targetCon.Shell() }
This library was created for my ssh client (https://github.com/blacknon/lssh)
Index ¶
- func CreateAuthMethodCertificate(cert string, keySigner ssh.Signer) (auth ssh.AuthMethod, err error)
- func CreateAuthMethodPKCS11(provider, pin string) (auth []ssh.AuthMethod, err error)
- func CreateAuthMethodPassword(password string) (auth ssh.AuthMethod)
- func CreateAuthMethodPublicKey(key, password string) (auth ssh.AuthMethod, err error)
- func CreateSignerAgent(sshAgent interface{}) (signers []ssh.Signer, err error)
- func CreateSignerCertificate(cert string, keySigner ssh.Signer) (certSigner ssh.Signer, err error)
- func CreateSignerPKCS11(provider, pin string) (signers []ssh.Signer, err error)
- func CreateSignerPublicKey(key, password string) (signer ssh.Signer, err error)
- func CreateSignerPublicKeyData(keyData []byte, password string) (signer ssh.Signer, err error)
- func CreateSignerPublicKeyPrompt(key, password string) (signer ssh.Signer, err error)
- func GetStdin() io.ReadCloser
- func NewChangeOSFS(fs billy.Filesystem) billy.Filesystem
- func NewChangeSFTPFS(client *sftp.Client, base string) billy.Filesystem
- func RequestTty(session *ssh.Session) (err error)
- type AgentInterface
- type C11
- type COS
- func (fs COS) Chmod(name string, mode os.FileMode) error
- func (fs COS) Chown(name string, uid, gid int) error
- func (fs COS) Chtimes(name string, atime time.Time, mtime time.Time) error
- func (fs COS) Lchown(name string, uid, gid int) error
- func (fs COS) Link(path string, link string) error
- func (fs COS) Mkfifo(path string, mode uint32) error
- func (fs COS) Mknod(path string, mode uint32, major uint32, minor uint32) error
- func (fs COS) Socket(path string) error
- type Connect
- func (c *Connect) AddKeySshAgent(sshAgent interface{}, key interface{})
- func (c *Connect) ChangeWinSize(session *ssh.Session)
- func (c *Connect) CheckClientAlive() error
- func (c *Connect) CmdShell(session *ssh.Session, command string) (err error)
- func (c *Connect) Command(command string) (err error)
- func (c *Connect) CreateClient(host, port, user string, authMethods []ssh.AuthMethod) (err error)
- func (c *Connect) CreateSession() (session *ssh.Session, err error)
- func (c *Connect) ForwardSshAgent(session *ssh.Session)
- func (c *Connect) HTTPDynamicForward(address, port string) (err error)
- func (c *Connect) HTTPReverseDynamicForward(address, port string) (err error)
- func (c *Connect) NFSForward(address, port, basepoint string) (err error)
- func (c *Connect) NFSReverseForward(address, port, sharepoint string) (err error)
- func (c *Connect) SendKeepAlive(session *ssh.Session)
- func (c *Connect) SetLog(path string, timestamp bool)
- func (c *Connect) SetLogWithRemoveAnsiCode(path string, timestamp bool)
- func (c *Connect) Shell(session *ssh.Session) (err error)
- func (c *Connect) TCPDynamicForward(address, port string) (err error)
- func (c *Connect) TCPLocalForward(localAddr, remoteAddr string) (err error)
- func (c *Connect) TCPRemoteForward(localAddr, remoteAddr string) (err error)
- func (c *Connect) TCPReverseDynamicForward(address, port string) (err error)
- func (c *Connect) VerifyAndAppendNew(hostname string, remote net.Addr, key ssh.PublicKey) (err error)
- func (c *Connect) X11Forward(session *ssh.Session) (err error)
- type ContextDialer
- type NetPipe
- type OverwriteInventory
- type Proxy
- func (p *Proxy) CreateHttpProxyDialer() (proxyDialer proxy.Dialer, err error)
- func (p *Proxy) CreateProxyCommandProxyDialer() (proxyDialer proxy.Dialer, err error)
- func (p *Proxy) CreateProxyDialer() (proxyContextDialer ProxyDialer, err error)
- func (p *Proxy) CreateSocks5ProxyDialer() (proxyDialer proxy.Dialer, err error)
- type ProxyDialer
- type SFTPFS
- func (fs *SFTPFS) Capabilities() billy.Capability
- func (fs *SFTPFS) Create(filename string) (billy.File, error)
- func (fs *SFTPFS) Join(elem ...string) string
- func (fs *SFTPFS) Lstat(filename string) (os.FileInfo, error)
- func (fs *SFTPFS) MkdirAll(filename string, perm os.FileMode) error
- func (fs *SFTPFS) Open(filename string) (billy.File, error)
- func (fs *SFTPFS) OpenFile(filename string, flag int, perm os.FileMode) (billy.File, error)
- func (fs *SFTPFS) ReadDir(path string) ([]os.FileInfo, error)
- func (fs *SFTPFS) Readlink(link string) (string, error)
- func (fs *SFTPFS) Remove(filename string) error
- func (fs *SFTPFS) RemoveAll(filename string) error
- func (fs *SFTPFS) Rename(from, to string) error
- func (fs *SFTPFS) Stat(filename string) (os.FileInfo, error)
- func (fs *SFTPFS) Symlink(target, link string) error
- func (fs *SFTPFS) TempFile(dir, prefix string) (billy.File, error)
- type WriteInventory
- type XAuth
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func CreateAuthMethodCertificate ¶
func CreateAuthMethodCertificate(cert string, keySigner ssh.Signer) (auth ssh.AuthMethod, err error)
CreateAuthMethodCertificate returns ssh.AuthMethod generated from Certificate. To generate an AuthMethod from a certificate, you will need the certificate's private key Signer. Signer should be generated from CreateSignerPublicKey() or CreateSignerPKCS11().
func CreateAuthMethodPKCS11 ¶
func CreateAuthMethodPKCS11(provider, pin string) (auth []ssh.AuthMethod, err error)
CreateAuthMethodPKCS11 return []ssh.AuthMethod generated from pkcs11 token. PIN is required to generate a AuthMethod from a PKCS 11 token. Not available if cgo is disabled.
WORNING: Does not work if multiple tokens are stuck at the same time.
func CreateAuthMethodPassword ¶
func CreateAuthMethodPassword(password string) (auth ssh.AuthMethod)
CreateAuthMethodPassword returns ssh.AuthMethod generated from password.
func CreateAuthMethodPublicKey ¶
func CreateAuthMethodPublicKey(key, password string) (auth ssh.AuthMethod, err error)
CreateAuthMethodPublicKey returns ssh.AuthMethod generated from PublicKey. If you have not specified a passphrase, please specify a empty character("").
func CreateSignerAgent ¶ added in v0.1.1
CreateSignerAgent return []ssh.Signer from ssh-agent. In sshAgent, put agent.Agent or agent.ExtendedAgent.
func CreateSignerCertificate ¶
CreateSignerCertificate returns ssh.Signer generated from Certificate. To generate an AuthMethod from a certificate, you will need the certificate's private key Signer. Signer should be generated from CreateSignerPublicKey() or CreateSignerPKCS11().
func CreateSignerPKCS11 ¶
CreateSignerPKCS11 returns []ssh.Signer generated from PKCS11 token. PIN is required to generate a Signer from a PKCS 11 token. Not available if cgo is disabled.
WORNING: Does not work if multiple tokens are stuck at the same time.
func CreateSignerPublicKey ¶
CreateSignerPublicKey returns []ssh.Signer generated from public key. If you have not specified a passphrase, please specify a empty character("").
func CreateSignerPublicKeyData ¶ added in v0.1.1
CreateSignerPublicKeyData return ssh.Signer from private key and password
func CreateSignerPublicKeyPrompt ¶ added in v0.1.1
CreateSignerPublicKeyPrompt rapper CreateSignerPKCS11. Output a passphrase input prompt if the passphrase is not entered or incorrect.
Only Support UNIX-like OS.
func GetStdin ¶ added in v0.1.6
func GetStdin() io.ReadCloser
func NewChangeOSFS ¶ added in v0.1.16
func NewChangeOSFS(fs billy.Filesystem) billy.Filesystem
NewChangeOSFS wraps billy osfs to add the change interface
func NewChangeSFTPFS ¶ added in v0.1.16
func RequestTty ¶
RequestTty requests the association of a pty with the session on the remote host. Terminal size is obtained from the currently connected terminal
Types ¶
type AgentInterface ¶
type AgentInterface interface{}
AgentInterface Interface for storing agent.Agent or agent.ExtendedAgent.
type C11 ¶ added in v0.1.2
C11 struct for Crypto11 processing. Not available if cgo is disabled.
type COS ¶ added in v0.1.16
type COS struct {
billy.Filesystem
}
COS or OSFS + Change wraps a billy.FS to not fail the `Change` interface.
type Connect ¶
type Connect struct { // Client *ssh.Client Client *ssh.Client // Session Session *ssh.Session // Session Stdin, Stdout, Stderr... Stdin io.Reader Stdout io.Writer Stderr io.Writer // ProxyDialer ProxyDialer proxy.ContextDialer // Connect timeout second. ConnectTimeout int // SendKeepAliveMax and SendKeepAliveInterval SendKeepAliveMax int SendKeepAliveInterval int // Session use tty flag. // Set it before CraeteClient. TTY bool // Forward ssh agent flag. // Set it before CraeteClient. ForwardAgent bool // Set the TTY to be used as the input and output for the Session/Cmd. PtyRelayTty *os.File // StdoutMutex is a mutex for use Stdout. StdoutMutex *sync.Mutex // CheckKnownHosts if true, check knownhosts. // Ignored if HostKeyCallback is set. // Set it before CraeteClient. CheckKnownHosts bool // HostKeyCallback is ssh.HostKeyCallback. // This item takes precedence over `CheckKnownHosts`. // Set it before CraeteClient. HostKeyCallback ssh.HostKeyCallback // OverwriteKnownHosts if true, if the knownhost is different, check whether to overwrite. OverwriteKnownHosts bool // KnownHostsFiles is list of knownhosts files path. KnownHostsFiles []string // TextAskWriteKnownHosts defines a confirmation message when writing a knownhost. // We are using Go's template engine and have the following variables available. // - Address ... ssh server hostname // - RemoteAddr ... ssh server address // - Fingerprint ... ssh PublicKey fingerprint TextAskWriteKnownHosts string // TextAskOverwriteKnownHosts defines a confirmation message when over-writing a knownhost. // We are using Go's template engine and have the following variables available. // - Address ... ssh server hostname // - RemoteAddr ... ssh server address // - OldKeyText ... old ssh PublicKey text. // ex: /home/user/.ssh/known_hosts:17: ecdsa-sha2-nistp256 AAAAE2VjZHN...bJklasnFtkFSDyOjTFSv2g= // - NewFingerprint ... new ssh PublicKey fingerprint TextAskOverwriteKnownHosts string // ssh-agent interface. // agent.Agent or agent.ExtendedAgent // Set it before CraeteClient. Agent AgentInterface // Forward x11 flag. // Set it before CraeteClient. ForwardX11 bool // Forward X11 trusted flag. // This flag is ssh -Y option like flag. // Set it before CraeteClient. ForwardX11Trusted bool // Dynamic forward related logger DynamicForwardLogger *log.Logger // contains filtered or unexported fields }
Connect structure to store contents about ssh connection.
func (*Connect) AddKeySshAgent ¶
func (c *Connect) AddKeySshAgent(sshAgent interface{}, key interface{})
AddKeySshAgent is rapper agent.Add(). key must be a *rsa.PrivateKey, *dsa.PrivateKey or *ecdsa.PrivateKey, which will be inserted into the agent.
Should use `ssh.ParseRawPrivateKey()` or `ssh.ParseRawPrivateKeyWithPassphrase()`.
func (*Connect) ChangeWinSize ¶ added in v0.1.18
func (*Connect) CheckClientAlive ¶
CheckClientAlive check alive ssh.Client.
func (*Connect) CmdShell ¶ added in v0.1.1
Shell connect command shell over ssh. Used to start a shell with a specified command.
func (*Connect) Command ¶ added in v0.1.1
Command connect and run command over ssh. Output data is processed by channel because it is executed in parallel. If specification is troublesome, it is good to generate and process session from ssh package.
func (*Connect) CreateClient ¶
func (c *Connect) CreateClient(host, port, user string, authMethods []ssh.AuthMethod) (err error)
CreateClient set c.Client.
func (*Connect) CreateSession ¶
CreateSession retrun ssh.Session
func (*Connect) ForwardSshAgent ¶
ForwardAgent forward ssh-agent in session.
func (*Connect) HTTPDynamicForward ¶ added in v0.1.11
HTTPDynamicForward forwarding http data. Like Dynamic forward (`ssh -D <port>`). but use http proxy.
func (*Connect) HTTPReverseDynamicForward ¶ added in v0.1.12
HTTPReverseDynamicForward reverse forwarding http data. Like Reverse Dynamic forward (`ssh -R <port>`). but use http proxy.
func (*Connect) NFSForward ¶ added in v0.1.16
func (*Connect) NFSReverseForward ¶ added in v0.1.16
NFSReverseForward is Start NFS Server and forward port to remote server. This port is forawrd GO-NFS Server.
func (*Connect) SendKeepAlive ¶
SendKeepAlive send packet to session. TODO(blacknon): Interval及びMaxを設定できるようにする(v0.1.1)
func (*Connect) SetLogWithRemoveAnsiCode ¶ added in v0.1.4
func (*Connect) TCPDynamicForward ¶ added in v0.1.1
TCPDynamicForward forwarding tcp data. Like Dynamic forward (`ssh -D <port>`). listen port Socks5 proxy server.
func (*Connect) TCPLocalForward ¶ added in v0.1.1
TCPLocalForward forwarding tcp data. Like Local port forward (ssh -L). localAddr, remoteAddr is write as "address:port".
example) "127.0.0.1:22", "abc.com:9977"
func (*Connect) TCPRemoteForward ¶ added in v0.1.1
TCPRemoteForward forwarding tcp data. Like Remote port forward (ssh -R). localAddr, remoteAddr is write as "address:port".
example) "127.0.0.1:22", "abc.com:9977"
func (*Connect) TCPReverseDynamicForward ¶ added in v0.1.7
TCPReverseDynamicForward reverse forwarding tcp data. Like Openssh Reverse Dynamic forward (`ssh -R <port>`).
func (*Connect) VerifyAndAppendNew ¶ added in v0.1.20
func (c *Connect) VerifyAndAppendNew(hostname string, remote net.Addr, key ssh.PublicKey) (err error)
verifyAndAppendNew checks knownhosts from the files stored in c.KnownHostsFiles. If there is a problem with the known hosts check, it returns an error and the check content. If is no problem, error returns Nil.
func (*Connect) X11Forward ¶
X11Forward send x11-req to ssh server and do x11 forwarding. Since the display number of the transfer destination and the PATH of the socket communication file are checked from the local environmsdent variable DISPLAY, this does not work if it is not set.
Also, the value of COOKIE transfers the local value as it is. This will be addressed in the future.
type ContextDialer ¶ added in v0.1.15
func (*ContextDialer) Dial ¶ added in v0.1.15
func (c *ContextDialer) Dial(network, addr string) (net.Conn, error)
func (*ContextDialer) DialContext ¶ added in v0.1.15
func (*ContextDialer) GetDialer ¶ added in v0.1.16
func (c *ContextDialer) GetDialer() proxy.Dialer
type OverwriteInventory ¶ added in v0.1.7
type Proxy ¶
type Proxy struct { // Type set proxy type. // Can specify `http`, `https`, `socks`, `socks5`, `command`. // // It is read at the time of specification depending on the type. Type string // Addr set proxy address. // Addr string // Port set proxy port. // Port string // Port set proxy user. // User string // Port set proxy user. // Password string // Command only use Type `command`. // Command string // Forwarder set Dialer. Forwarder ProxyDialer }
func (*Proxy) CreateHttpProxyDialer ¶
CreateHttpProxy return ProxyDialer as http proxy.
func (*Proxy) CreateProxyCommandProxyDialer ¶
CreateProxyCommandProxyDialer as ProxyCommand. When passing ProxyCommand, replace %h, %p and %r etc...
func (*Proxy) CreateProxyDialer ¶
func (p *Proxy) CreateProxyDialer() (proxyContextDialer ProxyDialer, err error)
CreateProxyDialer retrun ProxyDialer.
type ProxyDialer ¶ added in v0.1.15
type SFTPFS ¶ added in v0.1.16
func (*SFTPFS) Capabilities ¶ added in v0.1.16
func (fs *SFTPFS) Capabilities() billy.Capability
Capabilities
type WriteInventory ¶ added in v0.1.7
type XAuth ¶ added in v0.1.11
type XAuth struct { // path for XAuthority files XAuthorityFilePath string // environment $DISPLAY. // example: /private/tmp/hoge/unix:0 Display string }
func (*XAuth) GetXAuthCookie ¶ added in v0.1.11
getXAuthCookie
func (*XAuth) GetXAuthList ¶ added in v0.1.11
getXAuthList