Go执行远程ssh命令
使用包:golang.org/x/crypto/ssh
以下封装一个发送命令的Cli结构体
package utils import (
"fmt"
"golang.org/x/crypto/ssh"
"golang.org/x/crypto/ssh/terminal"
"io"
"net"
"os"
"time"
) type Cli struct {
IP string //IP地址
Username string //用户名
Password string //密码
Port int //端口号
client *ssh.Client //ssh客户端
LastResult string //最近一次Run的结果
} //创建命令行对象
//@param ip IP地址
//@param username 用户名
//@param password 密码
//@param port 端口号,默认22
func New(ip string, username string, password string, port ...int) *Cli {
cli := new(Cli)
cli.IP = ip
cli.Username = username
cli.Password = password
if len(port) <= 0 {
cli.Port = 22
} else {
cli.Port = port[0]
}
return cli
} //执行shell
//@param shell shell脚本命令
func (c Cli) Run(shell string) (string, error) {
if c.client == nil {
if err := c.connect(); err != nil {
return "", err
}
}
session, err := c.client.NewSession()
if err != nil {
return "", err
}
defer session.Close()
buf, err := session.CombinedOutput(shell) c.LastResult = string(buf)
return c.LastResult, err
}
//连接
func (c *Cli) connect() error {
config := ssh.ClientConfig{
User: c.Username,
Auth: []ssh.AuthMethod{ssh.Password(c.Password)},
HostKeyCallback: func(hostname string, remote net.Addr, key ssh.PublicKey) error {
return nil
},
Timeout: 10 * time.Second,
}
addr := fmt.Sprintf("%s:%d", c.IP, c.Port)
sshClient, err := ssh.Dial("tcp", addr, &config)
if err != nil {
return err
}
c.client = sshClient
return nil
}
测试执行shell代码
cli := New("IP", "用户名", "密码", 端口号)
output, err := cli.Run("free -h")
fmt.Printf("%v\n%v", output, err)
还有类似top或者vim的命令是需要交互的,可以利用包golang.org/x/crypto/ssh/terminal实现
再封装一个方法RunTerminal
//执行带交互的命令
func (c *Cli) RunTerminal(shell string, stdout, stderr io.Writer) error {
if c.client == nil {
if err := c.connect(); err != nil {
return err
}
}
session, err := c.client.NewSession()
if err != nil {
return err
}
defer session.Close() fd := int(os.Stdin.Fd())
oldState, err := terminal.MakeRaw(fd)
if err != nil {
panic(err)
}
defer terminal.Restore(fd, oldState) session.Stdout = stdout
session.Stderr = 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 {
return err
} session.Run(shell)
return nil
}
测试RunTerminal方法
cli := New("IP", "用户名", "密码", 端口号)
cli.RunTerminal("top", os.Stdout, os.Stdin)
Go执行远程ssh命令的更多相关文章
- Teamviewer远程ssh命令行更改密码启动
Teamviewer远程ssh命令行更改密码启动 设置密码 $ sudo teamviewer passwd [NewPasswd ] 查看teamviewer信息 $ teamviewer info ...
- 在Jenkins中配置执行远程shell命令
1.想要 远程登录到linux服务器并执行相应的shell脚本,需要在jenkins上安装插件enkins SSH plugin 2. 安装了这个插件后,进入系统的配置管理中配置 SSH remote ...
- jenkins 执行远程linux命令
在Jenkins中进行构建时,可能需要首先SSH登录到一个远程服务器以执行必要的脚本,然后再执行构建.这时,需要安装SSH Plugin,并进行如下配置.1.在Jenkins界面,系统管理->管 ...
- 在Jenkins中配置执行远程shell命令(转)
用过Jenkins的都知道,在Build配置那里有1个Add buld step, 有这样两个选项: 1. Execute Windows batch command 2. Execute shell ...
- Jenkins执行 remote SSH 命令
1.安装 SSH Pipeline Steps 插件 2.在凭据中添加remote server凭据,如下 3.Pipeline编写: def GetRemoteServer(ip){ def rem ...
- Jenkin配置执行远程shell命令
转载自 http://www.cnblogs.com/parryyang/p/6261730.html 在利用jenkins进行集成化部署的时候,我们在部署生成的war包时,往往需要进行一些备份,或者 ...
- ubuntu 下非交互式执行远程shell命令
apt-get install sshpass sshpass -p **your_password** ssh -o StrictHostKeyChecking=no "root@$ip& ...
- linux利用ssh远程执行多台机器执行同样的命令
这篇文章主要介绍了ssh远程执行命令方法和Shell脚本实例,本文讲解了ssh执行远程操作方法和远程执行命令shell脚本示例,需要的朋友可以参考下 ssh执行远程操作命令格式代码如下: ssh -t ...
- Ubuntu 14.10 下SSH执行远程命令
有些时候需要在远程机器上执行命令,如果每次都等进去挺麻烦的,所以用脚本执行会方便很多.下面介绍一下在shell脚本中执行远程命令. 1,首先写好要运行的脚本 run-command.sh, 加上执行权 ...
随机推荐
- windows环境Caffe安装配置步骤(无GPU)及mnist训练
在硕士第二年,义无反顾地投身到了深度学习的浪潮中.从之前的惯性导航转到这个方向,一切从头开始,在此,仅以此文记录自己的打怪之路. 最初的想法是动手熟悉Caffe,考虑到直接上手Ubuntu会有些难度, ...
- MacBook 经常使用快捷键
Mac OS X系统图形表示方法 ⇧ = shift ⌃ = control ⌥ = option / alt Home=fn + ◄ End=fn + ► Page Up=fn + ▲ Pag ...
- Windows 下Oracle database 9i 64bit 仅仅有 Windows Itanium 64bit
Windows 下Oracle database 9i 64bit 仅仅有 Windows Itanium 64bit,没有Windows x86-64bit的 详细请见例如以下的certificat ...
- WPF使用RoutedCommand自己定义命令
主要代码例如以下所看到的: /// <summary> /// 声明并定义命令. /// </summary> RoutedCommand ClearCommand = new ...
- java读取请求中body数据
java读取请求中body数据 /** * 获取request中body数据 * * @author lifq * * 2017年2月24日 下午2:29:06 * @throws IOExcepti ...
- Java Restful Web Service 学习指南
Restful是一种架构style,目前常说的有restful web service, resultful http.现在热搜榜的微服务,大多数会采用Restful方式. JAX-RS 作为一个Re ...
- Intellij IDEA 4种配置热部署的方法
热部署可以使的修改代码后,无须重启服务器,就可以加载更改的代码. 第1种:修改服务器配置,使得IDEA窗口失去焦点时,更新类和资源 菜单Run -> EditConfiguration , 然后 ...
- AsyncLocal的运作机制和陷阱
这是今天帮柠檬分析一个AsyncLocal相关的问题时发现的. 试想这个代码输出的值是多少? using System; using System.Threading; using System.Th ...
- 在Azure上部署IPv6的App通过IOS App Store审核
随着中国企业出海Go Global,越来越多的用户开始在Global Azure部署自己的应用.由于对Global Azure功能和文档的不熟悉,使用过程中或多或少遇到了一些坑.事实上呢,这些并不是坑 ...
- 【python】入门:打印字符串、简单计算