Sending file over SSH in go
I found this answer before posting this question but the answer is not clear to me.
Here is the code of the answer:
conn, err := ssh.Dial("tcp", hostname+":22", config)
if err != nil {
return err
}
session, err := conn.NewSession()
if err != nil {
return err
}
defer session.Close()
r, err := session.StdoutPipe()
if err != nil {
return err
}
name := fmt.Sprintf("%s/backup_folder_%v.tar.gz", path, time.Now().Unix())
file, err := os.OpenFile(name, os.O_APPEND|os.O_WRONLY|os.O_CREATE, 0644)
if err != nil {
return err
}
defer file.Close()
if err := session.Start(cmd); err != nil {
return err
}
n, err := io.Copy(file, r)
if err != nil {
return err
}
if err := session.Wait(); err != nil {
return err
}
return nil
I don't understand relation between the cmd variable and io.Copy, where and how does it know which file to copy.
I like the idea of using io.Copy but i do not know how to create the file via ssh and start sending content to it using io.Copy.
add a comment |
I found this answer before posting this question but the answer is not clear to me.
Here is the code of the answer:
conn, err := ssh.Dial("tcp", hostname+":22", config)
if err != nil {
return err
}
session, err := conn.NewSession()
if err != nil {
return err
}
defer session.Close()
r, err := session.StdoutPipe()
if err != nil {
return err
}
name := fmt.Sprintf("%s/backup_folder_%v.tar.gz", path, time.Now().Unix())
file, err := os.OpenFile(name, os.O_APPEND|os.O_WRONLY|os.O_CREATE, 0644)
if err != nil {
return err
}
defer file.Close()
if err := session.Start(cmd); err != nil {
return err
}
n, err := io.Copy(file, r)
if err != nil {
return err
}
if err := session.Wait(); err != nil {
return err
}
return nil
I don't understand relation between the cmd variable and io.Copy, where and how does it know which file to copy.
I like the idea of using io.Copy but i do not know how to create the file via ssh and start sending content to it using io.Copy.
1
You can use github.com/bramvdbogaerde/go-scp
– Ullaakut
Nov 12 at 7:38
add a comment |
I found this answer before posting this question but the answer is not clear to me.
Here is the code of the answer:
conn, err := ssh.Dial("tcp", hostname+":22", config)
if err != nil {
return err
}
session, err := conn.NewSession()
if err != nil {
return err
}
defer session.Close()
r, err := session.StdoutPipe()
if err != nil {
return err
}
name := fmt.Sprintf("%s/backup_folder_%v.tar.gz", path, time.Now().Unix())
file, err := os.OpenFile(name, os.O_APPEND|os.O_WRONLY|os.O_CREATE, 0644)
if err != nil {
return err
}
defer file.Close()
if err := session.Start(cmd); err != nil {
return err
}
n, err := io.Copy(file, r)
if err != nil {
return err
}
if err := session.Wait(); err != nil {
return err
}
return nil
I don't understand relation between the cmd variable and io.Copy, where and how does it know which file to copy.
I like the idea of using io.Copy but i do not know how to create the file via ssh and start sending content to it using io.Copy.
I found this answer before posting this question but the answer is not clear to me.
Here is the code of the answer:
conn, err := ssh.Dial("tcp", hostname+":22", config)
if err != nil {
return err
}
session, err := conn.NewSession()
if err != nil {
return err
}
defer session.Close()
r, err := session.StdoutPipe()
if err != nil {
return err
}
name := fmt.Sprintf("%s/backup_folder_%v.tar.gz", path, time.Now().Unix())
file, err := os.OpenFile(name, os.O_APPEND|os.O_WRONLY|os.O_CREATE, 0644)
if err != nil {
return err
}
defer file.Close()
if err := session.Start(cmd); err != nil {
return err
}
n, err := io.Copy(file, r)
if err != nil {
return err
}
if err := session.Wait(); err != nil {
return err
}
return nil
I don't understand relation between the cmd variable and io.Copy, where and how does it know which file to copy.
I like the idea of using io.Copy but i do not know how to create the file via ssh and start sending content to it using io.Copy.
asked Nov 12 at 5:29
HowToGo
827
827
1
You can use github.com/bramvdbogaerde/go-scp
– Ullaakut
Nov 12 at 7:38
add a comment |
1
You can use github.com/bramvdbogaerde/go-scp
– Ullaakut
Nov 12 at 7:38
1
1
You can use github.com/bramvdbogaerde/go-scp
– Ullaakut
Nov 12 at 7:38
You can use github.com/bramvdbogaerde/go-scp
– Ullaakut
Nov 12 at 7:38
add a comment |
1 Answer
1
active
oldest
votes
Here is a minimal example on how to use Go as an scp client:
config := &ssh.ClientConfig{
User: "user",
Auth: ssh.AuthMethod{
ssh.Password("pass"),
},
HostKeyCallback: ssh.InsecureIgnoreHostKey(),
}
client, _ := ssh.Dial("tcp", "remotehost:22", config)
defer client.Close()
session, _ := client.NewSession()
defer session.Close()
file, _ := os.Open("filetocopy")
defer file.Close()
stat, _ := file.Stat()
wg := sync.WaitGroup{}
wg.Add(1)
go func() {
hostIn, _ := session.StdinPipe()
defer hostIn.Close()
fmt.Fprintf(hostIn, "C0664 %d %sn", stat.Size(), "filecopyname")
io.Copy(hostIn, file)
fmt.Fprint(hostIn, "x00")
wg.Done()
}()
session.Run("/usr/bin/scp -t /remotedirectory/")
wg.Wait()
Note that I have ignored all errors only for conciseness.
session.StdinPipe()will create a writable pipe for the remote host.
fmt.Fprintf(... "C0664 ...")will signal the start of a file with0664permission,stat.Size()size and the remote filenamefilecopyname.
io.Copy(hostIn, file)will write the contents offileintohostIn.
fmt.Fprint(hostIn, "x00")will signal the end of the file.
session.Run("/usr/bin/scp -qt /remotedirectory/")will run the scp command.
Edit: Added waitgroup per OP's request
If you don't want to go through the trouble of writing this, there are already packages out there that has this functionality: github.com/bramvdbogaerde/go-scp
– ssemilla
Nov 12 at 8:53
I really wanted answer like this. Thanks a lot.
– HowToGo
Nov 12 at 12:35
It doesn't really work for me. It creates the file but there is no content inside. I actually realised it's not great to use session with scp within a command. This answer looks more of a copy paste than actual answer. io.Copy does not work. It just finishes because it's inside of the Goroutine otherwise it's left "doing something"
– HowToGo
Nov 12 at 12:57
file with no content?
– HowToGo
Nov 12 at 13:02
io.Copy spins forever
– HowToGo
Nov 12 at 13:02
|
show 3 more comments
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53256373%2fsending-file-over-ssh-in-go%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
1 Answer
1
active
oldest
votes
1 Answer
1
active
oldest
votes
active
oldest
votes
active
oldest
votes
Here is a minimal example on how to use Go as an scp client:
config := &ssh.ClientConfig{
User: "user",
Auth: ssh.AuthMethod{
ssh.Password("pass"),
},
HostKeyCallback: ssh.InsecureIgnoreHostKey(),
}
client, _ := ssh.Dial("tcp", "remotehost:22", config)
defer client.Close()
session, _ := client.NewSession()
defer session.Close()
file, _ := os.Open("filetocopy")
defer file.Close()
stat, _ := file.Stat()
wg := sync.WaitGroup{}
wg.Add(1)
go func() {
hostIn, _ := session.StdinPipe()
defer hostIn.Close()
fmt.Fprintf(hostIn, "C0664 %d %sn", stat.Size(), "filecopyname")
io.Copy(hostIn, file)
fmt.Fprint(hostIn, "x00")
wg.Done()
}()
session.Run("/usr/bin/scp -t /remotedirectory/")
wg.Wait()
Note that I have ignored all errors only for conciseness.
session.StdinPipe()will create a writable pipe for the remote host.
fmt.Fprintf(... "C0664 ...")will signal the start of a file with0664permission,stat.Size()size and the remote filenamefilecopyname.
io.Copy(hostIn, file)will write the contents offileintohostIn.
fmt.Fprint(hostIn, "x00")will signal the end of the file.
session.Run("/usr/bin/scp -qt /remotedirectory/")will run the scp command.
Edit: Added waitgroup per OP's request
If you don't want to go through the trouble of writing this, there are already packages out there that has this functionality: github.com/bramvdbogaerde/go-scp
– ssemilla
Nov 12 at 8:53
I really wanted answer like this. Thanks a lot.
– HowToGo
Nov 12 at 12:35
It doesn't really work for me. It creates the file but there is no content inside. I actually realised it's not great to use session with scp within a command. This answer looks more of a copy paste than actual answer. io.Copy does not work. It just finishes because it's inside of the Goroutine otherwise it's left "doing something"
– HowToGo
Nov 12 at 12:57
file with no content?
– HowToGo
Nov 12 at 13:02
io.Copy spins forever
– HowToGo
Nov 12 at 13:02
|
show 3 more comments
Here is a minimal example on how to use Go as an scp client:
config := &ssh.ClientConfig{
User: "user",
Auth: ssh.AuthMethod{
ssh.Password("pass"),
},
HostKeyCallback: ssh.InsecureIgnoreHostKey(),
}
client, _ := ssh.Dial("tcp", "remotehost:22", config)
defer client.Close()
session, _ := client.NewSession()
defer session.Close()
file, _ := os.Open("filetocopy")
defer file.Close()
stat, _ := file.Stat()
wg := sync.WaitGroup{}
wg.Add(1)
go func() {
hostIn, _ := session.StdinPipe()
defer hostIn.Close()
fmt.Fprintf(hostIn, "C0664 %d %sn", stat.Size(), "filecopyname")
io.Copy(hostIn, file)
fmt.Fprint(hostIn, "x00")
wg.Done()
}()
session.Run("/usr/bin/scp -t /remotedirectory/")
wg.Wait()
Note that I have ignored all errors only for conciseness.
session.StdinPipe()will create a writable pipe for the remote host.
fmt.Fprintf(... "C0664 ...")will signal the start of a file with0664permission,stat.Size()size and the remote filenamefilecopyname.
io.Copy(hostIn, file)will write the contents offileintohostIn.
fmt.Fprint(hostIn, "x00")will signal the end of the file.
session.Run("/usr/bin/scp -qt /remotedirectory/")will run the scp command.
Edit: Added waitgroup per OP's request
If you don't want to go through the trouble of writing this, there are already packages out there that has this functionality: github.com/bramvdbogaerde/go-scp
– ssemilla
Nov 12 at 8:53
I really wanted answer like this. Thanks a lot.
– HowToGo
Nov 12 at 12:35
It doesn't really work for me. It creates the file but there is no content inside. I actually realised it's not great to use session with scp within a command. This answer looks more of a copy paste than actual answer. io.Copy does not work. It just finishes because it's inside of the Goroutine otherwise it's left "doing something"
– HowToGo
Nov 12 at 12:57
file with no content?
– HowToGo
Nov 12 at 13:02
io.Copy spins forever
– HowToGo
Nov 12 at 13:02
|
show 3 more comments
Here is a minimal example on how to use Go as an scp client:
config := &ssh.ClientConfig{
User: "user",
Auth: ssh.AuthMethod{
ssh.Password("pass"),
},
HostKeyCallback: ssh.InsecureIgnoreHostKey(),
}
client, _ := ssh.Dial("tcp", "remotehost:22", config)
defer client.Close()
session, _ := client.NewSession()
defer session.Close()
file, _ := os.Open("filetocopy")
defer file.Close()
stat, _ := file.Stat()
wg := sync.WaitGroup{}
wg.Add(1)
go func() {
hostIn, _ := session.StdinPipe()
defer hostIn.Close()
fmt.Fprintf(hostIn, "C0664 %d %sn", stat.Size(), "filecopyname")
io.Copy(hostIn, file)
fmt.Fprint(hostIn, "x00")
wg.Done()
}()
session.Run("/usr/bin/scp -t /remotedirectory/")
wg.Wait()
Note that I have ignored all errors only for conciseness.
session.StdinPipe()will create a writable pipe for the remote host.
fmt.Fprintf(... "C0664 ...")will signal the start of a file with0664permission,stat.Size()size and the remote filenamefilecopyname.
io.Copy(hostIn, file)will write the contents offileintohostIn.
fmt.Fprint(hostIn, "x00")will signal the end of the file.
session.Run("/usr/bin/scp -qt /remotedirectory/")will run the scp command.
Edit: Added waitgroup per OP's request
Here is a minimal example on how to use Go as an scp client:
config := &ssh.ClientConfig{
User: "user",
Auth: ssh.AuthMethod{
ssh.Password("pass"),
},
HostKeyCallback: ssh.InsecureIgnoreHostKey(),
}
client, _ := ssh.Dial("tcp", "remotehost:22", config)
defer client.Close()
session, _ := client.NewSession()
defer session.Close()
file, _ := os.Open("filetocopy")
defer file.Close()
stat, _ := file.Stat()
wg := sync.WaitGroup{}
wg.Add(1)
go func() {
hostIn, _ := session.StdinPipe()
defer hostIn.Close()
fmt.Fprintf(hostIn, "C0664 %d %sn", stat.Size(), "filecopyname")
io.Copy(hostIn, file)
fmt.Fprint(hostIn, "x00")
wg.Done()
}()
session.Run("/usr/bin/scp -t /remotedirectory/")
wg.Wait()
Note that I have ignored all errors only for conciseness.
session.StdinPipe()will create a writable pipe for the remote host.
fmt.Fprintf(... "C0664 ...")will signal the start of a file with0664permission,stat.Size()size and the remote filenamefilecopyname.
io.Copy(hostIn, file)will write the contents offileintohostIn.
fmt.Fprint(hostIn, "x00")will signal the end of the file.
session.Run("/usr/bin/scp -qt /remotedirectory/")will run the scp command.
Edit: Added waitgroup per OP's request
edited Nov 12 at 13:21
answered Nov 12 at 8:52
ssemilla
3,077424
3,077424
If you don't want to go through the trouble of writing this, there are already packages out there that has this functionality: github.com/bramvdbogaerde/go-scp
– ssemilla
Nov 12 at 8:53
I really wanted answer like this. Thanks a lot.
– HowToGo
Nov 12 at 12:35
It doesn't really work for me. It creates the file but there is no content inside. I actually realised it's not great to use session with scp within a command. This answer looks more of a copy paste than actual answer. io.Copy does not work. It just finishes because it's inside of the Goroutine otherwise it's left "doing something"
– HowToGo
Nov 12 at 12:57
file with no content?
– HowToGo
Nov 12 at 13:02
io.Copy spins forever
– HowToGo
Nov 12 at 13:02
|
show 3 more comments
If you don't want to go through the trouble of writing this, there are already packages out there that has this functionality: github.com/bramvdbogaerde/go-scp
– ssemilla
Nov 12 at 8:53
I really wanted answer like this. Thanks a lot.
– HowToGo
Nov 12 at 12:35
It doesn't really work for me. It creates the file but there is no content inside. I actually realised it's not great to use session with scp within a command. This answer looks more of a copy paste than actual answer. io.Copy does not work. It just finishes because it's inside of the Goroutine otherwise it's left "doing something"
– HowToGo
Nov 12 at 12:57
file with no content?
– HowToGo
Nov 12 at 13:02
io.Copy spins forever
– HowToGo
Nov 12 at 13:02
If you don't want to go through the trouble of writing this, there are already packages out there that has this functionality: github.com/bramvdbogaerde/go-scp
– ssemilla
Nov 12 at 8:53
If you don't want to go through the trouble of writing this, there are already packages out there that has this functionality: github.com/bramvdbogaerde/go-scp
– ssemilla
Nov 12 at 8:53
I really wanted answer like this. Thanks a lot.
– HowToGo
Nov 12 at 12:35
I really wanted answer like this. Thanks a lot.
– HowToGo
Nov 12 at 12:35
It doesn't really work for me. It creates the file but there is no content inside. I actually realised it's not great to use session with scp within a command. This answer looks more of a copy paste than actual answer. io.Copy does not work. It just finishes because it's inside of the Goroutine otherwise it's left "doing something"
– HowToGo
Nov 12 at 12:57
It doesn't really work for me. It creates the file but there is no content inside. I actually realised it's not great to use session with scp within a command. This answer looks more of a copy paste than actual answer. io.Copy does not work. It just finishes because it's inside of the Goroutine otherwise it's left "doing something"
– HowToGo
Nov 12 at 12:57
file with no content?
– HowToGo
Nov 12 at 13:02
file with no content?
– HowToGo
Nov 12 at 13:02
io.Copy spins forever
– HowToGo
Nov 12 at 13:02
io.Copy spins forever
– HowToGo
Nov 12 at 13:02
|
show 3 more comments
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Some of your past answers have not been well-received, and you're in danger of being blocked from answering.
Please pay close attention to the following guidance:
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53256373%2fsending-file-over-ssh-in-go%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
1
You can use github.com/bramvdbogaerde/go-scp
– Ullaakut
Nov 12 at 7:38