Sending file over SSH in go












-1














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.










share|improve this question


















  • 1




    You can use github.com/bramvdbogaerde/go-scp
    – Ullaakut
    Nov 12 at 7:38
















-1














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.










share|improve this question


















  • 1




    You can use github.com/bramvdbogaerde/go-scp
    – Ullaakut
    Nov 12 at 7:38














-1












-1








-1







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.










share|improve this question













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.







go ssh






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Nov 12 at 5:29









HowToGo

827




827








  • 1




    You can use github.com/bramvdbogaerde/go-scp
    – Ullaakut
    Nov 12 at 7:38














  • 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












1 Answer
1






active

oldest

votes


















1














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.





  1. session.StdinPipe() will create a writable pipe for the remote host.


  2. fmt.Fprintf(... "C0664 ...") will signal the start of a file with 0664 permission, stat.Size() size and the remote filename filecopyname.


  3. io.Copy(hostIn, file) will write the contents of file into hostIn.


  4. fmt.Fprint(hostIn, "x00") will signal the end of the file.


  5. session.Run("/usr/bin/scp -qt /remotedirectory/") will run the scp command.


Edit: Added waitgroup per OP's request






share|improve this answer























  • 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











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
});


}
});














draft saved

draft discarded


















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









1














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.





  1. session.StdinPipe() will create a writable pipe for the remote host.


  2. fmt.Fprintf(... "C0664 ...") will signal the start of a file with 0664 permission, stat.Size() size and the remote filename filecopyname.


  3. io.Copy(hostIn, file) will write the contents of file into hostIn.


  4. fmt.Fprint(hostIn, "x00") will signal the end of the file.


  5. session.Run("/usr/bin/scp -qt /remotedirectory/") will run the scp command.


Edit: Added waitgroup per OP's request






share|improve this answer























  • 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
















1














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.





  1. session.StdinPipe() will create a writable pipe for the remote host.


  2. fmt.Fprintf(... "C0664 ...") will signal the start of a file with 0664 permission, stat.Size() size and the remote filename filecopyname.


  3. io.Copy(hostIn, file) will write the contents of file into hostIn.


  4. fmt.Fprint(hostIn, "x00") will signal the end of the file.


  5. session.Run("/usr/bin/scp -qt /remotedirectory/") will run the scp command.


Edit: Added waitgroup per OP's request






share|improve this answer























  • 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














1












1








1






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.





  1. session.StdinPipe() will create a writable pipe for the remote host.


  2. fmt.Fprintf(... "C0664 ...") will signal the start of a file with 0664 permission, stat.Size() size and the remote filename filecopyname.


  3. io.Copy(hostIn, file) will write the contents of file into hostIn.


  4. fmt.Fprint(hostIn, "x00") will signal the end of the file.


  5. session.Run("/usr/bin/scp -qt /remotedirectory/") will run the scp command.


Edit: Added waitgroup per OP's request






share|improve this answer














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.





  1. session.StdinPipe() will create a writable pipe for the remote host.


  2. fmt.Fprintf(... "C0664 ...") will signal the start of a file with 0664 permission, stat.Size() size and the remote filename filecopyname.


  3. io.Copy(hostIn, file) will write the contents of file into hostIn.


  4. fmt.Fprint(hostIn, "x00") will signal the end of the file.


  5. session.Run("/usr/bin/scp -qt /remotedirectory/") will run the scp command.


Edit: Added waitgroup per OP's request







share|improve this answer














share|improve this answer



share|improve this answer








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


















  • 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


















draft saved

draft discarded




















































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.




draft saved


draft discarded














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





















































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







Popular posts from this blog

The Sandy Post

Danny Elfman

Pages that link to "Head v. Amoskeag Manufacturing Co."