commit | 966fb2ba48006b53b12ea8d8118e1d1f87fecad6 | [log] [tgz] |
---|---|---|
author | Jonas Alfredsson <jonasal@axis.com> | Wed May 26 15:14:11 2021 +0200 |
committer | Jonas Alfredsson <jonasal@axis.com> | Thu May 27 09:26:36 2021 +0200 |
tree | 7ef2069bc36c6f2a34d9ff08f25ea05c4d71cee5 | |
parent | 877482f5981e734a9fd3d619df1f771f61126830 [diff] |
Fix for file names with space in them Use the %q syntax for [fmt][1] in order to create a quoted and escaped string. This way we can both copy and write files which have a space in them. Disclosure: Technically it is not entirely correct to use %q here since Go's quoting rules aren't identical to those of a shell, but it's good enough. [1]: https://golang.org/pkg/fmt/
This package makes it very easy to copy files over scp in Go. It uses the golang.org/x/crypto/ssh package to establish a secure connection to a remote server in order to copy the files via the SCP protocol.
package main import ( "fmt" scp "github.com/bramvdbogaerde/go-scp" "github.com/bramvdbogaerde/go-scp/auth" "golang.org/x/crypto/ssh" "os" ) func main() { // Use SSH key authentication from the auth package // we ignore the host key in this example, please change this if you use this library clientConfig, _ := auth.PrivateKey("username", "/path/to/rsa/key", ssh.InsecureIgnoreHostKey()) // For other authentication methods see ssh.ClientConfig and ssh.AuthMethod // Create a new SCP client client := scp.NewClient("example.com:22", &clientConfig) // Connect to the remote server err := client.Connect() if err != nil { fmt.Println("Couldn't establish a connection to the remote server ", err) return } // Open a file f, _ := os.Open("/path/to/local/file") // Close client connection after the file has been copied defer client.Close() // Close the file after it has been copied defer f.Close() // Finaly, copy the file over // Usage: CopyFile(fileReader, remotePath, permission) err = client.CopyFile(f, "/home/server/test.txt", "0655") if err != nil { fmt.Println("Error while copying file ", err) } }
If you have an existing established SSH connection, you can use that instead.
func connectSSH() *ssh.Client { // setup SSH connection } func main() { sshClient := connectSSH() // Create a new SCP client, note that this function might // return an error, as a new SSH session is established using the existing connecton client, err := scp.NewClientBySSH(sshClient) if err != nil { fmt.Println("Error creating new SSH session from existing connection", err) } /* .. same as above .. */ }
It is also possible to copy remote files using this library. The usage is similar to the example at the top of this section, except that CopyFromRemote
needsto be used instead.
For a more comprehensive example, please consult the TestDownloadFile
function in t he tests/basic_test.go
file.
This library is licensed under the Mozilla Public License 2.0.
A copy of the license is provided in the LICENSE.txt
file.
Copyright (c) 2020 Bram Vandenbogaerde