60 lines
1.5 KiB
Go
60 lines
1.5 KiB
Go
package main
|
|
|
|
import (
|
|
"fmt"
|
|
"math/rand"
|
|
"os"
|
|
"time"
|
|
)
|
|
|
|
// 定义包含大小写字母、数字、特殊符号的字符集
|
|
const charset = "abcdefghijklmnopqrstuvwxyz" +
|
|
"ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" +
|
|
"!@#$%^*()"
|
|
|
|
// 生成指定长度的随机字符串
|
|
func generateRandomString(length int) string {
|
|
// 初始化随机数种子
|
|
rand.Seed(time.Now().UnixNano())
|
|
|
|
// 用于存储生成的随机字符串
|
|
b := make([]byte, length)
|
|
|
|
// 遍历指定长度,从字符集中随机选取字符添加到结果中
|
|
for i := range b {
|
|
b[i] = charset[rand.Intn(len(charset))]
|
|
}
|
|
return string(b)
|
|
}
|
|
|
|
// 将内容追加到文件中
|
|
func appendToFile(filePath string, content string) error {
|
|
// 以追加和创建文件的模式打开文件
|
|
file, err := os.OpenFile(filePath, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
// 确保文件在函数结束时关闭
|
|
defer file.Close()
|
|
|
|
// 向文件中写入内容并添加换行符
|
|
_, err = file.WriteString(content + "\n")
|
|
return err
|
|
}
|
|
|
|
func main() {
|
|
// 调用函数生成 32 位的随机密码
|
|
password := generateRandomString(32)
|
|
fmt.Println("生成的 32 位密码是:", password)
|
|
|
|
// 定义要写入的文件路径
|
|
filePath := "/Users/d-robotics/gitea/k8s-wk/passwd/passwd.txt"
|
|
// 调用函数将密码追加到文件中
|
|
err := appendToFile(filePath, password)
|
|
if err != nil {
|
|
fmt.Printf("写入文件时出错: %v\n", err)
|
|
} else {
|
|
fmt.Printf("密码已成功追加到 %s 文件中。\n", filePath)
|
|
}
|
|
}
|