搜尋
首頁後端開發Golang關於用golang封裝ssh用於在遠端主機上執行命令,上傳或下載文件

下面由golang教學欄位介紹給大家介紹用golang封裝ssh用於在遠端主機上執行指令,上傳或下載文件,希望對需要的朋友有所幫助!

關於用golang封裝ssh用於在遠端主機上執行命令,上傳或下載文件

python中可以paramiko實現在遠端主機上執行命令,上傳和下載文件,用go也可以封裝一個,在go中用ssh就sftp包可以實現,實現了下面的功能

  • 在遠端主機執行命令返回結果、返回值
  • #上傳和下載檔案遠端主機上,以及傳輸了多少個位元組

認證方式

  • 如果指定了密碼,那麼採用使用者密碼的方式認證,否則採用使用者密碼鍵的方式
    • 如果沒有指定用戶,則預設使用目前的用戶
  • 如果沒有指定密碼,將採用用戶秘鑰方式,預設取~/.ssh/id_rsa檔案私鑰檔案取得秘鑰
    和paramik類似

直接上程式碼

package mainimport (
    "errors"
    "fmt"
    "github.com/pkg/sftp"
    "golang.org/x/crypto/ssh"
    "io"
    "io/ioutil"
    "log"
    "os"
    "os/user"
    "time")var (
    DefaultSShTcpTimeout = 15 * time.Second   // 与ssh建立连接的默认时间,自己设置一个就行)// 错误定义var (
    InvalidHostName = errors.New("invalid parameters: hostname is empty")
    InvalidPort     = errors.New("invalid parameters: port must be range 0 ~ 65535"))// 返回当前用户名func getCurrentUser() string {
    user, _ := user.Current()
    return user.Username}// 存放上传或下载的信息type TransferInfo struct {
    Kind         string   // upload或download
    Local        string   // 本地路径
    Dst          string   // 目标路径
    TransferByte int64    // 传输的字节数(byte)}func (t *TransferInfo) String()  string {
    return fmt.Sprintf(`TransforInfo(Kind:"%s", Local: "%s", Dst: "%s", TransferByte: %d)`,
        t.Kind, t.Local, t.Dst, t.TransferByte)}// 存放执行结果的结构体信息type ExecInfo struct {
    Cmd         string
    Output     []byte
    ExitCode int}func (e *ExecInfo) OutputString() string {
    return string(e.Output)}func (e *ExecInfo) String() string {
    return fmt.Sprintf(`ExecInfo(cmd: "%s", exitcode: %d)`,
        e.Cmd, e.ExitCode)}type AuthConfig struct {
    *ssh.ClientConfig
    User     string
    Password string
    KeyFile  string
    Timeout  time.Duration}func (a *AuthConfig) setDefault()  {
    if a.User == "" {
        a.User = getCurrentUser()
    }

    if a.KeyFile == "" {
        userHome, _ := os.UserHomeDir()
        a.KeyFile = fmt.Sprintf("%s/.ssh/id_rsa", userHome)
    }

    if a.Timeout == 0 {
        a.Timeout = DefaultSShTcpTimeout    }}func (a *AuthConfig) SetAuthMethod() (ssh.AuthMethod, error) {
    a.setDefault()
    if a.Password != "" {
        return ssh.Password(a.Password), nil    }
    data, err := ioutil.ReadFile(a.KeyFile)
    if err != nil {
        return nil, err    }
    singer, err := ssh.ParsePrivateKey(data)
    if err != nil {
        return nil, err    }
    return ssh.PublicKeys(singer), nil}func (a *AuthConfig) ApplyConfig() error {
    authMethod, err := a.SetAuthMethod()
    if err != nil {
        return err    }
    a.ClientConfig = &ssh.ClientConfig{
        User: a.User,
        Auth: []ssh.AuthMethod{authMethod},
        HostKeyCallback: ssh.InsecureIgnoreHostKey(),
        Timeout: a.Timeout,
    }
    return nil}// 存放连接的结构体type conn struct {
    client     *ssh.Client
    sftpClient *sftp.Client}func (c *conn) Close()  {
    if c.sftpClient != nil {
        c.sftpClient.Close()
        c.sftpClient = nil    }
    if c.client != nil {
        c.client.Close()
        c.client = nil    }}// SSHClient结构体type SSHClient struct {
    conn
    HostName   string
    Port        int
    AuthConfig AuthConfig}// 设置默认端口信息func (s *SSHClient) setDefaultValue()  {
    if s.Port == 0 {
        s.Port = 22
    }}// 与远程主机连接func (s *SSHClient) Connect() error {
    if s.client != nil {
        log.Println("Already Login")
        return nil    }
    if err := s.AuthConfig.ApplyConfig(); err != nil {
        return err    }
    s.setDefaultValue()
    addr := fmt.Sprintf("%s:%d", s.HostName, s.Port)
    var err error
    s.client, err = ssh.Dial("tcp", addr, s.AuthConfig.ClientConfig)
    if err != nil {
        return err    }
    return nil}// 一个session只能执行一次命令,也就是说不能在同一个session执行多次s.session.CombinedOutput// 如果想执行多次,需要每条为每个命令创建一个session(这里是这样做)func (s *SSHClient) Exec(cmd string) (*ExecInfo, error) {
    session, err := s.client.NewSession()
    if err != nil {
        return nil, err    }
    defer session.Close()
    output, err := session.CombinedOutput(cmd)
    var exitcode int    if err != nil {
        // 断言转成具体实现类型,获取返回值
        exitcode = err.(*ssh.ExitError).ExitStatus()
    }
    return &ExecInfo{
        Cmd: cmd,
        Output: output,
        ExitCode: exitcode,
    }, nil}// 将本地文件上传到远程主机上func (s *SSHClient) Upload(localPath string, dstPath string) (*TransferInfo, error) {
    transferInfo := &TransferInfo{Kind: "upload", Local: localPath, Dst: dstPath, TransferByte: 0}
    var err error    // 如果sftp客户端没有打开,就打开,为了复用
    if s.sftpClient == nil {
        if s.sftpClient, err = sftp.NewClient(s.client); err != nil {
            return transferInfo, err        }
    }
    localFileObj, err := os.Open(localPath)
    if err != nil {
        return transferInfo, err    }
    defer localFileObj.Close()

    dstFileObj, err := s.sftpClient.Create(dstPath)
    if err != nil {
        return transferInfo, err    }
    defer dstFileObj.Close()

    written, err := io.Copy(dstFileObj, localFileObj)
    if err != nil {
        return transferInfo, err    }
    transferInfo.TransferByte = written    return transferInfo, nil}// 从远程主机上下载文件到本地func (s *SSHClient) Download(dstPath string, localPath string)  (*TransferInfo, error) {
    transferInfo := &TransferInfo{Kind: "download", Local: localPath, Dst: dstPath, TransferByte: 0}
    var err error    if s.sftpClient == nil {
        if s.sftpClient, err = sftp.NewClient(s.client); err != nil {
            return transferInfo, err        }
    }
    //defer s.sftpClient.Close()
    localFileObj, err := os.Create(localPath)
    if err != nil {
        return transferInfo, err    }
    defer localFileObj.Close()

    dstFileObj, err := s.sftpClient.Open(dstPath)
    if err != nil {
        return transferInfo, err    }
    defer dstFileObj.Close()

    written, err := io.Copy(localFileObj, dstFileObj)
    if err != nil {
        return transferInfo, err    }
    transferInfo.TransferByte = written    return transferInfo, nil}// SSHclient的构造方法func NewSSHClient(hostname string, port int, authConfig AuthConfig) (*SSHClient, error) {
    switch {
    case hostname == "":
        return nil, InvalidHostName    case port > 65535 || port 

以上是關於用golang封裝ssh用於在遠端主機上執行命令,上傳或下載文件的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述
本文轉載於:learnku。如有侵權,請聯絡admin@php.cn刪除
使用GO編程語言構建可擴展系統使用GO編程語言構建可擴展系統Apr 25, 2025 am 12:19 AM

goisidealforbuildingscalablesystemsduetoitssimplicity,效率和建築物內currencysupport.1)go'scleansyntaxandaxandaxandaxandMinimalisticDesignenhanceProductivityAndRedCoductivityAndRedCuceErr.2)ItSgoroutinesAndInesAndInesAndInesAndineSandChannelsEnablenableNablenableNableNablenableFifficConcurrentscorncurrentprogragrammentworking torkermenticmminging

