执行SSH命令后无法在远程服务器上终止该命令。

huangapple go评论79阅读模式
英文:

go execute ssh command and can't kill the command on the remote server

问题

我使用go exec ssh在远程服务器上执行"tail -f"命令。然后我杀死了这个进程,但是"tail -f"命令仍然在远程服务器上运行。

我应该怎么做才能在远程服务器上杀死"tail -f"进程?

我的代码如下:

package main

import (
	"os/exec"
	"github.com/astaxie/beego"
	"time"
)

func main() {
	var cmd = exec.Command("ssh","-t", "-p", "9122","deploy@123.com" ,"tail -f /log.out")
	var err error
	cmd.Start()
	time.Sleep(time.Second*5)
	err = cmd.Process.Kill() // 当我杀死这个进程时,远程服务器 deploy@123.com 上仍然运行着 'tail -f /log.out'
	beego.Error(err)
}
英文:

I use go exec ssh to execute "tail -f" on the remote server. Then I kill the process, but the "tail -f " still runs on the remote server.

What can I do to kill the "tail -f" process on the remote server?

My code is as follows:

package main

import (
	"os/exec"
	"github.com/astaxie/beego"
	"time"
)

func main() {
	var  cmd = exec.Command("ssh","-t", "-p", "9122","deploy@123.com" ,"tail -f /log.out")
	var err error
	cmd.Start()
	time.Sleep(time.Second*5)
	err = cmd.Process.Kill() // when I kill this process, the remote server  deploy@123.com still has 'tail -f /log.out' running
	beego.Error(err)
}

答案1

得分: 1

只需在参数中再添加一个"-t"。

var cmd = exec.Command("ssh", "-t", "-t", "-p", "9122", "deploy@123.com", "tail -f /log.out")

更多信息,请参考此链接

英文:

Just add one more "-t" in the arguments.

var  cmd = exec.Command("ssh","-t", "-t", "-p", "9122","deploy@123.com" ,"tail -f /log.out")

For more information, refer this link

答案2

得分: 0

你可以尝试发送 Control-C

w, err := cmd.StdinPipe()
ctlC, err := hex.DecodeString(`\x03`) // 在大多数机器上是 CtlC
w.Write(ctlC)

在终止 ssh 之前

err = cmd.Process.Kill()

这在我的设置中有效。

英文:

You can try to send Control-C

w, err := cmd.StdinPipe()
ctlC, err := hex.DecodeString(`\x03`) //CtlC on most machines
w.Write(ctlC)

before killing ssh

err = cmd.Process.Kill()

this works in my setup

huangapple
  • 本文由 发表于 2016年9月8日 19:46:14
  • 转载请务必保留本文链接:https://go.coder-hub.com/39390087.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定