栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Go语言

golang实现自动ssh远程linux并执行shell命令

Go语言 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

golang实现自动ssh远程linux并执行shell命令

需求:自动ssh远程linux服务器进行巡检,并截图。

实现思路:win10电脑安装openssh客户端软件用于ssh远程linux,golang使用robotgo模拟键盘操作输入shell命令,并截图。

win10安装openssh:

 

 

golang代码:

package main

import (
	"strings"
	"time"

	"github.com/go-vgo/robotgo"
)

func main() {

	robotgo.KeyTap(`r`, `command`) 
	time.Sleep(time.Second * 5)
	robotgo.TypeStr("ssh root@192.168.1.100") //服务器用户名与对应IP
	time.Sleep(time.Second * 5)
	robotgo.KeyTap("enter")
	time.Sleep(time.Second * 15)
	robotgo.TypeStr("Fwqmm@2022") //服务器密码
	time.Sleep(time.Second * 5)
	robotgo.KeyTap("enter")
	time.Sleep(time.Second * 5)
	robotgo.TypeStr("su - oracle")
	time.Sleep(time.Second * 5)
	robotgo.KeyTap("enter")
	time.Sleep(time.Second * 5)
	robotgo.TypeStr("cd ")
	time.Sleep(time.Second * 5)
	robotgo.KeyTap("enter")
	time.Sleep(time.Second * 5)
	robotgo.TypeStr("df -h")
	robotgo.KeyTap("enter")

	width, height := robotgo.GetScreenSize()
	bitmap := robotgo.CaptureScreen(0, 0, width, height)
	now := time.Now()
	formatNow := now.Format("15:04:05.000")
	sname1 := strings.Replace(formatNow, ":", "", -1)
	sname2 := strings.Replace(sname1, ".", "", -1)
	robotgo.SaveBitmap(bitmap, sname2+".png")

	time.Sleep(time.Second * 5)
	robotgo.TypeStr("exit")
	time.Sleep(time.Second * 5)
	robotgo.KeyTap("enter")
	time.Sleep(time.Second * 5)
	robotgo.TypeStr("exit")
	time.Sleep(time.Second * 5)
	robotgo.KeyTap("enter")

}

编译时,使用go build -ldflags "-extldflags "-static" -s -w",就能链接必要的静态库,程序可在其他电脑正常运行。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/903295.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号