有效地使用Init功能的最佳實踐有效地使用Init功能的最佳實踐Apr 25, 2025 am 12:18 AM

Initfunctionsingorunautomationbeforemain()andareusefulforsettingupenvorments和InitializingVariables.usethemforsimpletasks,避免使用輔助效果,andbecautiouswithTestingTestingTestingAndLoggingTomaintAnainCodeCodeCodeClarityAndTestesto。

INIT函數在GO軟件包中的執行順序INIT函數在GO軟件包中的執行順序Apr 25, 2025 am 12:14 AM

goinitializespackagesintheordertheordertheyimported,thenexecutesInitFunctionswithinApcageIntheirdeFinityOrder,andfilenamesdetermineTheOrderAcractacractacrosmultiplefiles.thisprocessCanbeCanbeinepessCanbeInfleccessByendercrededBydeccredByDependenciesbetenciesbetencemendencenciesbetnependendpackages,whermayleLeadtocomplexinitialitialializizesizization

在GO中定義和使用自定義接口在GO中定義和使用自定義接口Apr 25, 2025 am 12:09 AM

CustomInterfacesingoarecrucialforwritingFlexible,可維護,andTestableCode.TheyEnableDevelostOverostOcusonBehaviorBeiroveration,增強ModularityAndRobustness.byDefiningMethodSigntulSignatulSigntulSignTypaterSignTyperesthattypesmustemmustemmustemmustemplement,InterfaceSallowForCodeRepodEreusaperia

