How to implement remote execution commands using the Go language _golang

Source: Internet
Author: User

Objective

What is the use of remote command execution? Why do you want to execute commands remotely? If you only have 2, 3 servers need to be managed, remote execution commands do not have much effect, you can log on to each server to complete a variety of operations. When your server is larger than 3, the way commands are executed remotely can greatly increase your productivity.

If you have a tool that can execute commands remotely, you can operate multiple machines like a single machine, with more machines and more efficiency. The most common way to execute commands remotely is to use the SSH protocol to send commands to a remote machine for execution and to get the results returned.

General commands

A general order is a command that will be executed within a certain period of time. such as grep, Cat, and so on. The steps to execute a command are: Connect, execute, get the result

Connection

The connection includes authentication and can be authenticated using either password or Sshkey 2 ways. The following example completes the connection using a password authentication method for simplicity.

Import ( 
 "FMT"
 "Time" "

 golang.org/x/crypto/ssh"
)

func Connect (user, password, host string, port int) (*SSH. Session, Error) { 
 var (
 auth  []ssh). Authmethod
 addr  string
 clientconfig *ssh. ClientConfig
 client *ssh. Client session
 *ssh. Session
 Err  error
 ]
 //Get Auth method
 auth = make ([]ssh. Authmethod, 0)
 auth = append (auth, ssh. Password (Password))

 ClientConfig = &ssh. clientconfig{
 User:user,
 auth:auth,
 timeout:30 * time. Second,
 }

 //connet to ssh
 addr = fmt. Sprintf ("%s:%d", host, port)

 if client, err = ssh. Dial ("TCP", addr, ClientConfig); Err!= Nil {return
 nil, err
 }

 //Create sessions
 if session, Err = client. NewSession (); Err!= Nil {return
 nil, err
 } return session

 , nil
}

The connection method is very simple, as long as the user login to the host *, * password *, * host name or ip*, *ssh port

Execute, Command get results

When the connection succeeds, it's easy to execute the command

Import ( 
 "FMT"
 "Log"
 "OS" "Time
 "

 "Golang.org/x/crypto/ssh"
)

func main () { 
 Session, Err: = Connect ("root", "xxxxx", "127.0.0.1",)
 if err!= nil {
 log. Fatal (Err)
 }
 defer session. Close () session

 . Run ("LS/; Ls/abc ")
}

After the above code runs, although the command executes normally, there is no result of the normal output and no abnormal output. To display the results, you need to modify the session's Stdout and Stderr redirection func main as follows:

Func Main () {session 
 , err: = Connect ("root", "xxxxx", "127.0.0.1",)
 if err!= nil {
 log. Fatal (Err)
 }
 defer session. Close () session

 . Stdout = OS. Stdout session
 . Stderr = OS. Stderr session
 . Run ("LS/; Ls/abc ")
}

This will enable the display of normal, abnormal information on the screen.

Interactive commands

The above method cannot remotely execute interactive commands, such as top, to edit a file remotely, for example, vi /etc/nginx/nginx.conf if you want to support interactive commands, you need the current terminal to take over the remote PTY.

Func Main () {session 
 , err: = Connect ("root", "Olordjesus", "Dockers.iotalabs.io", 2210)
 If err!= nil {
 LOG.F Atal (err)
 }
 defer session. Close ()

 FD: = Int (OS. STDIN.FD ())
 oldstate, err: = Terminal. Makeraw (FD)
 If err!= nil {
 panic (err)
 }
 defer terminal. Restore (FD, oldstate)

 //excute command session
 . Stdout = OS. Stdout session
 . Stderr = OS. Stderr session
 . Stdin = OS. Stdin

 termwidth, termheight, err: = Terminal. GetSize (FD)
 If err!= nil {
 panic (err)
 }

 //Set up terminal modes modes
 : = SSH. terminalmodes{
 ssh. ECHO:  1,//enable echoing
 ssh. tty_op_ispeed:14400,//input speed = 14.4kbaud
 ssh. tty_op_ospeed:14400,//output Speed = 14.4kbaud
 }

 //Request pseudo terminal
 If err: = Session. Requestpty ("Xterm-256color", Termheight, Termwidth, modes); Err!= nil {
 log. Fatal (ERR)
 } session

 . Run ("Top")
}

Summarize

OK, so that you can perform interactive commands, such as the top above can also edit files remotely by using commands such as the vi/etc/nginx/nignx.conf . The above is how to use the Go language to implement the entire content of remote command, I hope this article will help you learn python.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.