In recent years, Golang has gradually become popular in the development field. Its simple and efficient syntax structure, good concurrency performance and out-of-the-box standard library make it the preferred language for many developers.
In network security, the SSH protocol is a commonly used encryption protocol that can protect the security of sensitive data during network transmission. In many fields, such as server management, operation and maintenance personnel often need to use SSH to connect to the server for operations. This article will describe how to write an SSH client using Golang.
SSH is the abbreviation of Secure Shell, which is a network protocol used to provide a secure transmission channel for network services in an insecure network. SSH supports functions such as remote command execution, file transfer, and TCP/IP tunneling.
The SSH protocol has two versions, namely SSH-1 and SSH-2, the latter is the latest version. SSH-2 includes the following parts:
In the SSH protocol, a three-way handshake process is required between the client and the server to establish a connection. After a successful handshake, both parties negotiate which encryption, authentication, and compression algorithms to use. Once negotiation is complete, communications are encrypted, ensuring data security.
In Golang, we can use the official library golang.org/x/crypto/ssh
to implement SSH client connection and operation.
To connect to the server, we need to first create an SSH client. This can be achieved by creating a ssh.Client
.
config := &ssh.ClientConfig{ User: "root", Auth: []ssh.AuthMethod{ ssh.Password("password"), }, HostKeyCallback: ssh.InsecureIgnoreHostKey(), } addr := "example.com:22" client, err := ssh.Dial("tcp", addr, config) if err != nil { log.Fatal("Failed to dial: ", err) } defer client.Close()
In the above code, config
defines the configuration information of the client, including user name, password and host address, etc. The HostKeyCallback
parameter is used to specify the certificate verification callback function. Here we use the ssh.InsecureIgnoreHostKey()
function to skip certificate verification. The
Dial
function is used to establish a connection, where tcp
indicates using the TCP/IP protocol to connect, addr
is the server address, config
is the client’s configuration information.
After the connection is successful, we can use ssh.Session
to execute the command. ssh.Session
is a session, similar to an interactive terminal, on which commands can be executed.
session, err := client.NewSession() if err != nil { log.Fatal("Failed to create session: ", err) } defer session.Close() var b bytes.Buffer session.Stdout = &b if err := session.Run("ls -l"); err != nil { log.Fatal("Failed to run: " + err.Error()) } fmt.Println(b.String())
In the above code, we create a new ssh.Session
object and use the client.NewSession()
function to implement it. We direct the standard output to a bytes.Buffer
object to later output the results of executing the command.
Use the session.Run("ls -l")
function to execute the command. If the execution is successful, the results will be written to standard output. Finally, we output the command execution results.
The SSH client can also use the sftp
protocol for file transfer. We can use the ssh.Client.NewSFTP()
function to create a sftp
client.
sftp, err := client.NewSFTP() if err != nil { log.Fatal("Failed to create SFTP client: ", err) } defer sftp.Close()
In the above code, we create a new ssh.SFTP
object and use the client.NewSFTP()
function to implement it.
Next, we can use the sftp
client to upload and download files.
localFile := "/path/to/local/file" remoteFile := "/path/to/remote/file" // 上传文件 srcFile, err := os.Open(localFile) if err != nil { log.Fatal("Failed to open local file: ", err) } defer srcFile.Close() dstFile, err := sftp.Create(remoteFile) if err != nil { log.Fatal("Failed to create remote file: ", err) } defer dstFile.Close() if _, err := io.Copy(dstFile, srcFile); err != nil { log.Fatal("Failed to upload file: ", err) } // 下载文件 remoteFile := "/path/to/remote/file" localFile := "/path/to/local/file" srcFile, err := sftp.Open(remoteFile) if err != nil { log.Fatal("Failed to open remote file: ", err) } defer srcFile.Close() dstFile, err := os.Create(localFile) if err != nil { log.Fatal("Failed to create local file: ", err) } defer dstFile.Close() if _, err := io.Copy(dstFile, srcFile); err != nil { log.Fatal("Failed to download file: ", err) }
In the code for uploading files, we first open the local file and the remote file, then use the sftp.Create()
function to create the remote file, and write the contents of the local file to the remote file .
In the code for downloading files, we first open the remote file and the local file, then use the sftp.Open()
function to open the remote file and write the contents of the remote file to the local file.
This article introduces how to use Golang to write an SSH client to implement functions such as connecting to the server, executing commands, and uploading and downloading files. Of course, this is just a simple example, and more operations and processing may be required in actual applications. I hope readers can understand and master the use of SSH clients in Golang through sharing this article.
The above is the detailed content of ssh implemented by golang. For more information, please follow other related articles on the PHP Chinese website!