1、go语言通过ssh连接远程服务器执行命令

2、go语言通过sftp连接远程服务器上传和下载文件

3、相关依赖

github.com/pkg/sftp 
golang.org/x/crypto/ssh
github.com/pkg/errors

4、所有代码展示

package controllersimport ("github.com/astaxie/beego""github.com/pkg/sftp""github.com/astaxie/beego/logs""golang.org/x/crypto/ssh""net""os""path"
)
//根据ip获取sftpClient
func getSftpClientByIp(ip string) (*sftp.Client) {logs.Info(ip)return getSftpClientBySshClient(getSshClientByIp(ip))
}//根据sshClient获取sftpClient
func getSftpClientBySshClient(client *ssh.Client) (*sftp.Client) {var (sftpClient   *sftp.Clienterr error)// create sftp clientif sftpClient, err = sftp.NewClient(client); err != nil {logs.Error("Failed to NewClient: ", err)panic(err)}return sftpClient
}//根据ip获取sshClient
func getSshClientByIp(ip string) (*ssh.Client) {config := &ssh.ClientConfig{User: beego.AppConfig.String("linuxUserName"),Auth: []ssh.AuthMethod{ssh.Password(beego.AppConfig.String("linuxPwd")),},//需要验证服务端,不做验证返回nil就可以,点击HostKeyCallback看源码就知道了HostKeyCallback: func(hostname string, remote net.Addr, key ssh.PublicKey) error {return nil},}client, err := ssh.Dial("tcp", ip + ":" + beego.AppConfig.String("linuxPort"), config)if err != nil {logs.Error("Failed to dial: ", err)panic(err)}return client
}//上传文件
func uploadFile(ip string, localFilePath string, remoteDir string) {sftpClient := getSftpClientByIp(ip)defer sftpClient.Close()srcFile, err := os.Open(localFilePath)if err != nil {logs.Error("Failed to open file : ", err)panic(err)}defer srcFile.Close()var remoteFileName = path.Base(localFilePath)dstFile, err := sftpClient.Create(path.Join(remoteDir, remoteFileName))if err != nil {logs.Error("Failed to create file : ", err)panic(err)}defer dstFile.Close()buf := make([]byte, 1024)for {n, _ := srcFile.Read(buf)if n == 0 {break}dstFile.Write(buf)}logs.Info("copy file to remote server finished!")
}
//下载文件
func downFile(ip string, remoteFilePath string, localDir string) {client := getSshClientByIp(ip)session, err := client.NewSession()if err != nil {logs.Error("Failed to NewSession : ", err)panic(err)}defer session.Close()session.Run("gzip " + remoteFilePath)remoteFilePathGz := remoteFilePath + ".gz";sftpClient := getSftpClientBySshClient(client)defer sftpClient.Close()    // 用来测试的远程文件路径 和 本地文件夹srcFile, err := sftpClient.Open(remoteFilePathGz)if err != nil {logs.Error("Failed to Open file : ", err)panic(err)}defer srcFile.Close()var localFileName = path.Base(remoteFilePathGz)dstFile, err := os.Create(path.Join(localDir, localFileName))if err != nil {logs.Error("Failed to Create file : ", err)panic(err)}defer dstFile.Close()if _, err = srcFile.WriteTo(dstFile); err != nil {logs.Error("Failed to write file : ", err)panic(err)}session.Run("rm -rf " + remoteFilePathGz)
}
// @router /server/log/down [get]
func (c *ServerLogController) Get() {downFile("192.168.31.116","/home/wlogs/catalina_20180720.log","e:/tmp/")logs.Info("copy file to remote server finished!")c.ServeJSON()c.StopRun()return
}
// @router /publish/upload [get]
func (c *PublishController) UploadPublish() {var localFilePath = "E:/yumengyao/Desktop/hl-p-loans-realname01_catalina_20180720.log/data/tomcat-app/logs/catalina_20180720.log"var remoteDir = "/home/wlogs/"uploadFile("192.168.31.116",localFilePath,remoteDir)logs.Info("copy file to remote server finished!")c.ServeJSON()c.StopRun()return
}

go语言连接远程服务器相关推荐

  1. 易语言远程查询oracle数据库连接,易语言如何连接远程服务器上的数据库,并读取数据...

    标签: 用易语言来连接远程服务器上的数据库,可以使用支持库中的方法. 连接数据库方法名: 连接mysql(服务器地址,用户名,密码,数据库名,端口号) 注意:连接mysql()这个方法名,如果没有,单 ...

  2. 跳板机连接linux服务器,linux通过跳板机连接远程服务器并进行文件传输的方法...

    linux通过跳板机连接远程服务器并进行文件传输的方法 最近在linux主机上部署环境时,遇到了很多问题,第一个就是通过跳板机远程连接服务器传输文件的问题. 看了很多网上的解决办法,大部分就是说用Se ...

  3. pycharm连接远程服务器并进行代码上传+远程调试

    Pycharm连接远程服务器并进行代码上传+远程调试 </h1><div class="clear"></div><div class=& ...

  4. 连接远程服务器CredSSP加密Oracle修正报错解决办法

    连接远程服务器CredSSP加密Oracle修正报错解决办法: 打开注册表,快捷输入 "regedit"(类似找命令提示符 输入 cmd 一样)找文件夹 路径:HKLM(缩写)\S ...

  5. ssh免密连接远程服务器

    ssh免密连接远程服务器 借助ssky-keygen和ssh-copy-id工具,通过4个简单的步骤实现无需输入密码登录远程Linux主机 1 生成密钥 通过内置的工具生成RSA算法加密的密钥 ssh ...

  6. pycharm连接远程服务器

    pycharm连接远程服务器 文章目录 pycharm连接远程服务器 pycharm工具栏:Tools-->Deployment-->Configuration![ 左上角:点击+加号-- ...

  7. xshell如何登陆数据库_Xshell连接远程服务器和操作数据库

    (1)连接服务器的操作: 打开xshell,连接远程服务器: 填好主机地址,点击确定后:跳到会话页面,点击连接:输入登陆的用户名(用户必须经过授权后才能登陆),进入身份验证页面:用户密钥一般会自动生成 ...

  8. Pycharm连接远程服务器进行代码调试开发

    点击上方"AI搞事情"关注我们 在工作中,我们经常会在linux服务器上做开发,另外GPU显卡也基本都装在性能更好便于团队共用的服务器上,这个时候我们就会用到服务器上的Python ...

  9. 工具SSHSecure连接远程服务器步骤

    一.远程连接工具SSHSecure的使用 实际开发中,Linux服务器都在其他的地方,我们要通过远程的方式去连接远程linux系统并操作它,Linux远程的操作工具有很多,企业中常用的有Puttty. ...

最新文章

  1. ONNX 实时graph优化方法
  2. 软件测试培训适合什么人学习?
  3. 推荐一款神级 API 接口管理神器
  4. Linux C编程--线程操作3--线程属性解析
  5. html5后代选择符,css选择符有哪些?哪些属性可以继承?
  6. linux随机数示例:随机产生以139开头的电话号码
  7. 归属地的判断规则有吗_IPO|创业板注册制规则-详解股权激励新规
  8. WEBBASE篇: 第八篇, JavaScript知识2
  9. Nginx+Tomcat windows环境下简单集群搭建
  10. Acwing 307. 连通图
  11. wordpress主题ajax,为自制WordPress主题/插件的后台设置页面添加ajax支持
  12. php+mysql执行sql文件路径_PHP———MySQL笔记(5)之MySQL数据库导出导入sql文件(详细)...
  13. Windows下对文件做MD5校验
  14. android nanohttp,在Android中使用NanoHTTPD
  15. linux上的smartsvn图形客户端,linux 下svn图形客户端smartsvn 安装
  16. 地图制作:Google Earth Pro的下载及功能介绍(详细介绍)(上)
  17. 落户杭州难不难!入户杭州超全办理细则来了!想落户杭州的赶紧看
  18. 【日记】python获取公众号的全部文章并截取图导出
  19. selenium录屏python_Selenium实现录屏的一种方法
  20. 重磅!Amazon发布个人免费的AI编程助手:CodeWhisperer !

热门文章

  1. 妹子图APP(一)—— Retrofit+Glide+Gson加载网络图片
  2. Jmeter 测试12306 获取火车票订单接口
  3. Science Advances:社会和健康科学中用于描述、预测和因果推理的机器学习方法
  4. 野蔷薇的伤感人生日志:已失落于尘埃,再也找寻不得
  5. centos/redhat kernel-debug-info-xx.rpm与kernel-debuginfo-xx.rpm区别
  6. 仿微信朋友圈图片点击放大效果
  7. 微信小程序实现朋友圈图片展现形式
  8. ie 11 打印 iframe 404 降级解决方案
  9. 宿舍管理程序c语言,学生宿舍管理软件C语言源代码完整版
  10. 15、Kanzi插件——通过Kanzi Engine插件创建自定义消息类型+代码解析