您的位置 首页 golang

golang执行linux命令

需求

需要通过openssl 生成 rsa 秘钥,然后保存该秘钥。

代码实例

 package main
import (
    "io/ioutil"
" bytes "
"fmt"
    "os/exec"
)
func main() {
    //获取当期执行路径
pwd, err := utils.ExecShell("pwd")
if err != nil {
fmt.Println("当前命令执行出错")
}
 root Path := strings. Replace (pwd, "\n", "", -1)
//当前文件路劲下存在/tools/rsa
utils.ExecShell("chmod -R 755 " + rootPath + "/tools/rsa") //执行授权命令
//调用创建公私钥的脚本
utils.ExecShell("cd " + rootPath + "/tools/rsa/ && /bin/sh ./create Request .sh") 
publicKeyPath := rootPath + "/tools/rsa/rsa_public_key.pem.cer"
privateKeyPath := rootPath + "/tools/rsa/rsa_private_key.pem"
pkcs8KeyPath := rootPath + "/tools/rsa/pkcs8.pem"
//读取创建的秘钥
publicRsaKey, _ := ioutil.ReadFile(publicKeyPath)
privateRsaKey, _ := ioutil.ReadFile(privateKeyPath)
pkcs8Key, _ := ioutil.ReadFile(pkcs8KeyPath)
fmt.Println(string(publicRsaKey))
fmt.Println(string(privateRsaKey))
fmt.Println(string(pkcs8Key))
}
func ExecShell(s string) (string, error) {
//函数返回一个*Cmd,用于使用给出的参数执行name指定的程序
cmd := exec.Command("/bin/bash", "-c", s)
//读取io.Writer类型的cmd. stdout ,再通过bytes.Buffer(缓冲 byte 类型的缓冲器)将byte类型转化为string类型(out.String():这是bytes类型提供的接口)
var out bytes.Buffer
cmd. Stdout  = &out
//Run执行c包含的命令,并阻塞直到完成。  这里stdout被取出,cmd.Wait()无法正确获取stdin,stdout, stderr ,则阻塞在那了
err := cmd.Run()
return out.String(), err
}  

脚本

  echo  "生成rsa私钥,输出 私钥 文件rsa_private_key.pem文件中"
 openssl  genrsa -out rsa_private_key.pem 1024
echo "生成rs公钥,输出公钥文件到rsa_public_key.pem"
openssl rsa -in rsa_private_key.pem -pubout -out rsa_public_key.pem
echo "生成pkcs8.pem"
openssl pkcs8 -topk8 -inform PEM -in rsa_private_key.pem -outform pem -nocrypt -out pkcs8.pem  

文章来源:智云一二三科技

文章标题:golang执行linux命令

文章地址:https://www.zhihuclub.com/93847.shtml

关于作者: 智云科技

热门文章

网站地图