帮我规整以下代码:package main
import ( "fmt" "log" "os" "os/exec" "strings" )
const ( apacheConfPath = "/usr/local/lighthouse/softwares/apache/conf/httpd.conf" // 修改Apache配置文件路径 localPort = "8080" )
func main() { // 修改Apache配置文件中的端口号 err := updateApacheConfig() if err != nil { log.Fatalf("Failed to update Apache configuration: %s", err) }
// 重新加载Apache配置
err = reloadApache()
if err != nil {
log.Fatalf("Failed to reload Apache: %s", err)
}
// 配置防火墙规则
err = configureFirewall()
if err != nil {
log.Fatalf("Failed to configure firewall: %s", err)
}
fmt.Printf("Apache端口已修改为本地可见的端口 %s\n", localPort) }
func updateApacheConfig() error { // 打开Apache配置文件 apacheConfFile, err := os.OpenFile(apacheConfPath, os.O_RDWR, 0644) if err != nil { return fmt.Errorf("failed to open Apache configuration file: %w", err) } defer apacheConfFile.Close()
// 读取Apache配置文件内容
apacheConfBytes, err := os.ReadFile(apacheConfPath)
if err != nil {
return fmt.Errorf("failed to read Apache configuration file: %w", err)
}
// 替换端口号
newConfContent := strings.ReplaceAll(string(apacheConfBytes), "Listen 80", "Listen "+localPort)
// 回到文件开头
_, err = apacheConfFile.Seek(0, 0)
if err != nil {
return fmt.Errorf("failed to seek to the beginning of Apache configuration file: %w", err)
}
// 清空文件内容
err = apacheConfFile.Truncate(0)
if err != nil {
return fmt.Errorf("failed to truncate Apache configuration file: %w", err)
}
// 写入新的配置内容 _, err = apacheConfFile.WriteString(newConfContent) if err != nil { return fmt.Errorf("failed to write updated Apache configuration: %w", err) }
return nil
}
func reloadApache() error { cmd := exec.Command("systemctl", "restart", "httpd") // 使用systemctl命令重新启动Apache err := cmd.Run() if err != nil { return fmt.Errorf("failed to reload Apache: %w", err) } return nil }
func configureFirewall() error { // 添加防火墙规则允许从本地访问新端口 allowCmd := exec.Command("iptables", "-A", "INPUT", "-p", "tcp", "--dport", localPort, "-j", "ACCEPT") err := allowCmd.Run() if err != nil { return fmt.Errorf("failed to configure firewall to allow local access: %w", err) }
// 阻止从外部访问新端口
dropCmd := exec.Command("iptables", "-A", "INPUT", "-p", "tcp", "--dport", localPort, "-j", "DROP")
err = dropCmd.Run()
if err != nil {
return fmt.Errorf("failed to configure firewall to block external access: %w", err)
}
// 保存防火墙规则
saveCmd := exec.Command("bash", "-c", "iptables-save > /etc/sysconfig/iptables")
err = saveCmd.Run()
if err != nil {
return fmt.Errorf("failed to save firewall rules: %w", err)
}
return nil
}
最新发布