在GO中使用接口進行模擬和測試在GO中使用接口進行模擬和測試Apr 25, 2025 am 12:07 AM

使用接口進行模擬和測試的原因是:接口允許定義合同而不指定實現方式,使得測試更加隔離和易於維護。 1)接口的隱式實現使創建模擬對像變得簡單,這些對像在測試中可以替代真實實現。 2)使用接口可以輕鬆地在單元測試中替換服務的真實實現,降低測試複雜性和時間。 3)接口提供的靈活性使得可以為不同測試用例更改模擬行為。 4)接口有助於從一開始就設計可測試的代碼,提高代碼的模塊化和可維護性。

在GO中使用init進行包裝初始化在GO中使用init進行包裝初始化Apr 24, 2025 pm 06:25 PM

在Go中,init函數用於包初始化。 1)init函數在包初始化時自動調用,適用於初始化全局變量、設置連接和加載配置文件。 2)可以有多個init函數,按文件順序執行。 3)使用時需考慮執行順序、測試難度和性能影響。 4)建議減少副作用、使用依賴注入和延遲初始化以優化init函數的使用。

GO的選擇語句:多路復用並發操作GO的選擇語句:多路復用並發操作Apr 24, 2025 pm 05:21 PM

go'SselectStatementTreamLinesConcurrentProgrambyMultiplexingOperations.1)itallowSwaitingOnMultipleChannEloperations,執行thefirstreadyone.2)theDefirstreadyone.2)thedefefcasepreventlocksbysbysbysbysbysbythoplocktrograpraproxrograpraprocrecrecectefnoopeready.3)

GO中的高級並發技術:上下文和候補組GO中的高級並發技術:上下文和候補組Apr 24, 2025 pm 05:09 PM

contextancandwaitgroupsarecrucialingoformanaginggoroutineseflect.1)context contextsallowsAllowsAllowsAllowsAllowsAllingCancellationAndDeadLinesAcrossapibiboundaries,確保GoroutinesCanbestoppedGrace.2)WaitGroupsSynChronizeGoroutines,確保Allimizegoroutines,確保AllizeNizeGoROutines,確保AllimizeGoroutines

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser是一個安全的瀏覽器環境,安全地進行線上考試。該軟體將任何電腦變成一個安全的工作站。它控制對任何實用工具的訪問,並防止學生使用未經授權的資源。

PhpStorm Mac 版本

PhpStorm Mac 版本

最新(2018.2.1 )專業的PHP整合開發工具

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

這個專案正在遷移到osdn.net/projects/mingw的過程中,你可以繼續在那裡關注我們。 MinGW:GNU編譯器集合(GCC)的本機Windows移植版本,可自由分發的導入函式庫和用於建置本機Windows應用程式的頭檔;包括對MSVC執行時間的擴展,以支援C99功能。 MinGW的所有軟體都可以在64位元Windows平台上運作。

MantisBT

MantisBT

Mantis是一個易於部署的基於Web的缺陷追蹤工具,用於幫助產品缺陷追蹤。它需要PHP、MySQL和一個Web伺服器。請查看我們的演示和託管服務。

VSCode Windows 64位元 下載

VSCode Windows 64位元 下載

微軟推出的免費、功能強大的一款IDE編輯器