做网站公司排名,报个计算机培训班多少钱,订制网站建设,仓山区seo引擎优化软件前传 本地程序用的go语言#xff0c;想把main.go程序当中一些计算工作放到服务器上进行#xff0c;而只需要把结果给我即可。由于平台上暂时不能运行Go代码#xff0c;所以写的是python文件。
1、主要是使用ssh依赖进行连接#xff0c;但是大概率是需要手动添加的#xf… 前传 本地程序用的go语言想把main.go程序当中一些计算工作放到服务器上进行而只需要把结果给我即可。由于平台上暂时不能运行Go代码所以写的是python文件。
1、主要是使用ssh依赖进行连接但是大概率是需要手动添加的自动添加一直在报错。里面的go.mod也是要重新生成的主要还是不太熟。 连接就需要账号密码和地址配置好之后进行连接。test.py里面只有一个变量a并且数值是固定的只是需要输出而已里面的username和pwd还有Ip是自己的信息。
package mainimport (fmtlognettimegolang.org/x/crypto/ssh
)// 连接的配置
type ClientConfig struct {Host string //ipPort int64 // 端口Username string //用户名Password string //密码Client *ssh.Client //ssh clientLastResult string //最近一次运行的结果
}func (cliConf *ClientConfig) createClient(host string, port int64, username, password string) {var (client *ssh.Clienterr error)cliConf.Host hostcliConf.Port portcliConf.Username usernamecliConf.Password passwordcliConf.Port port//一般传入四个参数user[]ssh.AuthMethod{ssh.Password(password)}, HostKeyCallback超时时间config : ssh.ClientConfig{User: cliConf.Username,Auth: []ssh.AuthMethod{ssh.Password(password)},HostKeyCallback: func(hostname string, remote net.Addr, key ssh.PublicKey) error {return nil},Timeout: 10 * time.Second,}addr : fmt.Sprintf(%s:%d, cliConf.Host, cliConf.Port)//获取clientif client, err ssh.Dial(tcp, addr, config); err ! nil {log.Fatalln(error occurred:, err)}cliConf.Client client
}
func (cliConf *ClientConfig) RunShell(shell string) string {var (session *ssh.Sessionerr error)//获取session这个session是用来远程执行操作的if session, err cliConf.Client.NewSession(); err ! nil {log.Fatalln(error occurred:, err)}//执行shellif output, err : session.CombinedOutput(shell); err ! nil {log.Fatalln(error occurred:, err)} else {cliConf.LastResult string(output)}return cliConf.LastResult
}
func main() {cliConf : new(ClientConfig)cliConf.createClient(ip, 22, username, pwd)fmt.Println(cliConf.RunShell(cd gotest;python test.py))
}
服务器里面的代码是放在gotest文件夹里面的而每一次运行都需要cd gotest没有办法记录每次执行一条命令都会创建一条session而一条session默认只能执行一条命令并且两条命令不可以分开写。也就是
fmt.Println(cliConf.RunShell(cd gotest;python test.py))这一行代码不可以写成
cliConf.RunShell(cd gotest)
fmt.Println(cliConf.RunShell(python test.py))下图是一个运行结果 但是我将来肯定需要往里面放数据所以写test2.py文件 相应的修改main.go文件里面的runshell语句为
fmt.Println(cliConf.RunShell(cd gotest;python test.py))但是没有办法进行输入且一直会报错 后面朋友说可以通过命令行写参数所以把test2.py和main.go里面都进行了修改
fmt.Println(cliConf.RunShell(cd gotest;python test.py 2 3))结果也是可以正确输出的 但是可以看到仅仅是一个加法花费的时间是很长的数据来回的传输是很耗时的。 看到go有内置的RPC是一个进行远程控制的。