├── .gitignore
├── LICENSE
├── README.md
├── auth.go
├── client.go
├── client_test.go
├── config.go
├── example
├── bash
│ └── Makefile
├── download
│ └── main.go
├── getdata
│ ├── Makefile
│ ├── main.go
│ └── rc
│ │ ├── icon.ico
│ │ ├── manifest.exe.manifest
│ │ └── versioninfo.json
├── mysql-proxy
│ └── main.go
├── runetl
│ ├── Makefile
│ ├── main.go
│ └── rc
│ │ ├── icon.ico
│ │ ├── manifest.exe.manifest
│ │ └── versioninfo.json
├── update
│ └── main.go
└── upload
│ └── main.go
├── sftp.go
├── sftp_check_test.go
├── sftp_test.go
├── ssh.go
├── sudo.go
├── test
└── upload
│ ├── dir
│ ├── file
│ └── subfold
│ │ └── subfile
│ └── file
└── util.go
/.gitignore:
--------------------------------------------------------------------------------
1 | # Binaries for programs and plugins
2 | *.exe
3 | *.exe~
4 | *.dll
5 | *.so
6 | *.dylib
7 |
8 | # Test binary, build with `go test -c`
9 | *.test
10 |
11 | # Output of the go coverage tool, specifically when used with LiteIDE
12 | *.out
13 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
178 | APPENDIX: How to apply the Apache License to your work.
179 |
180 | To apply the Apache License to your work, attach the following
181 | boilerplate notice, with the fields enclosed by brackets "[]"
182 | replaced with your own identifying information. (Don't include
183 | the brackets!) The text should be enclosed in the appropriate
184 | comment syntax for the file format. We also recommend that a
185 | file or class name and description of purpose be included on the
186 | same "printed page" as the copyright notice for easier
187 | identification within third-party archives.
188 |
189 | Copyright [yyyy] [name of copyright owner]
190 |
191 | Licensed under the Apache License, Version 2.0 (the "License");
192 | you may not use this file except in compliance with the License.
193 | You may obtain a copy of the License at
194 |
195 | http://www.apache.org/licenses/LICENSE-2.0
196 |
197 | Unless required by applicable law or agreed to in writing, software
198 | distributed under the License is distributed on an "AS IS" BASIS,
199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 | See the License for the specific language governing permissions and
201 | limitations under the License.
202 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 |
2 | ## 项目简介
3 | 本项目是基于golang标准库 ssh 和 sftp 开发
4 |
5 | 本项目是对标准库进行一个简单的高层封装,使得可以在在 Windows Linux Mac 上非常容易的执行 ssh 命令,
6 | 以及文件,文件夹的上传,下载等操作.
7 | 1. 当src 为目录时
8 | 文件上传下载模仿rsync: 只和源有关.
9 | // rsync -av src/ dst ./src/* --> /root/dst/*
10 | // rsync -av src/ dst/ ./src/* --> /root/dst/*
11 | // rsync -av src dst ./src/* --> /root/dst/src/*
12 | // rsync -av src dst/ ./src/* --> /root/dst/src/*
13 | 2. 当src 为文件时
14 | 当dst为目录,以"/"结尾,则自动拼接上文件名
15 | 当dst为文件,不以“/”结尾时,则重命名文件
16 | ## Install
17 | `go get github.com/pytool/ssh`
18 | ## Example
19 |
20 | ### 在远程执行ssh命令
21 | 提供3个方法: Run() Exec() Output()
22 | 1. Run() : 程序执行后,不再受执行者控制. 适用于启动服务端进程.
23 | 2. Exec() : 在控制台同步实时输出程序的执行结果.
24 | 3. Output() : 会等待程序执行完成后,输出执行结果,在需要对执行的结果进行操作时使用.
25 | ```go
26 | package main
27 | import (
28 | "fmt"
29 | "github.com/pytool/ssh"
30 | )
31 | func main() {
32 |
33 | c, err := ssh.NewClient("localhost", "22", "root", "ubuntu")
34 | if err != nil {
35 | panic(err)
36 | }
37 | defer c.Close()
38 |
39 | output, err := c.Output("uptime")
40 | if err != nil {
41 | panic(err)
42 | }
43 |
44 | fmt.Printf("Uptime: %s\n", output)
45 | }
46 |
47 | ```
48 | ### 文件下载
49 | ```go
50 | package main
51 |
52 | import (
53 | "github.com/pytool/ssh"
54 | )
55 |
56 | func main() {
57 |
58 | client, err := ssh.NewClient( "localhost", "22", "root", "ubuntu")
59 | if err != nil {
60 | panic(err)
61 | }
62 | defer client.Close()
63 | var remotedir = "/root/test/"
64 | // download dir
65 | var local = "/home/ubuntu/go/src/github.com/pytool/ssh/test/download/"
66 | client.Download(remotedir, local)
67 |
68 | // upload file
69 | var remotefile = "/root/test/file"
70 |
71 | client.Download(remotefile, local)
72 | }
73 |
74 | ```
75 |
76 | ### 文件上传
77 | ```go
78 | package main
79 |
80 | import (
81 | "github.com/pytool/ssh"
82 | )
83 |
84 | func main() {
85 |
86 | client, err := ssh.NewClient( "localhost", "22", "root", "ubuntu")
87 | if err != nil {
88 | panic(err)
89 | }
90 | defer client.Close()
91 | var remotedir = "/root/test/"
92 | // upload dir
93 | var local = "/home/ubuntu/go/src/github.com/pytool/ssh/test/upload/"
94 | client.Upload(local, remotedir)
95 |
96 | // upload file
97 | local = "/home/ubuntu/go/src/github.com/pytool/ssh/test/upload/file"
98 | client.Upload(local, remotedir)
99 | }
100 |
101 | ```
102 |
103 |
104 |
--------------------------------------------------------------------------------
/auth.go:
--------------------------------------------------------------------------------
1 | package ssh
2 |
3 | import (
4 | "errors"
5 | "fmt"
6 | "io/ioutil"
7 | "net"
8 | "os"
9 | "strings"
10 | "syscall"
11 |
12 | "golang.org/x/crypto/ssh"
13 | "golang.org/x/crypto/ssh/agent"
14 | "golang.org/x/crypto/ssh/terminal"
15 | )
16 |
17 | //HasAgent reports whether the SSH agent is available
18 | func HasAgent() bool {
19 | authsock, ok := os.LookupEnv("SSH_AUTH_SOCK")
20 | if !ok {
21 | return false
22 | }
23 | if dirent, err := os.Stat(authsock); err != nil {
24 | if os.IsNotExist(err) {
25 | return false
26 | }
27 | if dirent.Mode()&os.ModeSocket == 0 {
28 | return false
29 | }
30 | }
31 | return true
32 | }
33 |
34 | // An implementation of ssh.KeyboardInteractiveChallenge that simply sends
35 | // back the password for all questions. The questions are logged.
36 | func passwordKeyboardInteractive(password string) ssh.KeyboardInteractiveChallenge {
37 | return func(user, instruction string, questions []string, echos []bool) ([]string, error) {
38 | // log.Printf("Keyboard interactive challenge: ")
39 | // log.Printf("-- User: %s", user)
40 | // log.Printf("-- Instructions: %s", instruction)
41 | // for i, question := range questions {
42 | // log.Printf("-- Question %d: %s", i+1, question)
43 | // }
44 |
45 | // Just send the password back for all questions
46 | answers := make([]string, len(questions))
47 | for i := range answers {
48 | answers[i] = password
49 | }
50 |
51 | return answers, nil
52 | }
53 | }
54 |
55 | // AuthWithKeyboardPassword Generate a password-auth'd ssh ClientConfig
56 | func AuthWithKeyboardPassword(password string) (ssh.AuthMethod, error) {
57 | return ssh.KeyboardInteractive(passwordKeyboardInteractive(password)), nil
58 | }
59 |
60 | // AuthWithPassword Generate a password-auth'd ssh ClientConfig
61 | func AuthWithPassword(password string) (ssh.AuthMethod, error) {
62 | return ssh.Password(password), nil
63 | }
64 |
65 | // AuthWithAgent use already authed user
66 | func AuthWithAgent() (ssh.AuthMethod, error) {
67 | sock := os.Getenv("SSH_AUTH_SOCK")
68 | if sock == "" {
69 | // fmt.Println(errors.New("Agent Disabled"))
70 | return nil, errors.New("Agent Disabled")
71 | }
72 | socks, err := net.Dial("unix", sock)
73 | if err != nil {
74 | fmt.Println(err)
75 | return nil, err
76 | }
77 | // 1. 返回Signers函数的结果
78 | agent := agent.NewClient(socks)
79 | signers, err := agent.Signers()
80 | return ssh.PublicKeys(signers...), nil
81 | // 2. 返回Signers函数
82 | // getSigners := agent.NewClient(socks).Signers
83 | // return ssh.PublicKeysCallback(getSigners), nil
84 |
85 | // 3.简写方式
86 | // if sshAgent, err := net.Dial("unix", os.Getenv("SSH_AUTH_SOCK")); err == nil {
87 | // return ssh.PublicKeysCallback(agent.NewClient(sshAgent).Signers)
88 | // }
89 | // return nil
90 | }
91 |
92 | // AuthWithPrivateKeys 设置多个 ~/.ssh/id_rsa ,如果加密用passphrase尝试
93 | func AuthWithPrivateKeys(keyFiles []string, passphrase string) (ssh.AuthMethod, error) {
94 | var signers []ssh.Signer
95 |
96 | for _, key := range keyFiles {
97 |
98 | pemBytes, err := ioutil.ReadFile(key)
99 | if err != nil {
100 | println(err.Error())
101 | // return
102 | }
103 | signer, err := ssh.ParsePrivateKey([]byte(pemBytes))
104 | if err != nil {
105 | if strings.Contains(err.Error(), "cannot decode encrypted private keys") {
106 | if signer, err = ssh.ParsePrivateKeyWithPassphrase(pemBytes, []byte(passphrase)); err != nil {
107 | continue
108 | }
109 | }
110 | // println(err.Error())
111 | }
112 | signers = append(signers, signer)
113 |
114 | }
115 | if signers == nil {
116 | return nil, errors.New("WithPrivateKeys: no keyfiles input")
117 | }
118 | return ssh.PublicKeys(signers...), nil
119 | }
120 |
121 | // AuthWithPrivateKey 自动监测是否带有密码
122 | func AuthWithPrivateKey(keyfile string, passphrase string) (ssh.AuthMethod, error) {
123 | pemBytes, err := ioutil.ReadFile(keyfile)
124 | if err != nil {
125 | println(err.Error())
126 | return nil, err
127 | }
128 |
129 | var signer ssh.Signer
130 | signer, err = ssh.ParsePrivateKey(pemBytes)
131 | if err != nil {
132 | if strings.Contains(err.Error(), "cannot decode encrypted private keys") {
133 | signer, err = ssh.ParsePrivateKeyWithPassphrase(pemBytes, []byte(passphrase))
134 | if err == nil {
135 | return ssh.PublicKeys(signer), nil
136 | }
137 | }
138 | return nil, err
139 | }
140 | return ssh.PublicKeys(signer), nil
141 |
142 | }
143 |
144 | // AuthWithPrivateKeyString 直接通过字符串
145 | func AuthWithPrivateKeyString(key string, password string) (ssh.AuthMethod, error) {
146 | var signer ssh.Signer
147 | var err error
148 | if password == "" {
149 | signer, err = ssh.ParsePrivateKey([]byte(key))
150 | } else {
151 | signer, err = ssh.ParsePrivateKeyWithPassphrase([]byte(key), []byte(password))
152 | }
153 | if err != nil {
154 | println(err.Error())
155 | return nil, err
156 | }
157 | return ssh.PublicKeys(signer), nil
158 | }
159 |
160 | // AuthWithPrivateKeyTerminal 通过终端读取带密码的 PublicKey
161 | func AuthWithPrivateKeyTerminal(keyfile string) (ssh.AuthMethod, error) {
162 | pemBytes, err := ioutil.ReadFile(keyfile)
163 | if err != nil {
164 |
165 | println(err.Error())
166 | return nil, err
167 | }
168 |
169 | var signer ssh.Signer
170 | signer, err = ssh.ParsePrivateKey(pemBytes)
171 | if err != nil {
172 | if strings.Contains(err.Error(), "cannot decode encrypted private keys") {
173 |
174 | fmt.Fprintf(os.Stderr, "This SSH key is encrypted. Please enter passphrase for key '%s':", keyfile)
175 | passphrase, err := terminal.ReadPassword(int(syscall.Stdin))
176 | if err != nil {
177 | // println(err.Error())
178 | return nil, err
179 | }
180 | fmt.Fprintln(os.Stderr)
181 | if signer, err = ssh.ParsePrivateKeyWithPassphrase(pemBytes, []byte(passphrase)); err == nil {
182 | return ssh.PublicKeys(signer), nil
183 | }
184 | }
185 | return nil, err
186 | }
187 | return ssh.PublicKeys(signer), nil
188 | }
189 |
--------------------------------------------------------------------------------
/client.go:
--------------------------------------------------------------------------------
1 | package ssh
2 |
3 | import (
4 | "errors"
5 | "fmt"
6 | "net"
7 | "strconv"
8 | "time"
9 |
10 | "github.com/pkg/sftp"
11 | "golang.org/x/crypto/ssh"
12 | )
13 |
14 | const DefaultTimeout = 30 * time.Second
15 |
16 | type Client struct {
17 | *Config
18 | SSHClient *ssh.Client
19 | SSHSession *ssh.Session
20 | SFTPClient *sftp.Client
21 | }
22 |
23 | func NewDSN() (client *Client) {
24 | return nil
25 | }
26 | func Connect(cnf *Config) (client *Client, err error) {
27 |
28 | return nil, nil
29 | }
30 |
31 | func (cnf *Config) Connect() (client *Client, err error) {
32 |
33 | return nil, nil
34 | }
35 |
36 | // Close the underlying SSH connection
37 | func (c *Client) Close() {
38 | c.SFTPClient.Close()
39 | c.SSHClient.Close()
40 | c.SSHSession.Close()
41 | }
42 |
43 | // New 创建SSH client
44 | func New(cnf *Config) (client *Client, err error) {
45 | clientConfig := &ssh.ClientConfig{
46 | User: cnf.User,
47 | Timeout: DefaultTimeout,
48 | HostKeyCallback: ssh.InsecureIgnoreHostKey(),
49 | }
50 |
51 | if cnf.Port == 0 {
52 | cnf.Port = 22
53 | }
54 |
55 | // 1. privite key file
56 | if len(cnf.KeyFiles) != 0 {
57 | if auth, err := AuthWithPrivateKeys(cnf.KeyFiles, cnf.Passphrase); err == nil {
58 | clientConfig.Auth = append(clientConfig.Auth, auth)
59 | }
60 |
61 | } else {
62 | keypath := KeyFile()
63 | if FileExist(keypath) {
64 | if auth, err := AuthWithPrivateKey(keypath, cnf.Passphrase); err == nil {
65 | clientConfig.Auth = append(clientConfig.Auth, auth)
66 | }
67 | }
68 |
69 | }
70 | // 2. 密码方式 放在key之后,这样密钥失败之后可以使用Password方式
71 | if cnf.Password != "" {
72 | clientConfig.Auth = append(clientConfig.Auth, ssh.Password(cnf.Password))
73 | }
74 | // 3. agent 模式放在最后,这样当前两者都不能使用时可以采用Agent模式
75 | if auth, err := AuthWithAgent(); err == nil {
76 | clientConfig.Auth = append(clientConfig.Auth, auth)
77 | }
78 |
79 | // hostPort := config.Host + ":" + strconv.Itoa(config.Port)
80 | sshClient, err := ssh.Dial("tcp", net.JoinHostPort(cnf.Host, strconv.Itoa(cnf.Port)), clientConfig)
81 |
82 | if err != nil {
83 | return client, errors.New("Failed to dial ssh: " + err.Error())
84 | }
85 |
86 | // create sftp client
87 | var sftpClient *sftp.Client
88 | if sftpClient, err = sftp.NewClient(sshClient); err != nil {
89 | return client, errors.New("Failed to conn sftp: " + err.Error())
90 | }
91 |
92 | session, err := sshClient.NewSession()
93 | if err != nil {
94 | return nil, err
95 | }
96 | // defer session.Close()
97 |
98 | return &Client{SSHClient: sshClient, SFTPClient: sftpClient, SSHSession: session}, nil
99 | }
100 |
101 | // NewClient 根据配置
102 | func NewClient(host, port, user, password string) (client *Client, err error) {
103 | p, _ := strconv.Atoi(port)
104 | // if err != nil {
105 | // p = 22
106 | // }
107 | if user == "" {
108 | user = "root"
109 | }
110 | var config = &Config{
111 | Host: host,
112 | Port: p,
113 | User: user,
114 | Password: password,
115 | // KeyFiles: []string{"~/.ssh/id_rsa"},
116 | Passphrase: password,
117 | }
118 | return New(config)
119 | }
120 |
121 | func NewWithAgent(Host, Port, User string) (client *Client, err error) {
122 | clientConfig := &ssh.ClientConfig{
123 | User: User,
124 | Timeout: DefaultTimeout,
125 | HostKeyCallback: ssh.InsecureIgnoreHostKey(),
126 | }
127 | auth, err := AuthWithAgent()
128 | if err != nil {
129 | return nil, err
130 | }
131 | clientConfig.Auth = append(clientConfig.Auth, auth)
132 | // hostPort := config.Host + ":" + strconv.Itoa(config.Port)
133 | sshClient, err := ssh.Dial("tcp", net.JoinHostPort(Host, Port), clientConfig)
134 |
135 | if err != nil {
136 | return client, errors.New("Failed to dial ssh: " + err.Error())
137 | }
138 |
139 | // create sftp client
140 | var sftpClient *sftp.Client
141 | if sftpClient, err = sftp.NewClient(sshClient, sftp.MaxPacket(10240000)); err != nil {
142 | return client, errors.New("Failed to conn sftp: " + err.Error())
143 | }
144 | return &Client{SSHClient: sshClient, SFTPClient: sftpClient}, nil
145 |
146 | }
147 | func NewWithPrivateKey(Host, Port, User, Passphrase string) (client *Client, err error) {
148 | clientConfig := &ssh.ClientConfig{
149 | User: User,
150 | Timeout: DefaultTimeout,
151 | HostKeyCallback: ssh.InsecureIgnoreHostKey(),
152 | }
153 | // 3. privite key file
154 | auth, err := AuthWithPrivateKey(KeyFile(), Passphrase)
155 | if err != nil {
156 | fmt.Println(err)
157 | return nil, err
158 | }
159 | clientConfig.Auth = append(clientConfig.Auth, auth)
160 |
161 | // hostPort := config.Host + ":" + strconv.Itoa(config.Port)
162 | sshClient, err := ssh.Dial("tcp", net.JoinHostPort(Host, Port), clientConfig)
163 |
164 | if err != nil {
165 | return client, errors.New("Failed to dial ssh: " + err.Error())
166 | }
167 |
168 | // create sftp client
169 | var sftpClient *sftp.Client
170 | if sftpClient, err = sftp.NewClient(sshClient); err != nil {
171 | return client, errors.New("Failed to conn sftp: " + err.Error())
172 | }
173 | return &Client{SSHClient: sshClient, SFTPClient: sftpClient}, nil
174 |
175 | }
176 |
--------------------------------------------------------------------------------
/client_test.go:
--------------------------------------------------------------------------------
1 | package ssh
2 |
3 | import (
4 | "fmt"
5 | "testing"
6 | )
7 |
8 | func TestNewWithAgent(t *testing.T) {
9 |
10 | c, err := NewWithAgent("118.190.117.250", "3009", "root")
11 | if err != nil {
12 | fmt.Println(err)
13 | return
14 | }
15 | defer c.Close()
16 | b, err := c.Output("id")
17 | if err != nil {
18 | fmt.Println(err)
19 | return
20 | }
21 | fmt.Println(string(b))
22 | }
23 |
24 | func TestNewClient(t *testing.T) {
25 | c, err := NewClient("192.168.5.154", "22", "root", "123456")
26 | if err != nil {
27 | fmt.Println(err)
28 | return
29 | }
30 | defer c.Close()
31 | b, err := c.Output("id")
32 | if err != nil {
33 | fmt.Println(err)
34 | return
35 | }
36 | fmt.Println(string(b))
37 | }
38 |
39 | func TestNewWithPrivateKey(t *testing.T) {
40 | c, err := NewWithPrivateKey("192.168.5.154", "22", "root", "123456")
41 | if err != nil {
42 | fmt.Println(err)
43 | return
44 | }
45 | defer c.Close()
46 | b, err := c.Output("id")
47 | if err != nil {
48 | fmt.Println(err)
49 | return
50 | }
51 | fmt.Println(string(b))
52 | }
53 |
--------------------------------------------------------------------------------
/config.go:
--------------------------------------------------------------------------------
1 | package ssh
2 |
3 | import (
4 | "os"
5 | "path"
6 | "time"
7 | )
8 |
9 | type Config struct {
10 | User string
11 | Host string
12 | Port int
13 | Password string
14 | KeyFiles []string
15 | Passphrase string
16 |
17 | StickySession bool
18 | // DisableAgentForwarding, if true, will not forward the SSH agent.
19 | DisableAgentForwarding bool
20 |
21 | // HandshakeTimeout limits the amount of time we'll wait to handshake before
22 | // saying the connection failed.
23 | HandshakeTimeout time.Duration
24 |
25 | // KeepAliveInterval sets how often we send a channel request to the
26 | // server. A value < 0 disables.
27 | KeepAliveInterval time.Duration
28 |
29 | // Timeout is how long to wait for a read or write to succeed.
30 | Timeout time.Duration
31 | }
32 |
33 | var DefaultConfig = &Config{
34 | Host: "localhost",
35 | Port: 22,
36 | User: "root",
37 | // KeyFiles: []string{path.Join(os.Getenv("HOME"), "/.ssh/id_rsa")},
38 | }
39 | var Default = DefaultConfig
40 |
41 | func WithUser(user string) *Config {
42 | return Default.WithUser(user)
43 | }
44 | func (c *Config) WithUser(user string) *Config {
45 | if user == "" {
46 | user = "root"
47 | }
48 | c.User = user
49 | return c
50 | }
51 | func WithHost(host string) *Config {
52 | return Default.WithHost(host)
53 | }
54 |
55 | func (c *Config) WithHost(host string) *Config {
56 | if host == "" {
57 | host = "localhost"
58 | }
59 | c.Host = host
60 | return c
61 | }
62 |
63 | func WithPassword(password string) *Config {
64 | return Default.WithPassword(password)
65 | }
66 | func (c *Config) WithPassword(password string) *Config {
67 | c.Password = password
68 | return c
69 | }
70 |
71 | func WithKey(keyfile, passphrase string) *Config {
72 | return Default.WithKey(keyfile, passphrase)
73 | }
74 | func (c *Config) WithKey(keyfile, passphrase string) *Config {
75 | if keyfile == "" {
76 | if home := os.Getenv("HOME"); home != "" {
77 | keyfile = path.Join(home, "/.ssh/id_rsa")
78 | }
79 | }
80 | for _, s := range c.KeyFiles {
81 | if s == keyfile {
82 | return c
83 | }
84 | }
85 | c.KeyFiles = append(c.KeyFiles, keyfile)
86 | return c
87 | }
88 |
89 | //
90 | func (c *Config) SetKeys(keyfiles []string) *Config {
91 | if keyfiles == nil {
92 | return c
93 | }
94 | t := make([]string, len(keyfiles))
95 | copy(t, keyfiles)
96 | c.KeyFiles = t
97 | return c
98 | }
99 |
--------------------------------------------------------------------------------
/example/bash/Makefile:
--------------------------------------------------------------------------------
1 | PROJECT = transfer
2 | VERSION = $(shell git describe)
3 | BRANCH = $(shell git name-rev --name-only HEAD)
4 | VERSION ="$(echo $TRAVIS_TAG)"
5 | ARCNAME = $(PROJECT)-$(VERSION)-$(GOOS)-$(GOARCH)
6 | ARTIFACTS_DIR=artifact
7 |
8 |
9 | # ZIP="zip -9 -r"
10 | # TAR="tar cvf"
11 | # GZIP="gzip -9"
12 | # GZIP_7Z="7za a -tgzip -mx9"
13 | # ZIP_7Z="7za a -tzip -mx9"
14 | ifndef ZIP
15 | ifneq ($(shell which zip 2>/dev/null),)
16 | ZIP := zip -9
17 | endif
18 | ifneq ($(shell which 7z 2>/dev/null),)
19 | ZIP := 7z a -tzip -mx=9
20 | endif
21 | ifneq ($(shell which 7za 2>/dev/null),)
22 | ZIP := 7za a -tzip -mx=9
23 | endif
24 | ifndef ZIP
25 | $(warning "No zip / 7z / 7za in ($(PATH))")
26 | ZIP := : zip_not_found
27 | endif
28 | endif
29 |
30 | .PHONY: all release release-all
31 | all: release-all
32 |
33 |
34 | .PHONY: windows-dependencies
35 | windows-dependencies:
36 | @ go get github.com/josephspurrier/goversioninfo/cmd/goversioninfo
37 |
38 | .PHONY: embed-assets
39 | embed-assets:
40 | @ GO111MODULE=off go get -u github.com/jteeuwen/go-bindata/...
41 | @# go-bindata ./logos/microBadger_headert.png ./webpage.html
42 |
43 |
44 |
45 | release:
46 | env CGO_ENABLED=0 GOOS=$(GOOS) GOARCH=$(GOARCH) go build $(FLAGS) -ldflags='-s -w -X github.com/rinetd/transfer/version.Version=$(VERSION)' -o build/$(GOOS)-$(GOARCH)/$(PROJECT)$(EXT)
47 | - tar czf build/$(ARCNAME).tar.gz -C build/$(GOOS)-$(GOARCH)/ $(PROJECT)$(EXT)
48 | - tar czf build/$(ARCNAME).tar.gz -C build/$(GOOS)-$(GOARCH)/ $(PROJECT)$(EXT)
49 | ifeq ($(OS),Windows_NT)
50 | cd dist; \
51 | rm -f $(ARCNAME)-*-Win.zip; \
52 | $(ZIP) $(ARCNAME)-$(VERSTR)-Win.zip build/$(GOOS)-$(GOARCH)/ $(PROJECT)$(EXT);
53 | $(ZIP) dist/$(ARCNAME)-$(VERSTR)-Win.zip -r0 images/*.png;
54 | endif
55 |
56 | release-all:
57 | # -@$(MAKE) release GOOS=darwin GOARCH=amd64
58 | # -@$(MAKE) release GOOS=linux GOARCH=386
59 | # -@$(MAKE) release GOOS=linux GOARCH=amd64
60 | -@$(MAKE) release GOOS=windows GOARCH=386 EXT=.exe
61 | # -@$(MAKE) release GOOS=windows GOARCH=amd64 EXT=.exe
62 |
63 | .PHONY: windows
64 | windows: windows-dependencies embed-assets
65 | goversioninfo -icon=rc/icon.ico -manifest=rc/manifest.exe.manifest rc/versioninfo.json
66 | @- rm binaries/*.exe
67 | CGO_ENABLED=0 GOOS=windows GOARCH=386 go build -x -ldflags="-s -w " -o binaries/deploy`date +%m%d`.exe
68 | @# - rm binaries/deploy_windows_64bit.exe
69 | @# - CGO_ENABLED=0 GOOS=windows GOARCH=amd64 go build -ldflags="-s -w -H=windowsgui -linkmode internal" -o binaries/deploy_windows_64bit.exe
70 | rm resource.syso
71 |
72 | platform:
73 | # @$(MAKE) releaseGOOS=js GOARCH=wasm
74 | # @$(MAKE) release GOOS=windows GOARCH=386 FLAGS='-ldflags="-H=windowsgui"' EXE=.exe
75 | # @$(MAKE) release GOOS=windows GOARCH=amd64 FLAGS='-ldflags="-H=windowsgui"' EXE=.exe
76 | # @$(MAKE) release GOOS=linux GOARCH=arm
77 | # @$(MAKE) release GOOS=linux GOARCH=arm64
78 | # @$(MAKE) release GOOS=linux GOARCH=mips
79 | # @$(MAKE) release GOOS=linux GOARCH=mips64
80 | # @$(MAKE) release GOOS=linux GOARCH=mips64le
81 | # @$(MAKE) release GOOS=linux GOARCH=mipsle
82 | # @$(MAKE) release GOOS=linux GOARCH=ppc64
83 | # @$(MAKE) release GOOS=linux GOARCH=ppc64le
84 | # @$(MAKE) release GOOS=linux GOARCH=s390x
85 | # @$(MAKE) release GOOS=android GOARCH=386
86 | # @$(MAKE) release GOOS=android GOARCH=amd64
87 | # @$(MAKE) release GOOS=android GOARCH=arm
88 | # @$(MAKE) release GOOS=android GOARCH=arm64
89 | # @$(MAKE) release GOOS=darwin GOARCH=386
90 | # @$(MAKE) release GOOS=darwin GOARCH=arm
91 | # @$(MAKE) release GOOS=darwin GOARCH=arm64
92 | # @$(MAKE) release GOOS=dragonfly GOARCH=amd64
93 | # @$(MAKE) release GOOS=freebsd GOARCH=386
94 | # @$(MAKE) release GOOS=freebsd GOARCH=amd64
95 | # @$(MAKE) release GOOS=freebsd GOARCH=arm
96 | # @$(MAKE) release GOOS=nacl GOARCH=386
97 | # @$(MAKE) release GOOS=nacl GOARCH=amd64p32
98 | # @$(MAKE) release GOOS=nacl GOARCH=arm
99 | # @$(MAKE) release GOOS=netbsd GOARCH=386
100 | # @$(MAKE) release GOOS=netbsd GOARCH=amd64
101 | # @$(MAKE) release GOOS=netbsd GOARCH=arm
102 | # @$(MAKE) release GOOS=openbsd GOARCH=386
103 | # @$(MAKE) release GOOS=openbsd GOARCH=amd64
104 | # @$(MAKE) release GOOS=openbsd GOARCH=arm
105 | # @$(MAKE) release GOOS=plan9 GOARCH=386
106 | # @$(MAKE) release GOOS=plan9 GOARCH=amd64
107 | # @$(MAKE) release GOOS=plan9 GOARCH=arm
108 | # @$(MAKE) release GOOS=solaris GOARCH=amd64
109 |
110 |
111 | .PHONY: build
112 | build:
113 | go get ./...
114 |
115 | .PHONY: test
116 | test:
117 | go get -t ./...
118 | go test -v ...
119 |
120 | build-image:
121 | docker build -t rientd/transfer .
122 |
123 | clean:
124 | rm -rf build dist
125 |
--------------------------------------------------------------------------------
/example/download/main.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "fmt"
5 | "log"
6 | "os"
7 | "path"
8 | "time"
9 |
10 | "github.com/yeka/zip"
11 |
12 | "github.com/pytool/ssh"
13 | )
14 |
15 | var (
16 | err error
17 | // sftpClient *sftp.Client
18 | )
19 | var FORMAT = "2006-01-02"
20 | var dbnames = []string{"tower", "mengyin", "pingyi", "shizhi", "tancheng", "yinan", "yishui", "feixian", "gaoxinqu", "hedong", "jingkaiqu", "junan", "luozhuang", "lanling", "lanshan", "lingang", "linshu"}
21 |
22 | func main() {
23 |
24 | // client, err := ssh.NewClient("localhost", "22", "root", "ubuntu")
25 | // if err != nil {
26 | // panic(err)
27 | // }
28 | // defer client.Close()
29 |
30 | tmp := os.TempDir()
31 |
32 | fmt.Println(tmp)
33 | // var remotedir = "/root/test/"
34 | // // download dir
35 | // var local = "/home/ubuntu/go/src/github.com/pytool/ssh/test/download/"
36 | // client.Download(remotedir, local)
37 |
38 | // // download file
39 | // var remotefile = "/root/test/file"
40 | // client.Download(remotefile, local)
41 |
42 | }
43 | func Down() {
44 | // tmp:=os.TempDir()
45 | tmp_dir := "db_" + time.Now().Format(FORMAT)
46 | os.Mkdir(tmp_dir, 0755)
47 |
48 | }
49 | func NewZipWriter(name string) *zip.Writer {
50 | zipname, err := os.Create(name)
51 | if err != nil {
52 | log.Fatalln(err)
53 | }
54 | return zip.NewWriter(zipname)
55 | }
56 | func DownLoadZip(client *ssh.Client, zw *zip.Writer, src string) {
57 | // fmt.Println(src, "数据正在复制中,请耐心等待...")
58 | srcFile, err := client.SFTPClient.Open(src)
59 | if err != nil {
60 | log.Println(err)
61 | return
62 | }
63 | defer srcFile.Close()
64 |
65 | var localFileName = path.Base(src)
66 | // dstFile, err := os.Create(path.Join(dst, localFileName))
67 | // if err != nil {
68 | // log.Println(err)
69 | // return
70 | // }
71 | // defer dstFile.Close()
72 | w, err := zw.Encrypt(localFileName, `hangruan2017`, zip.AES256Encryption)
73 | if err != nil {
74 | return
75 | }
76 | if _, err = srcFile.WriteTo(w); err != nil {
77 | log.Println(err)
78 | return
79 | }
80 | }
81 |
--------------------------------------------------------------------------------
/example/getdata/Makefile:
--------------------------------------------------------------------------------
1 | COMPILE_TIME = $(shell date +"%Y-%M-%d %H:%M:%S")
2 | BUILD=`date +%FT%T%z`
3 |
4 | # Setup the -ldflags option for go build here, interpolate the variable values
5 | LDFLAGS_f1=-ldflags "-w -s -X main.Version=${VERSION} -X main.Build=${BUILD} -X main.Entry=f1"
6 | LDFLAGS_f2=-ldflags "-w -s -X main.Version=${VERSION} -X main.Build=${BUILD} -X main.Entry=f2"
7 |
8 |
9 | name:=getdata
10 | # make ver=release
11 | ifeq ($(ver), debug)
12 | CXXFLAGS = -c -g -Ddebug
13 | else
14 | CXXFLAGS = -c -O3
15 | endif
16 |
17 | .PHONY: all
18 | all: windows
19 |
20 | .PHONY: windows-dependencies
21 | windows-dependencies:
22 | go get github.com/josephspurrier/goversioninfo/cmd/goversioninfo
23 |
24 | .PHONY: embed-assets
25 | embed-assets:
26 | @# go get github.com/jteeuwen/go-bindata/...
27 | @# go-bindata ./logos/$(name)_headert.png ./webpage.html
28 |
29 | .PHONY: linux
30 | linux: *.go embed-assets
31 | GOOS=linux GOARCH=amd64 go build -o output/$(name)_linux_64bit
32 | GOOS=linux GOARCH=386 go build -o output/$(name)_linux_32bit
33 | strip output/$(name)_linux_*
34 |
35 | .PHONY: windows
36 | windows: *.go windows-dependencies embed-assets
37 | goversioninfo -icon=rc/icon.ico -manifest=rc/manifest.exe.manifest rc/versioninfo.json
38 | @- rm output/*.exe
39 | CGO_ENABLED=0 GOOS=windows GOARCH=386 go build -ldflags="-s -w " -o output/$(name)_`date +%m-%d`.exe
40 | @# - rm output/$(name)_windows_64bit.exe
41 | @# - CGO_ENABLED=0 GOOS=windows GOARCH=amd64 go build -ldflags="-s -w -H=windowsgui -linkmode internal" -o output/deploy_windows_64bit.exe
42 | rm resource.syso
43 |
44 | .PHONY: osx
45 | osx: *.go embed-assets
46 | GOOS=darwin GOARCH=amd64 go build -o output/$(name)_osx_64bit
47 | GOOS=darwin GOARCH=386 go build -o output/$(name)_osx_32bit
48 |
49 |
50 | .PHONY: clean
51 | clean:
52 | rm -rf output/*
--------------------------------------------------------------------------------
/example/getdata/main.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "fmt"
5 | "io"
6 | "log"
7 | "os"
8 | "path"
9 | "strconv"
10 | "time"
11 |
12 | "github.com/yeka/zip"
13 |
14 | "github.com/pkg/sftp"
15 | "golang.org/x/crypto/ssh"
16 | )
17 |
18 | func connect(user, password, host string, port int) (*sftp.Client, error) {
19 | var (
20 | auth []ssh.AuthMethod
21 | addr string
22 | clientConfig *ssh.ClientConfig
23 | sshClient *ssh.Client
24 | sftpClient *sftp.Client
25 | err error
26 | )
27 | // get auth method
28 | auth = make([]ssh.AuthMethod, 0)
29 | auth = append(auth, ssh.Password(password))
30 |
31 | clientConfig = &ssh.ClientConfig{
32 | User: user,
33 | Auth: auth,
34 | Timeout: 30 * time.Second,
35 | HostKeyCallback: ssh.InsecureIgnoreHostKey(),
36 | }
37 |
38 | // connet to ssh
39 | addr = fmt.Sprintf("%s:%d", host, port)
40 |
41 | if sshClient, err = ssh.Dial("tcp", addr, clientConfig); err != nil {
42 | return nil, err
43 | }
44 |
45 | // create sftp client
46 | if sftpClient, err = sftp.NewClient(sshClient); err != nil {
47 | return nil, err
48 | }
49 |
50 | return sftpClient, nil
51 | }
52 |
53 | var FORMAT = "2006-01-02"
54 | var (
55 | err error
56 | sftpClient *sftp.Client
57 | )
58 | var dbnames = []string{"tower", "mengyin", "pingyi", "shizhi", "tancheng", "yinan", "yishui", "feixian", "gaoxinqu", "hedong", "jingkaiqu", "junan", "luozhuang", "lanling", "lanshan", "lingang", "linshu"}
59 |
60 | func main() {
61 |
62 | // 这里换成实际的 SSH 连接的 用户名,密码,主机名或IP,SSH端口
63 | // sftpClient, err = connect("root", "sdlylshl871016", "111.235.181.127", 443)
64 | sftpClient, err = connect("root", "HR2018!!", "15.14.12.150", 22)
65 | if err != nil {
66 | log.Println(err)
67 | }
68 | defer sftpClient.Close()
69 | // 用来测试的远程文件路径 和 本地文件夹
70 | // fmt.Println(shizhi)
71 | // var localDir = "."
72 | var dsts []string
73 | tmp := os.TempDir()
74 | date_dir := path.Join(tmp, "db_"+time.Now().Format(FORMAT))
75 | os.Mkdir(date_dir, 0755)
76 | var lzkpbi = "/docker/backup/" + time.Now().Format(FORMAT) + "_lzkp_bi_inner.zip"
77 | Down(lzkpbi, date_dir)
78 | dsts = append(dsts, path.Join(date_dir, time.Now().Format(FORMAT)+"_lzkp_bi_inner.zip"))
79 | for _, n := range dbnames {
80 | p := "/docker/backup/" + time.Now().Format(FORMAT) + "_" + n + "_inner.zip"
81 | // fmt.Println(p)
82 |
83 | Down(p, date_dir)
84 | dsts = append(dsts, path.Join(date_dir, time.Now().Format(FORMAT)+"_"+n+"_inner.zip"))
85 |
86 | }
87 |
88 | zippass("", dsts...)
89 | // fmt.Scanln()
90 | for _, v := range dsts {
91 | // fmt.Println(v)
92 | // ioutil.WriteFile(v, []byte("aaa"), 755)
93 | os.Remove(v)
94 | }
95 |
96 | }
97 |
98 | func Down(src, dst string) {
99 | // fmt.Println(src, "数据正在复制中,请耐心等待...")
100 | srcFile, err := sftpClient.Open(src)
101 | if err != nil {
102 | // log.Println(err)
103 | return
104 | }
105 | defer srcFile.Close()
106 |
107 | var localFileName = path.Base(src)
108 | dstFile, err := os.Create(path.Join(dst, localFileName))
109 | if err != nil {
110 | // log.Println(err)
111 | return
112 | }
113 | defer dstFile.Close()
114 |
115 | if _, err = srcFile.WriteTo(dstFile); err != nil {
116 | // log.Println(err)
117 | return
118 | }
119 |
120 | // fmt.Println(src, "数据复制完成!")
121 |
122 | }
123 |
124 | func zippass(dst string, src ...string) {
125 | fzip, err := os.Create(`D:/待测试数据.zip`)
126 | if err != nil {
127 | log.Fatalln(err)
128 | }
129 | zipw := zip.NewWriter(fzip)
130 | defer zipw.Close()
131 | for i, n := range src {
132 | w, err := zipw.Encrypt(strconv.Itoa(i), `hangruan2017`, zip.AES256Encryption)
133 | if err != nil {
134 | log.Fatal(err)
135 | }
136 | f, err := os.Open(n)
137 | if err != nil {
138 | return
139 | }
140 |
141 | _, err = io.Copy(w, f)
142 | if err != nil {
143 | log.Fatal(err)
144 | }
145 | }
146 | zipw.Flush()
147 | }
148 |
--------------------------------------------------------------------------------
/example/getdata/rc/icon.ico:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/rinetd/ssh/5aaea5918db7617adeff0651d3037bf1b3890e2b/example/getdata/rc/icon.ico
--------------------------------------------------------------------------------
/example/getdata/rc/manifest.exe.manifest:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
--------------------------------------------------------------------------------
/example/getdata/rc/versioninfo.json:
--------------------------------------------------------------------------------
1 | {
2 | "_FixedFileInfo": {
3 | "FileVersion": {
4 | "Major": 18,
5 | "Minor": 7,
6 | "Patch": 16,
7 | "Build": 0
8 | },
9 | "ProductVersion": {
10 | "Major": 2018,
11 | "Minor": 7,
12 | "Patch": 16,
13 | "Build": 0
14 | },
15 | "FileFlagsMask": "3f",
16 | "FileFlags ": "00",
17 | "FileOS": "040004",
18 | "FileType": "01",
19 | "FileSubType": "00"
20 | },
21 | "StringFileInfo": {
22 | "FileDescription": "履职考评系统升级",
23 | "FileVersion": "2.1.0",
24 | "ProductName": "履职考评系统",
25 | "ProductVersion": "2018.7.1",
26 | "LegalCopyright": "Copyright@pytool",
27 | "OriginalFilename": "update.exe",
28 | "Comments": " ",
29 | "CompanyName": "Company",
30 | "InternalName": "",
31 | "LegalTrademarks": "",
32 | "PrivateBuild": "",
33 | "SpecialBuild": ""
34 | },
35 | "VarFileInfo": {
36 | "Translation": {
37 | "LangID": "0409",
38 | "CharsetID": "04B0"
39 | }
40 | },
41 | "IconPath": "deploy.ico",
42 | "ManifestPath": ""
43 | }
--------------------------------------------------------------------------------
/example/mysql-proxy/main.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "database/sql"
5 | "fmt"
6 | "net"
7 |
8 | "github.com/pytool/ssh"
9 |
10 | "github.com/go-sql-driver/mysql"
11 | )
12 |
13 | var dsn = `lzkp:yqhtfjzm@tcp(192.168.5.100:3306)/?parseTime=true&loc=Local`
14 | var DBNAME = "shizhi"
15 | var db *sql.DB
16 |
17 | func Prepare() {
18 | var err error
19 | db, err = sql.Open("mysql", dsn)
20 | if err != nil {
21 | // return FAIL, fmt.Errorf("Unable to open connection to database server: %s", err.Error())
22 | fmt.Print("")
23 | }
24 | // defer db.Close()
25 | err = db.Ping()
26 | if err != nil {
27 | // return FAIL, fmt.Errorf("Unable to ping database server: %s", err.Error())
28 | fmt.Print("")
29 | }
30 | // _, err = db.Exec("CREATE DATABASE IF NOT EXISTS" + DBNAME)
31 | // if err != nil {
32 | // // return FAIL, fmt.Errorf("Unable to create database %s: %s", DBNAME, err.Error())
33 | // fmt.Print("")
34 | // }
35 | // defer db.Exec("DROP DATABASE dbgrep")
36 | _, err = db.Exec("use " + DBNAME)
37 | if err != nil {
38 | fmt.Errorf("Unable to select database %s: %s", DBNAME, err.Error())
39 | }
40 | // return m.Run(), nil
41 | }
42 |
43 | func main() {
44 | // SSH的连接参数:
45 | config := ssh.Default.WithPassword("HR2018!!").WithHost("192.168.5.157")
46 | client, err := ssh.New(config)
47 | // client, err := ssh.NewClient("localhost", "22", "root", "ubuntu")
48 | if err != nil {
49 | panic(err)
50 | }
51 | defer client.Close()
52 | fmt.Println(client.Output("id"))
53 |
54 | // 1. 注册自定义的 Dial 命名为:mysql+ssh
55 | // Now we register the ViaSSHDialer with the ssh connection as a parameter
56 | mysql.RegisterDial("mysql+ssh", func(addr string) (net.Conn, error) {
57 | return client.SSHClient.Dial("tcp", addr)
58 | })
59 |
60 | // DB数据库的连接参数:
61 | dbUser := "root" // DB username
62 | dbPass := "" // DB Password
63 | dbHost := "localhost:3306" // DB Hostname/IP
64 | dbName := "shizhi" // Database name
65 | // 2. 使用自定义命名为:mysql+ssh的 Dial 进行mysql连接
66 | // And now we can use our new driver with the regular mysql connection string tunneled through the SSH connection
67 | if db, err := sql.Open("mysql", fmt.Sprintf("%s:%s@mysql+ssh(%s)/%s", dbUser, dbPass, dbHost, dbName)); err == nil {
68 |
69 | if rows, err := db.Query("SELECT user, host FROM mysql.user "); err == nil {
70 | for rows.Next() {
71 | var id string
72 | var name string
73 | rows.Scan(&id, &name)
74 | fmt.Printf("ID: %s\tName: %s\n", id, name)
75 | }
76 | rows.Close()
77 | } else {
78 | fmt.Printf("Failure: %s", err.Error())
79 | }
80 |
81 | db.Close()
82 | fmt.Printf("Successfully connected to the db\n")
83 | }
84 | }
85 |
--------------------------------------------------------------------------------
/example/runetl/Makefile:
--------------------------------------------------------------------------------
1 | PROJECT = 数据同步
2 | VERSION = $(shell git describe)
3 | BRANCH = $(shell git name-rev --name-only HEAD)
4 | VERSION ="$(echo $TRAVIS_TAG)"
5 | ARCNAME = $(PROJECT)-$(VERSION)-$(GOOS)-$(GOARCH)
6 | ARTIFACTS_DIR=artifact
7 |
8 |
9 | # ZIP="zip -9 -r"
10 | # TAR="tar cvf"
11 | # GZIP="gzip -9"
12 | # GZIP_7Z="7za a -tgzip -mx9"
13 | # ZIP_7Z="7za a -tzip -mx9"
14 | ifndef ZIP
15 | ifneq ($(shell which zip 2>/dev/null),)
16 | ZIP := zip -9
17 | endif
18 | ifneq ($(shell which 7z 2>/dev/null),)
19 | ZIP := 7z a -tzip -mx=9
20 | endif
21 | ifneq ($(shell which 7za 2>/dev/null),)
22 | ZIP := 7za a -tzip -mx=9
23 | endif
24 | ifndef ZIP
25 | $(warning "No zip / 7z / 7za in ($(PATH))")
26 | ZIP := : zip_not_found
27 | endif
28 | endif
29 |
30 | .PHONY: all release release-all
31 | all: release-all
32 |
33 |
34 | .PHONY: windows-dependencies
35 | windows-dependencies:
36 | @ go get github.com/josephspurrier/goversioninfo/cmd/goversioninfo
37 |
38 | .PHONY: embed-assets
39 | embed-assets:
40 | @ GO111MODULE=off go get -u github.com/jteeuwen/go-bindata/...
41 | @# go-bindata ./logos/microBadger_headert.png ./webpage.html
42 |
43 |
44 |
45 | release:
46 | goversioninfo -icon=rc/icon.ico -manifest=rc/manifest.exe.manifest rc/versioninfo.json
47 | env CGO_ENABLED=0 GOOS=$(GOOS) GOARCH=$(GOARCH) go build $(FLAGS) -ldflags='-s -w -X github.com/rinetd/transfer/version.Version=$(VERSION)' -o build/$(GOOS)-$(GOARCH)/$(PROJECT)$(EXT)
48 | rm resource.syso
49 | - tar czf build/$(ARCNAME).tar.gz -C build/$(GOOS)-$(GOARCH)/ $(PROJECT)$(EXT)
50 | - tar czf build/$(ARCNAME).tar.gz -C build/$(GOOS)-$(GOARCH)/ $(PROJECT)$(EXT)
51 | ifeq ($(OS),Windows_NT)
52 | cd dist; \
53 | rm -f $(ARCNAME)-*-Win.zip; \
54 | $(ZIP) $(ARCNAME)-$(VERSTR)-Win.zip build/$(GOOS)-$(GOARCH)/ $(PROJECT)$(EXT);
55 | $(ZIP) dist/$(ARCNAME)-$(VERSTR)-Win.zip -r0 images/*.png;
56 | endif
57 |
58 | release-all:
59 | # -@$(MAKE) release GOOS=darwin GOARCH=amd64
60 | # -@$(MAKE) release GOOS=linux GOARCH=386
61 | # -@$(MAKE) release GOOS=linux GOARCH=amd64
62 | -@$(MAKE) release GOOS=windows GOARCH=386 EXT=.exe
63 | # -@$(MAKE) release GOOS=windows GOARCH=amd64 EXT=.exe
64 |
65 | .PHONY: windows
66 | windows: windows-dependencies embed-assets
67 | goversioninfo -icon=rc/icon.ico -manifest=rc/manifest.exe.manifest rc/versioninfo.json
68 | @- rm binaries/*.exe
69 | CGO_ENABLED=0 GOOS=windows GOARCH=386 go build -x -ldflags="-s -w " -o binaries/deploy`date +%m%d`.exe
70 | @# - rm binaries/deploy_windows_64bit.exe
71 | @# - CGO_ENABLED=0 GOOS=windows GOARCH=amd64 go build -ldflags="-s -w -H=windowsgui -linkmode internal" -o binaries/deploy_windows_64bit.exe
72 | rm resource.syso
73 |
74 | platform:
75 | # @$(MAKE) releaseGOOS=js GOARCH=wasm
76 | # @$(MAKE) release GOOS=windows GOARCH=386 FLAGS='-ldflags="-H=windowsgui"' EXE=.exe
77 | # @$(MAKE) release GOOS=windows GOARCH=amd64 FLAGS='-ldflags="-H=windowsgui"' EXE=.exe
78 | # @$(MAKE) release GOOS=linux GOARCH=arm
79 | # @$(MAKE) release GOOS=linux GOARCH=arm64
80 | # @$(MAKE) release GOOS=linux GOARCH=mips
81 | # @$(MAKE) release GOOS=linux GOARCH=mips64
82 | # @$(MAKE) release GOOS=linux GOARCH=mips64le
83 | # @$(MAKE) release GOOS=linux GOARCH=mipsle
84 | # @$(MAKE) release GOOS=linux GOARCH=ppc64
85 | # @$(MAKE) release GOOS=linux GOARCH=ppc64le
86 | # @$(MAKE) release GOOS=linux GOARCH=s390x
87 | # @$(MAKE) release GOOS=android GOARCH=386
88 | # @$(MAKE) release GOOS=android GOARCH=amd64
89 | # @$(MAKE) release GOOS=android GOARCH=arm
90 | # @$(MAKE) release GOOS=android GOARCH=arm64
91 | # @$(MAKE) release GOOS=darwin GOARCH=386
92 | # @$(MAKE) release GOOS=darwin GOARCH=arm
93 | # @$(MAKE) release GOOS=darwin GOARCH=arm64
94 | # @$(MAKE) release GOOS=dragonfly GOARCH=amd64
95 | # @$(MAKE) release GOOS=freebsd GOARCH=386
96 | # @$(MAKE) release GOOS=freebsd GOARCH=amd64
97 | # @$(MAKE) release GOOS=freebsd GOARCH=arm
98 | # @$(MAKE) release GOOS=nacl GOARCH=386
99 | # @$(MAKE) release GOOS=nacl GOARCH=amd64p32
100 | # @$(MAKE) release GOOS=nacl GOARCH=arm
101 | # @$(MAKE) release GOOS=netbsd GOARCH=386
102 | # @$(MAKE) release GOOS=netbsd GOARCH=amd64
103 | # @$(MAKE) release GOOS=netbsd GOARCH=arm
104 | # @$(MAKE) release GOOS=openbsd GOARCH=386
105 | # @$(MAKE) release GOOS=openbsd GOARCH=amd64
106 | # @$(MAKE) release GOOS=openbsd GOARCH=arm
107 | # @$(MAKE) release GOOS=plan9 GOARCH=386
108 | # @$(MAKE) release GOOS=plan9 GOARCH=amd64
109 | # @$(MAKE) release GOOS=plan9 GOARCH=arm
110 | # @$(MAKE) release GOOS=solaris GOARCH=amd64
111 |
112 |
113 | .PHONY: build
114 | build:
115 | go get ./...
116 |
117 | .PHONY: test
118 | test:
119 | go get -t ./...
120 | go test -v ...
121 |
122 | build-image:
123 | docker build -t rientd/transfer .
124 |
125 | clean:
126 | rm -rf build dist
127 |
--------------------------------------------------------------------------------
/example/runetl/main.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "fmt"
5 |
6 | "github.com/pytool/ssh"
7 | )
8 |
9 | func main() {
10 | config := ssh.Default.WithHost("15.14.12.153").WithPassword("HR2018!!")
11 | // config.Host = "15.14.12.153"
12 | client, err := ssh.New(config)
13 | // client, err := ssh.NewClient("localhost", "22", "root", "ubuntu")
14 | if err != nil {
15 | // panic(err)
16 | fmt.Println("连接失败,按Enter键退出!")
17 | fmt.Scanln()
18 | }
19 | defer client.Close()
20 |
21 | err = client.Exec("sh /root/shetl/etl.sh")
22 | if err != nil {
23 | fmt.Println(err)
24 | // panic(err)
25 | fmt.Println("执行失败,按Enter键退出!")
26 | fmt.Scanln()
27 | }
28 |
29 | // fmt.Printf("Uptime: %s\n", output)
30 |
31 | }
32 |
--------------------------------------------------------------------------------
/example/runetl/rc/icon.ico:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/rinetd/ssh/5aaea5918db7617adeff0651d3037bf1b3890e2b/example/runetl/rc/icon.ico
--------------------------------------------------------------------------------
/example/runetl/rc/manifest.exe.manifest:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
--------------------------------------------------------------------------------
/example/runetl/rc/versioninfo.json:
--------------------------------------------------------------------------------
1 | {
2 | "FixedFileInfo": {
3 | "FileVersion": {
4 | "Major": 1,
5 | "Minor": 2,
6 | "Patch": 0,
7 | "Build": 1
8 | },
9 | "FileFlagsMask": "3f",
10 | "FileFlags ": "00",
11 | "FileOS": "040004",
12 | "FileType": "01",
13 | "FileSubType": "00"
14 | },
15 | "StringFileInfo": {
16 | "Comments": "执行etl",
17 | "CompanyName": "pytool",
18 | "FileVersion": "",
19 | "FileDescription": "执行数据同步etl",
20 | "ProductName": "履职考评数据同步",
21 | "ProductVersion": "2018.12.11",
22 | "LegalCopyright": "Copyright@pytool",
23 | "OriginalFilename": "etl.exe",
24 | "InternalName": "",
25 | "LegalTrademarks": "",
26 | "PrivateBuild": "",
27 | "SpecialBuild": ""
28 | },
29 | "VarFileInfo": {
30 | "Translation": {
31 | "LangID": "0409",
32 | "CharsetID": "04B0"
33 | }
34 | },
35 | "IconPath": "icon.ico",
36 | "ManifestPath": ""
37 | }
--------------------------------------------------------------------------------
/example/update/main.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "fmt"
5 |
6 | "github.com/pytool/ssh"
7 | )
8 |
9 | func main() {
10 | config := ssh.Default.WithPassword("ubuntu")
11 | client, err := ssh.New(config)
12 | // client, err := ssh.NewClient("localhost", "22", "root", "ubuntu")
13 | if err != nil {
14 | panic(err)
15 | }
16 | defer client.Close()
17 |
18 | output, err := client.Exec("uptime")
19 | if err != nil {
20 | panic(err)
21 | }
22 |
23 | fmt.Printf("Uptime: %s\n", output)
24 |
25 | }
26 |
--------------------------------------------------------------------------------
/example/upload/main.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "github.com/pytool/ssh"
5 | )
6 |
7 | func main() {
8 |
9 | client, err := ssh.NewClient("localhost", "22", "root", "ubuntu")
10 | if err != nil {
11 | panic(err)
12 | }
13 | defer client.Close()
14 | var remotedir = "/root/test/"
15 | // upload dir
16 | var local = "/home/ubuntu/go/src/github.com/pytool/ssh/test/upload/"
17 | client.Upload(local, remotedir)
18 | // upload file
19 | local = "/home/ubuntu/go/src/github.com/pytool/ssh/test/upload/file"
20 | client.Upload(local, remotedir)
21 |
22 | }
23 |
--------------------------------------------------------------------------------
/sftp.go:
--------------------------------------------------------------------------------
1 | package ssh
2 |
3 | import (
4 | "bytes"
5 | "errors"
6 | "io"
7 | "io/ioutil"
8 | "log"
9 | "os"
10 | "path"
11 | "path/filepath"
12 | "strings"
13 | )
14 |
15 | // Upload 上传本地文件 local 到sftp远程目录 remote like rsync
16 | // rsync -av src/ dst ./src/* --> /root/dst/*
17 | // rsync -av src/ dst/ ./src/* --> /root/dst/*
18 | // rsync -av src dst ./src/* --> /root/dst/src/*
19 | // rsync -av src dst/ ./src/* --> /root/dst/src/*
20 | func (c *Client) Upload(local string, remote string) (err error) {
21 | // var localDir, localFile, remoteDir, remoteFile string
22 |
23 | info, err := os.Stat(local)
24 | if err != nil {
25 | return errors.New("sftp: 跳过上传 Upload(\"" + local + "\") ,本地文件不存在或格式错误!")
26 | }
27 | if info.IsDir() {
28 | log.Println("sftp: UploadDir", local)
29 | return c.UploadDir(local, remote)
30 | }
31 | return c.UploadFile(local, remote)
32 | }
33 |
34 | // Download 下载sftp远程文件 remote 到本地 local like rsync
35 | func (c *Client) Download(remote string, local string) (err error) {
36 | if c.IsNotExist(strings.TrimSuffix(remote, "/")) {
37 | return errors.New("sftp: 远程文件不存在,跳过文件下载 \"" + remote + "\" ")
38 | }
39 | if c.IsDir(remote) {
40 | // return errors.New("检测到远程是文件不是目录 \"" + remote + "\" 跳过下载")
41 | return c.downloadDir(remote, local)
42 |
43 | }
44 | return c.downloadFile(remote, local)
45 |
46 | }
47 |
48 | // downloadFile a file from the remote server like cp
49 | func (c *Client) downloadFile(remoteFile, local string) error {
50 | // remoteFile = strings.TrimSuffix(remoteFile, "/")
51 | if !c.IsFile(remoteFile) {
52 | return errors.New("sftp: 文件不存在或不是文件, 跳过目录下载 downloadFile(" + remoteFile + ")")
53 | }
54 | var localFile string
55 | if local[len(local)-1] == '/' {
56 | localFile = filepath.Join(local, filepath.Base(remoteFile))
57 | } else {
58 | localFile = local
59 | }
60 | localFile = filepath.ToSlash(localFile)
61 | if c.Size(remoteFile) > 1000 {
62 | rsum := c.Md5File(remoteFile)
63 | ioutil.WriteFile(localFile+".md5", []byte(rsum), 755)
64 | if FileExist(localFile) {
65 | if rsum != "" {
66 | lsum, _ := Md5File(localFile)
67 | if lsum == rsum {
68 | log.Println("sftp: 文件与本地一致,跳过下载!", localFile)
69 | return nil
70 | }
71 | log.Println("sftp: 正在下载 ", localFile)
72 | }
73 | }
74 | }
75 | if err := os.MkdirAll(filepath.Dir(localFile), os.ModePerm); err != nil {
76 | // log.Println(err)
77 | return err
78 | }
79 |
80 | r, err := c.SFTPClient.Open(remoteFile)
81 | if err != nil {
82 | return err
83 | }
84 | defer r.Close()
85 |
86 | l, err := os.Create(localFile)
87 | if err != nil {
88 | return err
89 | }
90 | defer l.Close()
91 |
92 | _, err = io.Copy(l, r)
93 | return err
94 | }
95 |
96 | // downloadDir from remote dir to local dir like rsync
97 | // rsync -av src/ dst ./src/* --> /root/dst/*
98 | // rsync -av src/ dst/ ./src/* --> /root/dst/*
99 | // rsync -av src dst ./src/* --> /root/dst/src/*
100 | // rsync -av src dst/ ./src/* --> /root/dst/src/*
101 | func (c *Client) downloadDir(remote, local string) error {
102 | var localDir, remoteDir string
103 |
104 | if !c.IsDir(remote) {
105 | return errors.New("sftp: 目录不存在或不是目录, 跳过 downloadDir(" + remote + ")")
106 | }
107 | remoteDir = remote
108 | if remote[len(remote)-1] == '/' {
109 | localDir = local
110 | } else {
111 | localDir = path.Join(local, path.Base(remote))
112 | }
113 |
114 | walker := c.SFTPClient.Walk(remoteDir)
115 |
116 | for walker.Step() {
117 | if err := walker.Err(); err != nil {
118 | log.Println(err)
119 | continue
120 | }
121 |
122 | info := walker.Stat()
123 |
124 | relPath, err := filepath.Rel(remoteDir, walker.Path())
125 | if err != nil {
126 | return err
127 | }
128 |
129 | localPath := filepath.ToSlash(filepath.Join(localDir, relPath))
130 |
131 | // if we have something at the download path delete it if it is a directory
132 | // and the remote is a file and vice a versa
133 | localInfo, err := os.Stat(localPath)
134 | if os.IsExist(err) {
135 | if localInfo.IsDir() {
136 | if info.IsDir() {
137 | continue
138 | }
139 |
140 | err = os.RemoveAll(localPath)
141 | if err != nil {
142 | return err
143 | }
144 | } else if info.IsDir() {
145 | err = os.Remove(localPath)
146 | if err != nil {
147 | return err
148 | }
149 | }
150 | }
151 |
152 | if info.IsDir() {
153 | err = os.MkdirAll(localPath, os.ModePerm)
154 | if err != nil {
155 | return err
156 | }
157 |
158 | continue
159 | }
160 |
161 | c.downloadFile(walker.Path(), localPath)
162 |
163 | }
164 | return nil
165 | }
166 |
167 | //UploadFile 上传本地文件 localFile 到sftp远程目录 remote
168 | func (c *Client) UploadFile(localFile, remote string) error {
169 | // localFile = strings.TrimSuffix(localFile, "/")
170 | // localFile = filepath.ToSlash(localFile)
171 | info, err := os.Stat(localFile)
172 | if err != nil || info.IsDir() {
173 | return errors.New("sftp: 本地文件不存在,或是不是文件 UploadFile(\"" + localFile + "\") 跳过上传")
174 | }
175 |
176 | l, err := os.Open(localFile)
177 | if err != nil {
178 | return err
179 | }
180 | defer l.Close()
181 |
182 | var remoteFile, remoteDir string
183 | if remote[len(remote)-1] == '/' {
184 | remoteFile = filepath.ToSlash(filepath.Join(remote, filepath.Base(localFile)))
185 | remoteDir = remote
186 | } else {
187 | remoteFile = remote
188 | remoteDir = filepath.ToSlash(filepath.Dir(remoteFile))
189 | }
190 | log.Println("sftp: UploadFile", localFile, remoteFile)
191 | if info.Size() > 1000 {
192 | // 1. 检测远程是否存在
193 | rsum := c.Md5File(remoteFile)
194 | if rsum != "" {
195 | lsum, _ := Md5File(localFile)
196 | if lsum == rsum {
197 | log.Println("sftp: 文件与本地一致,跳过上传!", localFile)
198 | return nil
199 | }
200 | log.Println("sftp: 正在上传 ", localFile)
201 | }
202 | }
203 |
204 | // 目录不存在,则创建 remoteDir
205 | if _, err := c.SFTPClient.Stat(remoteDir); err != nil {
206 | log.Println("sftp: Mkdir all", remoteDir)
207 | c.MkdirAll(remoteDir)
208 | }
209 |
210 | r, err := c.SFTPClient.Create(remoteFile)
211 | if err != nil {
212 | return err
213 | }
214 |
215 | _, err = io.Copy(r, l)
216 | return err
217 | }
218 |
219 | // UploadDir files without checking diff status
220 | func (c *Client) UploadDir(localDir string, remoteDir string) (err error) {
221 | // defer func() {
222 | // if err != nil {
223 | // err = errors.New("UploadDir " + err.Error())
224 | // }
225 | // }()
226 | // 本地输入检测,必须是目录
227 | // localDir = filepath.ToSlash(localDir)
228 | info, err := os.Stat(localDir)
229 | if err != nil || !info.IsDir() {
230 | return errors.New("sftp: 本地目录不存在或不是目录 UploadDir(\"" + localDir + "\") 跳过上传")
231 | }
232 |
233 | // 模仿 rsync localDir不以'/'结尾,则创建尾目录
234 | if localDir[len(localDir)-1] != '/' {
235 | remoteDir = filepath.ToSlash(filepath.Join(remoteDir, filepath.Base(localDir)))
236 | }
237 | log.Println("sftp: UploadDir", localDir, remoteDir)
238 |
239 | rootDst := strings.TrimSuffix(remoteDir, "/")
240 | if c.IsFile(rootDst) {
241 | c.SFTPClient.Remove(rootDst)
242 | }
243 |
244 | walkFunc := func(path string, info os.FileInfo, err error) error {
245 | if err != nil {
246 | return err
247 | }
248 | // Calculate the final destination using the
249 | // base source and root destination
250 | relSrc, err := filepath.Rel(localDir, path)
251 | if err != nil {
252 | return err
253 | }
254 | finalDst := filepath.Join(rootDst, relSrc)
255 |
256 | // In Windows, Join uses backslashes which we don't want to get
257 | // to the sftp server
258 | finalDst = filepath.ToSlash(finalDst)
259 |
260 | // Skip the creation of the target destination directory since
261 | // it should exist and we might not even own it
262 | if finalDst == remoteDir {
263 | return nil
264 | log.Println("sftp: ", remoteDir, "--->", finalDst)
265 |
266 | }
267 |
268 | if info.IsDir() {
269 | err := c.MkdirAll(finalDst)
270 | if err != nil {
271 | log.Println("sftp: MkdirAll", err)
272 | }
273 | // log.Println("MkdirAll", finalDst)
274 | // err = c.SFTPClient.Mkdir(finalDst)
275 | // log.Println(err)
276 | // if err := c.SFTPClient.Mkdir(finalDst); err != nil {
277 | // // Do not consider it an error if the directory existed
278 | // remoteFi, fiErr := c.SFTPClient.Lstat(finalDst)
279 | // if fiErr != nil || !remoteFi.IsDir() {
280 | // return err
281 | // }
282 | // }
283 | // return err
284 | } else {
285 | // f, err := os.Open(path)
286 | // if err != nil {
287 | // return err
288 | // }
289 | // defer f.Close()
290 | return c.UploadFile(path, finalDst)
291 | }
292 | return nil
293 |
294 | }
295 | return filepath.Walk(localDir, walkFunc)
296 | }
297 |
298 | // Remove a file from the remote server
299 | func (c *Client) Remove(path string) error {
300 | return c.SFTPClient.Remove(path)
301 | }
302 |
303 | // RemoveDirectory Remove a directory from the remote server
304 | func (c *Client) RemoveDirectory(path string) error {
305 | return c.SFTPClient.RemoveDirectory(path)
306 | }
307 |
308 | // ReadAll Read a remote file and return the contents.
309 | func (c *Client) ReadAll(filepath string) ([]byte, error) {
310 | file, err := c.SFTPClient.Open(filepath)
311 | if err != nil {
312 | return nil, err
313 | }
314 | defer file.Close()
315 |
316 | return ioutil.ReadAll(file)
317 | }
318 |
319 | //FileExist 文件是否存在
320 | func (c *Client) FileExist(filepath string) (bool, error) {
321 | if _, err := c.SFTPClient.Stat(filepath); err != nil {
322 | return false, err
323 | }
324 | return true, nil
325 | }
326 |
327 | func (c *Client) RemoveFile(remoteFile string) error {
328 | return c.SFTPClient.Remove(remoteFile)
329 | }
330 | func (c *Client) RemoveDir(remoteDir string) error {
331 | remoteFiles, err := c.SFTPClient.ReadDir(remoteDir)
332 | if err != nil {
333 | log.Printf("sftp: remove remote dir: %s err: %v\n", remoteDir, err)
334 | return err
335 | }
336 | for _, file := range remoteFiles {
337 | subRemovePath := path.Join(remoteDir, file.Name())
338 | if file.IsDir() {
339 | c.RemoveDir(subRemovePath)
340 | } else {
341 | c.RemoveFile(subRemovePath)
342 | }
343 | }
344 | c.SFTPClient.RemoveDirectory(remoteDir) //must empty dir to remove
345 | log.Printf("sftp: remove remote dir: %s ok\n", remoteDir)
346 | return nil
347 | }
348 |
349 | //RemoveAll 递归删除目录,文件
350 | func (c *Client) RemoveAll(remoteDir string) error {
351 | c.RemoveDir(remoteDir)
352 | return nil
353 | }
354 |
355 | //MkdirAll 创建目录,递归
356 | func (c *Client) MkdirAll(dirpath string) error {
357 |
358 | parentDir := filepath.ToSlash(filepath.Dir(dirpath))
359 | _, err := c.SFTPClient.Stat(parentDir)
360 | if err != nil {
361 | // log.Println(err)
362 | if err.Error() == "file does not exist" {
363 | err := c.MkdirAll(parentDir)
364 | if err != nil {
365 | return err
366 | }
367 | } else {
368 | return err
369 | }
370 | }
371 | err = c.SFTPClient.Mkdir(filepath.ToSlash(dirpath))
372 | if err != nil {
373 | return err
374 | }
375 | return nil
376 | }
377 |
378 | func (c *Client) Mkdir(path string, fi os.FileInfo) error {
379 | log.Printf("[DEBUG] sftp: creating dir %s", path)
380 |
381 | if err := c.SFTPClient.Mkdir(path); err != nil {
382 | // Do not consider it an error if the directory existed
383 | remoteFi, fiErr := c.SFTPClient.Lstat(path)
384 | if fiErr != nil || !remoteFi.IsDir() {
385 | return err
386 | }
387 | }
388 |
389 | mode := fi.Mode().Perm()
390 | if err := c.SFTPClient.Chmod(path, mode); err != nil {
391 | return err
392 | }
393 | return nil
394 | }
395 |
396 | //IsDir 检查远程是否是个目录
397 | func (c *Client) IsDir(path string) bool {
398 | // 检查远程是文件还是目录
399 | info, err := c.SFTPClient.Stat(path)
400 | if err == nil && info.IsDir() {
401 | return true
402 | }
403 | return false
404 | }
405 |
406 | //Size 获取文件大小
407 | func (c *Client) Size(path string) int64 {
408 | info, err := c.SFTPClient.Stat(path)
409 | if err != nil {
410 | return 0
411 | }
412 | return info.Size()
413 | }
414 |
415 | //IsFile 检查远程是否是个文件
416 | func (c *Client) IsFile(path string) bool {
417 | info, err := c.SFTPClient.Stat(path)
418 | if err == nil && !info.IsDir() {
419 | return true
420 | }
421 | return false
422 | }
423 |
424 | //IsNotExist 检查远程是文件是否不存在
425 | func (c *Client) IsNotExist(path string) bool {
426 | _, err := c.SFTPClient.Stat(path)
427 | return err != nil
428 | }
429 |
430 | //IsExist 检查远程是文件是否存在
431 | func (c *Client) IsExist(path string) bool {
432 |
433 | _, err := c.SFTPClient.Stat(path)
434 | return err == nil
435 | }
436 |
437 | //Md5File 检查远程是文件是否存在
438 | func (c *Client) Md5File(path string) string {
439 | if c.IsNotExist(path) {
440 | return ""
441 | }
442 | b, err := c.Output("md5sum " + path)
443 | if err != nil {
444 | return ""
445 | }
446 | return string(bytes.Split(b, []byte{' '})[0])
447 |
448 | }
449 |
--------------------------------------------------------------------------------
/sftp_check_test.go:
--------------------------------------------------------------------------------
1 | package ssh
2 |
3 | import (
4 | "testing"
5 | )
6 |
7 | func TestClient_IsCheck(t *testing.T) {
8 | c := GetClient()
9 | defer c.Close()
10 | var remotes = []string{
11 | "/root/test/notExist",
12 | "/root/test/notExist/",
13 | "/root/test/file",
14 | "/root/test/file/", // 不存在
15 | "/root/test/dir",
16 | "/root/test/dir/",
17 | }
18 |
19 | // /root/test/file 存在
20 | // /root/test/file/ 不存在
21 | // /root/test/dir 存在
22 | // /root/test/dir/ 存在
23 | for _, v := range remotes {
24 | is := c.IsExist(v)
25 | if is {
26 | println(v, "\t存在")
27 | } else {
28 | println(v, "\t不存在")
29 | }
30 | }
31 |
32 | // /root/test/file 不是一个目录
33 | // /root/test/file/ 不是一个目录
34 | // /root/test/dir 是一个目录
35 | // /root/test/dir/ 是一个目录
36 | println()
37 | for _, v := range remotes {
38 | isdir := c.IsDir(v)
39 | if isdir {
40 | println(v, "\t是一个目录")
41 | } else {
42 | println(v, "\t不是一个目录")
43 | }
44 | }
45 |
46 | // /root/test/file 是一个文件
47 | // /root/test/file/ 不是一个文件
48 | // /root/test/dir 不是一个文件
49 | // /root/test/dir/ 不是一个文件
50 | println()
51 | for _, v := range remotes {
52 | isfile := c.IsFile(v)
53 | if isfile {
54 | println(v, "\t是一个文件")
55 | } else {
56 | println(v, "\t不是一个文件")
57 | }
58 |
59 | }
60 |
61 | }
62 |
--------------------------------------------------------------------------------
/sftp_test.go:
--------------------------------------------------------------------------------
1 | package ssh
2 |
3 | import (
4 | "sync"
5 | "testing"
6 | )
7 |
8 | func GetClient() *Client {
9 | var (
10 | once = sync.Once{}
11 | c = &Client{}
12 | err error
13 | )
14 | once.Do(func() {
15 | c, err = NewClient("localhost", "22", "root", "ubuntu")
16 | })
17 | if err != nil {
18 | panic(err)
19 | }
20 | return c
21 | }
22 |
23 | // func TestClient_RemoveAll(t *testing.T) {
24 | // c := GetClient()
25 | // defer c.Close()
26 | // var remotedir = "/root/test/"
27 | // fmt.Println(c.RemoveAll(remotedir))
28 | // }
29 | func TestClient_Init(t *testing.T) {
30 | c := GetClient()
31 | defer c.Close()
32 | var local = "/home/ubuntu/go/src/github.com/pytool/ssh/test/upload/"
33 |
34 | var remotedir = "/root/test/"
35 | c.RemoveAll("/root/upload/")
36 |
37 | err := c.Upload(local, remotedir)
38 | if err != nil {
39 | println("[Upload]", err.Error())
40 | }
41 | }
42 | func TestClient_Upload(t *testing.T) {
43 | c := GetClient()
44 | defer c.Close()
45 |
46 | var local = "/home/ubuntu/go/src/github.com/pytool/ssh/test/upload/"
47 | var uploads = map[string][]string{
48 | local + "null/": []string{"/root/upload/test/null/1", "/root/upload/test/null/2/"},
49 | local + "null/": []string{"/root/upload/test/null/3", "/root/upload/test/null/4/"},
50 | local + "file": []string{"/root/upload/test/file/1", "/root/upload/test/file/2/"},
51 | local + "file/": []string{"/root/upload/test/file/3", "/root/upload/test/file/4/"},
52 | local + "dir": []string{"/root/upload/test/dir/1", "/root/upload/test/dir/2/"},
53 | local + "dir/": []string{"/root/upload/test/dir/3", "/root/upload/test/dir/4/"},
54 | }
55 |
56 | for local, remotes := range uploads {
57 | for _, remote := range remotes {
58 | err := c.Upload(local, remote)
59 | if err != nil {
60 | println(err.Error())
61 | }
62 | // println(remote, "--->", v, "Finish download!")
63 |
64 | }
65 | }
66 | }
67 |
68 | func TestClient_Download(t *testing.T) {
69 | c := GetClient()
70 | defer c.Close()
71 |
72 | var local = "/home/ubuntu/go/src/github.com/pytool/ssh/test/download"
73 | var download = map[string][]string{
74 | "/root/test/notExist": []string{local + "/localNotExist/null/1", local + "/localNotExist/null/2/"},
75 | "/root/test/notExist/": []string{local + "/localNotExist/null/3", local + "/localNotExist/null/4/"},
76 | "/root/test/file": []string{local + "/localNotExist/file/1", local + "/localNotExist/file/2/"},
77 | "/root/test/file/": []string{local + "/localNotExist/file/3", local + "/localNotExist/file/4/"},
78 | "/root/test/dir": []string{local + "/localNotExist/dir/1", local + "/localNotExist/dir/2/"},
79 | "/root/test/dir/": []string{local + "/localNotExist/dir/3", local + "/localNotExist/dir/4/"},
80 | }
81 |
82 | for remote, local := range download {
83 | for _, v := range local {
84 | err := c.Download(remote, v)
85 | if err != nil {
86 | println(err.Error())
87 | }
88 | // println(remote, "--->", v, "Finish download!")
89 |
90 | }
91 | }
92 |
93 | }
94 |
95 | func TestClient_DownloadFile(t *testing.T) {
96 | c := GetClient()
97 | defer c.Close()
98 |
99 | var local = "/home/ubuntu/go/src/github.com/pytool/ssh/test/downloadfile"
100 | var download = map[string][]string{
101 | "/root/test/notExist": []string{local + "/localNotExist/null/1", local + "/localNotExist/null/2/"},
102 | "/root/test/notExist/": []string{local + "/localNotExist/null/3", local + "/localNotExist/null/4/"},
103 | "/root/test/file": []string{local + "/localNotExist/file/1", local + "/localNotExist/file/2/"},
104 | "/root/test/file/": []string{local + "/localNotExist/file/3", local + "/localNotExist/file/4/"},
105 | "/root/test/dir": []string{local + "/localNotExist/dir/1", local + "/localNotExist/dir/2/"},
106 | "/root/test/dir/": []string{local + "/localNotExist/dir/3", local + "/localNotExist/dir/4/"},
107 | }
108 |
109 | for remote, local := range download {
110 | for _, v := range local {
111 | err := c.downloadFile(remote, v)
112 | if err != nil {
113 | println(err.Error())
114 | }
115 | // println(remote, "--->", v, "Finish download!")
116 |
117 | }
118 | }
119 | }
120 | func TestClient_DownloadDir(t *testing.T) {
121 | c := GetClient()
122 | defer c.Close()
123 |
124 | var local = "/home/ubuntu/go/src/github.com/pytool/ssh/test/downloaddir"
125 | var download = map[string][]string{
126 | "/root/test/notExist": []string{local + "/localNotExist/null/1", local + "/localNotExist/null/2/"},
127 | "/root/test/notExist/": []string{local + "/localNotExist/null/3", local + "/localNotExist/null/4/"},
128 | "/root/test/file": []string{local + "/localNotExist/file/1", local + "/localNotExist/file/2/"},
129 | "/root/test/file/": []string{local + "/localNotExist/file/3", local + "/localNotExist/file/4/"},
130 | "/root/test/dir": []string{local + "/localNotExist/dir/1", local + "/localNotExist/dir/2/"},
131 | "/root/test/dir/": []string{local + "/localNotExist/dir/3", local + "/localNotExist/dir/4/"},
132 | }
133 |
134 | for remote, local := range download {
135 | for _, v := range local {
136 | err := c.downloadDir(remote, v)
137 | if err != nil {
138 | println(err.Error())
139 | }
140 | // println(remote, "--->", v, "Finish download!")
141 |
142 | }
143 | }
144 | }
145 | func TestClient_UploadFile(t *testing.T) {
146 | c := GetClient()
147 | defer c.Close()
148 | var local = "/home/ubuntu/go/src/github.com/pytool/ssh/test/upload/"
149 | var uploads = map[string][]string{
150 | local + "null": []string{"/root/upload/file_test/null/1", "/root/upload/file_test/null/2/"},
151 | local + "null/": []string{"/root/upload/file_test/null/3", "/root/upload/file_test/null/4/"},
152 | local + "file": []string{"/root/upload/file_test/file/1", "/root/upload/file_test/file/2/"},
153 | local + "file/": []string{"/root/upload/file_test/file/3", "/root/upload/file_test/file/4/"},
154 | local + "dir": []string{"/root/upload/file_test/dir/1", "/root/upload/file_test/dir/2/"},
155 | local + "dir/": []string{"/root/upload/file_test/dir/3", "/root/upload/file_test/dir/4/"},
156 | }
157 |
158 | for local, remotes := range uploads {
159 | for _, remote := range remotes {
160 | err := c.UploadFile(local, remote)
161 | if err != nil {
162 | println(err.Error())
163 | }
164 | // println(remote, "--->", v, "Finish download!")
165 |
166 | }
167 | }
168 | }
169 |
170 | func TestClient_UploadDir(t *testing.T) {
171 | c := GetClient()
172 | defer c.Close()
173 | var local = "/home/ubuntu/go/src/github.com/pytool/ssh/test/upload/"
174 | var uploads = map[string][]string{
175 | local + "null/": []string{"/root/upload/dir_test/null/1", "/root/upload/dir_test/null/2/"},
176 | local + "null/": []string{"/root/upload/dir_test/null/3", "/root/upload/dir_test/null/4/"},
177 | local + "file": []string{"/root/upload/dir_test/file/1", "/root/upload/dir_test/file/2/"},
178 | local + "file/": []string{"/root/upload/dir_test/file/3", "/root/upload/dir_test/file/4/"},
179 | local + "dir": []string{"/root/upload/dir_test/dir/1", "/root/upload/dir_test/dir/2/"},
180 | local + "dir/": []string{"/root/upload/dir_test/dir/3", "/root/upload/dir_test/dir/4/"},
181 | }
182 |
183 | for local, remotes := range uploads {
184 | for _, remote := range remotes {
185 | err := c.UploadDir(local, remote)
186 | if err != nil {
187 | println(err.Error())
188 | }
189 | // println(remote, "--->", v, "Finish download!")
190 |
191 | }
192 | }
193 | }
194 |
--------------------------------------------------------------------------------
/ssh.go:
--------------------------------------------------------------------------------
1 | package ssh
2 |
3 | import (
4 | "bufio"
5 | "bytes"
6 | "errors"
7 | "fmt"
8 | "io"
9 | "os"
10 | "path/filepath"
11 | )
12 |
13 | // Run Execute cmd on the remote host for daemon service
14 | func (c *Client) Run(cmd string) {
15 | session, err := c.SSHClient.NewSession()
16 | if err != nil {
17 | return
18 | }
19 | defer session.Close()
20 |
21 | err = session.Start(cmd)
22 | if err != nil {
23 | fmt.Printf("exec command:%v error:%v\n", cmd, err)
24 | }
25 | fmt.Printf("Waiting for command:%v to finish...\n", cmd)
26 | //阻塞等待fork出的子进程执行的结果,和cmd.Start()配合使用[不等待回收资源,会导致fork出执行shell命令的子进程变为僵尸进程]
27 | err = session.Wait()
28 | if err != nil {
29 | fmt.Printf(":Command finished with error: %v\n", err)
30 | }
31 | return
32 | }
33 |
34 | //Exec Execute cmd on the remote host and bind stderr and stdout
35 | func (c *Client) Exec1(cmd string) error {
36 |
37 | // New Session
38 | session, err := c.SSHClient.NewSession()
39 | if err != nil {
40 | return err
41 | }
42 | defer session.Close()
43 |
44 | // go func() {
45 | // time.Sleep(2419200 * time.Second)
46 | // conn.Close()
47 | // }()
48 |
49 | session.Stdout = os.Stdout
50 | session.Stderr = os.Stderr
51 | err = session.Run(cmd)
52 | session.Close()
53 | return nil
54 |
55 | }
56 |
57 | //Exec Execute cmd on the remote host and bind stderr and stdout
58 | func (c *Client) Exec(cmd string) error {
59 | session, err := c.SSHClient.NewSession()
60 | if err != nil {
61 | return err
62 | }
63 | defer session.Close()
64 | // session.Run(cmd)
65 | // return session.CombinedOutput(cmd)
66 | stdout, err := session.StdoutPipe()
67 | // stderr, err = session.StderrPipe()
68 | if err != nil {
69 | fmt.Println(err)
70 | return err
71 | }
72 |
73 | var b bytes.Buffer
74 | session.Stderr = &b
75 | session.Start(cmd)
76 | //创建一个流来读取管道内内容,这里逻辑是通过一行一行的读取的
77 | reader := bufio.NewReader(stdout)
78 |
79 | //实时循环读取输出流中的一行内容
80 | for {
81 | line, err2 := reader.ReadString('\n')
82 | if err2 != nil || io.EOF == err2 {
83 | break
84 | }
85 | print(line)
86 | }
87 |
88 | //阻塞直到该命令执行完成,该命令必须是被Start方法开始执行的
89 | session.Wait()
90 | if b.Len() > 0 {
91 | return errors.New(b.String())
92 | }
93 | return nil
94 | }
95 |
96 | // Output Execute cmd on the remote host and return stderr and stdout
97 | func (c *Client) Output(cmd string) ([]byte, error) {
98 | session, err := c.SSHClient.NewSession()
99 | if err != nil {
100 | return nil, err
101 | }
102 | defer session.Close()
103 | // session.Run(cmd)
104 | // return session.CombinedOutput(cmd)
105 | return session.Output(cmd)
106 | }
107 |
108 | // RunScript Executes a shell script file on the remote machine.
109 | // It is copied in the tmp folder and ran in a single session.
110 | // chmod +x is applied before running.
111 | // Returns an SshResponse and an error if any has occured
112 | func (c *Client) RunScript(scriptPath string) ([]byte, error) {
113 | session, err := c.SSHClient.NewSession()
114 | if err != nil {
115 | return nil, err
116 | }
117 | defer session.Close()
118 |
119 | // 1. 上传 script
120 | remotePath := fmt.Sprintf("/tmp/script/%s", filepath.Base(scriptPath))
121 | if err := c.UploadFile(scriptPath, remotePath); err != nil {
122 | return nil, err
123 | }
124 | // 2. 执行script
125 | rCmd := fmt.Sprintf("chmod +x %s ; %s", remotePath, remotePath)
126 | return session.CombinedOutput(rCmd)
127 | }
128 |
--------------------------------------------------------------------------------
/sudo.go:
--------------------------------------------------------------------------------
1 | package ssh
2 |
3 | import (
4 | "bytes"
5 | "io"
6 | "sync"
7 | )
8 |
9 | // This is the phrase that tells us sudo is looking for a password via stdin
10 | const sudoPwPrompt = "sudo_password"
11 |
12 | // sudoWriter is used to both combine stdout and stderr as well as
13 | // look for a password request from sudo.
14 | type sudoWriter struct {
15 | b bytes.Buffer
16 | pw string // The password to pass to sudo (if requested)
17 | stdin io.Writer // The writer from the ssh session
18 | m sync.Mutex
19 | }
20 |
21 | func (w *sudoWriter) Write(p []byte) (int, error) {
22 | // If we get the sudo password prompt phrase send the password via stdin
23 | // and don't write it to the buffer.
24 | if string(p) == sudoPwPrompt {
25 | w.stdin.Write([]byte(w.pw + "\n"))
26 | w.pw = "" // We don't need the password anymore so reset the string
27 | return len(p), nil
28 | }
29 |
30 | w.m.Lock()
31 | defer w.m.Unlock()
32 |
33 | return w.b.Write(p)
34 | }
35 |
36 | // ExecSu Execute cmd via sudo. Do not include the sudo command in
37 | // the cmd string. For example: Client.ExecSudo("uptime", "password").
38 | // If you are using passwordless sudo you can use the regular Exec()
39 | // function.
40 | func (c *Client) ExecSu(cmd, passwd string) ([]byte, error) {
41 | session, err := c.SSHClient.NewSession()
42 | if err != nil {
43 | return nil, err
44 | }
45 | defer session.Close()
46 |
47 | // -n run non interactively
48 | // -p specify the prompt. We do this to know that sudo is asking for a passwd
49 | // -S Writes the prompt to StdErr and reads the password from StdIn
50 | cmd = "sudo -p " + sudoPwPrompt + " -S " + cmd
51 |
52 | // Use the sudoRW struct to handle the interaction with sudo and capture the
53 | // output of the command
54 | w := &sudoWriter{
55 | pw: passwd,
56 | }
57 | w.stdin, err = session.StdinPipe()
58 | if err != nil {
59 | return nil, err
60 | }
61 |
62 | // Combine stdout, stderr to the same writer which also looks for the sudo
63 | // password prompt
64 | session.Stdout = w
65 | session.Stderr = w
66 |
67 | err = session.Run(cmd)
68 |
69 | return w.b.Bytes(), err
70 | }
71 |
--------------------------------------------------------------------------------
/test/upload/dir/file:
--------------------------------------------------------------------------------
1 | dir file
--------------------------------------------------------------------------------
/test/upload/dir/subfold/subfile:
--------------------------------------------------------------------------------
1 | this is subdir file
--------------------------------------------------------------------------------
/test/upload/file:
--------------------------------------------------------------------------------
1 | file
--------------------------------------------------------------------------------
/util.go:
--------------------------------------------------------------------------------
1 | package ssh
2 |
3 | import (
4 | "bufio"
5 | "crypto"
6 | "encoding/hex"
7 | "io"
8 | "log"
9 | "os"
10 | "path"
11 | "path/filepath"
12 |
13 | "github.com/mitchellh/go-homedir"
14 | )
15 |
16 | func KeyFile() string {
17 |
18 | home, err := homedir.Dir()
19 | if err != nil {
20 | println(err.Error())
21 | return ""
22 | }
23 | key := filepath.ToSlash(path.Join(home, ".ssh/id_rsa"))
24 | log.Println(key)
25 | return key
26 | }
27 | func FileExist(file string) bool {
28 | if _, err := os.Stat(file); err != nil {
29 | if os.IsNotExist(err) {
30 | return false
31 | }
32 | }
33 | return true
34 | }
35 | func MkdirAll(path string) error {
36 | // 检测文件夹是否存在 若不存在 创建文件夹
37 | if _, err := os.Stat(path); err != nil {
38 | if os.IsNotExist(err) {
39 | return os.MkdirAll(path, os.ModePerm)
40 | }
41 | }
42 | return nil
43 | }
44 |
45 | //Md5File 计算md5
46 | func Md5File(filename string) (string, error) {
47 | f, err := os.Open(filename)
48 | if err != nil {
49 | return "", err
50 | }
51 | defer f.Close()
52 |
53 | r := bufio.NewReader(f)
54 |
55 | hash := crypto.MD5.New()
56 | _, err = io.Copy(hash, r)
57 | if err != nil {
58 | return "", err
59 | }
60 |
61 | out := hex.EncodeToString(hash.Sum(nil))
62 | return out, nil
63 | }
64 |
--------------------------------------------------------------------------------