feat: 增加 ssh 登录日志功能

This commit is contained in:
ssongliu 2023-05-16 18:49:27 +08:00 committed by zhengkunwang223
parent b19cdd9339
commit efd545882f
13 changed files with 724 additions and 223 deletions

View File

@ -103,3 +103,30 @@ func (b *BaseApi) LoadSSHSecret(c *gin.Context) {
}
helper.SuccessWithData(c, data)
}
// @Tags SSH
// @Summary Load host ssh logs
// @Description 获取 ssh 登录日志
// @Accept json
// @Param request body dto.SearchSSHLog true "request"
// @Success 200 {object} dto.SSHLog
// @Security ApiKeyAuth
// @Router /host/ssh/logs [post]
func (b *BaseApi) LoadSSHLogs(c *gin.Context) {
var req dto.SearchSSHLog
if err := c.ShouldBindJSON(&req); err != nil {
helper.ErrorWithDetail(c, constant.CodeErrBadRequest, constant.ErrTypeInvalidParams, err)
return
}
if err := global.VALID.Struct(req); err != nil {
helper.ErrorWithDetail(c, constant.CodeErrBadRequest, constant.ErrTypeInvalidParams, err)
return
}
data, err := sshService.LoadLog(req)
if err != nil {
helper.ErrorWithDetail(c, constant.CodeErrInternalServer, constant.ErrTypeInternalServer, err)
return
}
helper.SuccessWithData(c, data)
}

View File

@ -1,5 +1,7 @@
package dto
import "time"
type SSHInfo struct {
Port string `json:"port" validate:"required,number,max=65535,min=1"`
ListenAddress string `json:"listenAddress"`
@ -17,3 +19,25 @@ type GenerateSSH struct {
type GenerateLoad struct {
EncryptionMode string `json:"encryptionMode" validate:"required,oneof=rsa ed25519 ecdsa dsa"`
}
type SearchSSHLog struct {
PageInfo
Info string `json:"info"`
Status string `json:"Status" validate:"required,oneof=Success Failed All"`
}
type SSHLog struct {
Logs []SSHHistory `json:"logs"`
TotalCount int `json:"totalCount"`
SuccessfulCount int `json:"successfulCount"`
FailedCount int `json:"failedCount"`
}
type SSHHistory struct {
Date time.Time `json:"date"`
Belong string `json:"belong"`
User string `json:"user"`
AuthMode string `json:"authMode"`
Address string `json:"address"`
Port string `json:"port"`
Status string `json:"status"`
Message string `json:"message"`
}

View File

@ -4,9 +4,14 @@ import (
"fmt"
"os"
"os/user"
"path"
"path/filepath"
"sort"
"strings"
"time"
"github.com/1Panel-dev/1Panel/backend/app/dto"
"github.com/1Panel-dev/1Panel/backend/constant"
"github.com/1Panel-dev/1Panel/backend/utils/cmd"
"github.com/1Panel-dev/1Panel/backend/utils/files"
)
@ -20,6 +25,7 @@ type ISSHService interface {
Update(key, value string) error
GenerateSSH(req dto.GenerateSSH) error
LoadSSHSecret(mode string) (string, error)
LoadLog(req dto.SearchSSHLog) (*dto.SSHLog, error)
}
func NewISSHService() ISSHService {
@ -141,6 +147,76 @@ func (u *SSHService) LoadSSHSecret(mode string) (string, error) {
return string(file), err
}
func (u *SSHService) LoadLog(req dto.SearchSSHLog) (*dto.SSHLog, error) {
var fileList []string
var data dto.SSHLog
baseDir := "/var/log"
if err := filepath.Walk(baseDir, func(pathItem string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if !info.IsDir() && strings.HasPrefix(info.Name(), "secure") || strings.HasPrefix(info.Name(), "auth") {
if strings.HasSuffix(info.Name(), ".gz") {
if err := handleGunzip(pathItem); err == nil {
fileList = append(fileList, strings.ReplaceAll(pathItem, ".gz", ""))
}
} else {
fileList = append(fileList, pathItem)
}
}
return nil
}); err != nil {
return nil, err
}
command := ""
if len(req.Info) != 0 {
command = fmt.Sprintf(" | grep '%s'", req.Info)
}
for i := 0; i < len(fileList); i++ {
if strings.HasPrefix(path.Base(fileList[i]), "secure") {
dataItem := loadFailedSecureDatas(fmt.Sprintf("cat %s | grep -a 'Failed password for' | grep -v 'invalid' %s", fileList[i], command))
data.FailedCount += len(dataItem)
data.TotalCount += len(dataItem)
if req.Status != constant.StatusSuccess {
data.Logs = append(data.Logs, dataItem...)
}
}
if strings.HasPrefix(path.Base(fileList[i]), "auth.log") {
dataItem := loadFailedAuthDatas(fmt.Sprintf("cat %s | grep -a 'Connection closed by authenticating user' | grep -a 'preauth' %s", fileList[i], command))
data.FailedCount += len(dataItem)
data.TotalCount += len(dataItem)
if req.Status != constant.StatusSuccess {
data.Logs = append(data.Logs, dataItem...)
}
}
dataItem := loadSuccessDatas(fmt.Sprintf("cat %s | grep Accepted %s", fileList[i], command))
data.TotalCount += len(dataItem)
if req.Status != constant.StatusFailed {
data.Logs = append(data.Logs, dataItem...)
}
}
data.SuccessfulCount = data.TotalCount - data.FailedCount
sort.Slice(data.Logs, func(i, j int) bool {
return data.Logs[i].Date.After(data.Logs[j].Date)
})
var itemDatas []dto.SSHHistory
total, start, end := len(data.Logs), (req.Page-1)*req.PageSize, req.Page*req.PageSize
if start > total {
itemDatas = make([]dto.SSHHistory, 0)
} else {
if end >= total {
end = total
}
itemDatas = data.Logs[start:end]
}
data.Logs = itemDatas
return &data, nil
}
func updateSSHConf(oldFiles []string, param string, value interface{}) []string {
hasKey := false
var newFiles []string
@ -170,3 +246,103 @@ func updateSSHConf(oldFiles []string, param string, value interface{}) []string
}
return newFiles
}
func loadSuccessDatas(command string) []dto.SSHHistory {
var datas []dto.SSHHistory
timeNow := time.Now()
stdout2, err := cmd.Exec(command)
if err == nil {
lines := strings.Split(string(stdout2), "\n")
for _, line := range lines {
parts := strings.Fields(line)
if len(parts) != 14 {
continue
}
historyItem := dto.SSHHistory{
Belong: parts[3],
AuthMode: parts[6],
User: parts[8],
Address: parts[10],
Port: parts[12],
Status: constant.StatusSuccess,
}
historyItem.Date, _ = time.Parse("2006 Jan 2 15:04:05", fmt.Sprintf("%d %s %s %s", timeNow.Year(), parts[0], parts[1], parts[2]))
if historyItem.Date.After(timeNow) {
historyItem.Date = historyItem.Date.AddDate(-1, 0, 0)
}
datas = append(datas, historyItem)
}
}
return datas
}
func loadFailedAuthDatas(command string) []dto.SSHHistory {
var datas []dto.SSHHistory
timeNow := time.Now()
stdout2, err := cmd.Exec(command)
if err == nil {
lines := strings.Split(string(stdout2), "\n")
for _, line := range lines {
parts := strings.Fields(line)
if len(parts) != 15 {
continue
}
historyItem := dto.SSHHistory{
Belong: parts[3],
AuthMode: parts[8],
User: parts[10],
Address: parts[11],
Port: parts[13],
Status: constant.StatusFailed,
}
historyItem.Date, _ = time.Parse("2006 Jan 2 15:04:05", fmt.Sprintf("%d %s %s %s", timeNow.Year(), parts[0], parts[1], parts[2]))
if historyItem.Date.After(timeNow) {
historyItem.Date = historyItem.Date.AddDate(-1, 0, 0)
}
if strings.Contains(line, ": ") {
historyItem.Message = strings.Split(line, ": ")[0]
}
datas = append(datas, historyItem)
}
}
return datas
}
func loadFailedSecureDatas(command string) []dto.SSHHistory {
var datas []dto.SSHHistory
timeNow := time.Now()
stdout2, err := cmd.Exec(command)
if err == nil {
lines := strings.Split(string(stdout2), "\n")
for _, line := range lines {
parts := strings.Fields(line)
if len(parts) != 14 {
continue
}
historyItem := dto.SSHHistory{
Belong: parts[3],
AuthMode: parts[6],
User: parts[8],
Address: parts[10],
Port: parts[12],
Status: constant.StatusFailed,
}
historyItem.Date, _ = time.Parse("2006 Jan 2 15:04:05", fmt.Sprintf("%d %s %s %s", timeNow.Year(), parts[0], parts[1], parts[2]))
if historyItem.Date.After(timeNow) {
historyItem.Date = historyItem.Date.AddDate(-1, 0, 0)
}
if strings.Contains(line, ": ") {
historyItem.Message = strings.Split(line, ": ")[0]
}
datas = append(datas, historyItem)
}
}
return datas
}
func handleGunzip(path string) error {
if _, err := cmd.Execf("gunzip %s", path); err != nil {
return err
}
return nil
}

View File

@ -0,0 +1,98 @@
package service
import (
"fmt"
"os"
"path"
"path/filepath"
"strings"
"testing"
"time"
"github.com/1Panel-dev/1Panel/backend/constant"
"github.com/1Panel-dev/1Panel/backend/utils/cmd"
)
func TestCa(t *testing.T) {
var (
fileList []string
datas []history
successfulCount int
failedCount int
)
baseDir := "/Users/slooop/Downloads"
if err := filepath.Walk(baseDir, func(pathItem string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if !info.IsDir() && strings.HasPrefix(info.Name(), "secure") || strings.HasPrefix(info.Name(), "auth") {
fileList = append(fileList, strings.ReplaceAll(pathItem, ".gz", ""))
}
return nil
}); err != nil {
fmt.Println(err)
}
for i := 0; i < len(fileList); i++ {
if strings.HasPrefix(path.Base(fileList[i]), "secure") {
dataItem := loadDatas2(fmt.Sprintf("cat %s | grep -a 'Failed password for' | grep -v 'invalid'", fileList[i]), 14, constant.StatusFailed)
failedCount += len(dataItem)
datas = append(datas, dataItem...)
}
if strings.HasPrefix(path.Base(fileList[i]), "auth.log") {
dataItem := loadDatas2(fmt.Sprintf("cat %s | grep -a 'Connection closed by authenticating user' | grep -a 'preauth'", fileList[i]), 15, constant.StatusFailed)
failedCount += len(dataItem)
datas = append(datas, dataItem...)
}
dataItem := loadDatas2(fmt.Sprintf("cat %s | grep Accepted", fileList[i]), 14, constant.StatusSuccess)
datas = append(datas, dataItem...)
}
successfulCount = len(datas) - failedCount
fmt.Println(len(datas), successfulCount, failedCount)
}
func loadDatas2(command string, length int, status string) []history {
var datas []history
stdout2, err := cmd.Exec(command)
if err == nil {
lines := strings.Split(string(stdout2), "\n")
for _, line := range lines {
parts := strings.Fields(line)
if len(parts) != length {
continue
}
historyItem := history{
Belong: parts[3],
User: parts[8],
AuthMode: parts[6],
Address: parts[10],
Port: parts[12],
Status: status,
}
dateStr := fmt.Sprintf("%d %s %s %s", time.Now().Year(), parts[0], parts[1], parts[2])
historyItem.Date, _ = time.Parse("2006 Jan 2 15:04:05", dateStr)
// if err != nil {
// historyItem.Date, _ = time.Parse("2006 Jan 2 15:04:05", dateStr)
// }
fmt.Println(dateStr + "===>" + historyItem.Date.Format("2006.01.02 15:04:05"))
datas = append(datas, historyItem)
}
}
return datas
}
func TestCas(t *testing.T) {
ss := "2023 May 9 14:48:28"
kk, err := time.Parse("2006 Jan 2 15:04:05", ss)
fmt.Println(kk, err)
}
type history struct {
Date time.Time
Belong string
User string
AuthMode string
Address string
Port string
Status string
Message string
}

View File

@ -39,6 +39,7 @@ func (s *HostRouter) InitHostRouter(Router *gin.RouterGroup) {
hostRouter.POST("/ssh/update", baseApi.UpdateSSH)
hostRouter.POST("/ssh/generate", baseApi.GenerateSSH)
hostRouter.POST("/ssh/secret", baseApi.LoadSSHSecret)
hostRouter.POST("/ssh/log", baseApi.LoadSSHLogs)
hostRouter.GET("/command", baseApi.ListCommand)
hostRouter.POST("/command", baseApi.CreateCommand)

View File

@ -118,4 +118,23 @@ export namespace Host {
encryptionMode: string;
password: string;
}
export interface searchSSHLog extends ReqPage {
info: string;
status: string;
}
export interface sshLog {
logs: Array<sshHistory>;
successfulCount: number;
failedCount: number;
}
export interface sshHistory {
date: Date;
belong: string;
user: string;
authMode: string;
address: string;
port: string;
status: string;
message: string;
}
}

View File

@ -110,3 +110,6 @@ export const generateSecret = (params: Host.SSHGenerate) => {
export const loadSecret = (mode: string) => {
return http.post<string>(`/hosts/ssh/secret`, { encryptionMode: mode });
};
export const loadSSHLogs = (params: Host.searchSSHLog) => {
return http.post<Host.sshLog>(`/hosts/ssh/log`, params);
};

View File

@ -845,6 +845,11 @@ const message = {
keyAuthHelper: '是否启用密钥认证默认启用',
useDNS: '反向解析',
dnsHelper: '控制 SSH 服务器是否启用 DNS 解析功能从而验证连接方的身份',
loginLogs: 'SSH 登录日志',
loginUser: '用户',
loginMode: '登录方式',
authenticating: '密钥',
password: '密码',
},
setting: {
all: '全部',

View File

@ -51,15 +51,26 @@ const hostRouter = {
},
},
{
path: '/hosts/ssh',
path: '/hosts/ssh/ssh',
name: 'SSH',
component: () => import('@/views/host/ssh/index.vue'),
component: () => import('@/views/host/ssh/ssh/index.vue'),
meta: {
title: 'menu.ssh',
activeMenu: '/hosts/ssh/ssh',
keepAlive: true,
requiresAuth: false,
},
},
{
path: '/hosts/ssh/log',
name: 'SSHLog',
component: () => import('@/views/host/ssh/log/index.vue'),
hidden: true,
meta: {
activeMenu: '/hosts/ssh/ssh',
requiresAuth: false,
},
},
{
path: '/hosts/firewall/port',
name: 'FirewallPort',

View File

@ -1,230 +1,25 @@
<template>
<div v-loading="loading">
<RouterButton
:buttons="[
{
label: i18n.global.t('menu.ssh'),
path: '/hosts/ssh',
},
]"
/>
<LayoutContent style="margin-top: 20px" :title="$t('menu.ssh')" :divider="true">
<template #main>
<el-radio-group v-model="confShowType" @change="changeMode">
<el-radio-button label="base">{{ $t('database.baseConf') }}</el-radio-button>
<el-radio-button label="all">{{ $t('database.allConf') }}</el-radio-button>
</el-radio-group>
<el-row style="margin-top: 20px" v-if="confShowType === 'base'">
<el-col :span="1"><br /></el-col>
<el-col :span="10">
<el-form :model="form" label-position="left" ref="formRef" label-width="120px">
<el-form-item :label="$t('ssh.port')" prop="port" :rules="Rules.port">
<el-input v-model.number="form.port">
<template #append>
<el-button icon="Collection" @click="onSave(formRef, 'Port', form.port + '')">
{{ $t('commons.button.save') }}
</el-button>
</template>
</el-input>
<span class="input-help">{{ $t('ssh.portHelper') }}</span>
</el-form-item>
<el-form-item :label="$t('ssh.listenAddress')" prop="listenAddress">
<el-input v-model="form.listenAddress">
<template #append>
<el-button
icon="Collection"
@click="onSave(formRef, 'ListenAddress', form.listenAddress)"
>
{{ $t('commons.button.save') }}
</el-button>
</template>
</el-input>
<span class="input-help">{{ $t('ssh.addressHelper') }}</span>
</el-form-item>
<el-form-item :label="$t('ssh.permitRootLogin')" prop="permitRootLogin">
<el-select
v-model="form.permitRootLogin"
@change="onSave(formRef, 'PermitRootLogin', form.permitRootLogin)"
style="width: 100%"
>
<el-option :label="$t('ssh.rootHelper1')" value="yes" />
<el-option :label="$t('ssh.rootHelper2')" value="no" />
<el-option :label="$t('ssh.rootHelper3')" value="without-password" />
<el-option :label="$t('ssh.rootHelper4')" value="forced-commands-only" />
</el-select>
<span class="input-help">{{ $t('ssh.rootSettingHelper') }}</span>
</el-form-item>
<el-form-item :label="$t('ssh.passwordAuthentication')" prop="passwordAuthentication">
<el-switch
active-value="yes"
inactive-value="no"
@change="onSave(formRef, 'PasswordAuthentication', form.passwordAuthentication)"
v-model="form.passwordAuthentication"
></el-switch>
<span class="input-help">{{ $t('ssh.pwdAuthHelper') }}</span>
</el-form-item>
<el-form-item :label="$t('ssh.pubkeyAuthentication')" prop="pubkeyAuthentication">
<el-switch
active-value="yes"
inactive-value="no"
@change="onSave(formRef, 'PubkeyAuthentication', form.pubkeyAuthentication)"
v-model="form.pubkeyAuthentication"
></el-switch>
<span class="input-help">{{ $t('ssh.keyAuthHelper') }}</span>
<el-button link @click="onOpenDrawer" type="primary">
{{ $t('ssh.pubkey') }}
</el-button>
</el-form-item>
<el-form-item :label="$t('ssh.useDNS')" prop="useDNS">
<el-switch
active-value="yes"
inactive-value="no"
@change="onSave(formRef, 'UseDNS', form.useDNS)"
v-model="form.useDNS"
></el-switch>
<span class="input-help">{{ $t('ssh.dnsHelper') }}</span>
</el-form-item>
</el-form>
</el-col>
</el-row>
<div v-if="confShowType === 'all'">
<codemirror
:autofocus="true"
placeholder="# The SSH configuration file does not exist or is empty (/etc/ssh/sshd_config)"
:indent-with-tab="true"
:tabSize="4"
style="margin-top: 10px; height: calc(100vh - 330px)"
:lineWrapping="true"
:matchBrackets="true"
theme="cobalt"
:styleActiveLine="true"
:extensions="extensions"
v-model="sshConf"
/>
<el-button :disabled="loading" type="primary" @click="onSaveFile" style="margin-top: 5px">
{{ $t('commons.button.save') }}
</el-button>
</div>
</template>
<div>
<RouterButton :buttons="buttons" />
<LayoutContent>
<router-view></router-view>
</LayoutContent>
<PubKey ref="pubKeyRef" />
</div>
</template>
<script lang="ts" setup>
import { onMounted, reactive, ref } from 'vue';
import { Codemirror } from 'vue-codemirror';
import LayoutContent from '@/layout/layout-content.vue';
import { javascript } from '@codemirror/lang-javascript';
import { oneDark } from '@codemirror/theme-one-dark';
import PubKey from '@/views/host/ssh/pubkey/index.vue';
import i18n from '@/lang';
import { MsgSuccess } from '@/utils/message';
import { getSSHInfo, updateSSH } from '@/api/modules/host';
import { LoadFile, SaveFileContent } from '@/api/modules/files';
import { Rules } from '@/global/form-rules';
import { ElMessageBox, FormInstance } from 'element-plus';
import LayoutContent from '@/layout/layout-content.vue';
import RouterButton from '@/components/router-button/index.vue';
const loading = ref(false);
const formRef = ref();
const extensions = [javascript(), oneDark];
const confShowType = ref('base');
const pubKeyRef = ref();
const sshConf = ref();
const form = reactive({
port: 22,
listenAddress: '',
passwordAuthentication: 'yes',
pubkeyAuthentication: 'yes',
encryptionMode: '',
primaryKey: '',
permitRootLogin: 'yes',
useDNS: 'no',
});
const onSaveFile = async () => {
loading.value = true;
await SaveFileContent({ path: '/etc/ssh/sshd_config', content: sshConf.value })
.then(() => {
loading.value = false;
MsgSuccess(i18n.global.t('commons.msg.operationSuccess'));
})
.catch(() => {
loading.value = false;
});
};
const onOpenDrawer = () => {
pubKeyRef.value.acceptParams();
};
const onSave = async (formEl: FormInstance | undefined, key: string, value: string) => {
if (!formEl) return;
let itemKey = key.replace(key[0], key[0].toLowerCase());
const result = await formEl.validateField(itemKey, callback);
if (!result) {
return;
}
ElMessageBox.confirm(
i18n.global.t('ssh.sshChangeHelper', [i18n.global.t('ssh.' + itemKey), value]),
i18n.global.t('ssh.sshChange'),
{
confirmButtonText: i18n.global.t('commons.button.confirm'),
cancelButtonText: i18n.global.t('commons.button.cancel'),
type: 'info',
},
)
.then(async () => {
loading.value = true;
await updateSSH(key, value)
.then(() => {
loading.value = false;
MsgSuccess(i18n.global.t('commons.msg.operationSuccess'));
})
.catch(() => {
loading.value = false;
});
})
.catch(() => {
search();
});
};
function callback(error: any) {
if (error) {
return error.message;
} else {
return;
}
}
const loadSSHConf = async () => {
const res = await LoadFile({ path: '/etc/ssh/sshd_config' });
sshConf.value = res.data || '';
};
const changeMode = async () => {
if (confShowType.value === 'all') {
loadSSHConf();
} else {
search();
}
};
const search = async () => {
const res = await getSSHInfo();
form.port = Number(res.data.port);
form.listenAddress = res.data.listenAddress;
form.passwordAuthentication = res.data.passwordAuthentication;
form.pubkeyAuthentication = res.data.pubkeyAuthentication;
form.permitRootLogin = res.data.permitRootLogin;
form.useDNS = res.data.useDNS;
};
onMounted(() => {
search();
});
const buttons = [
{
label: i18n.global.t('menu.ssh'),
path: '/hosts/ssh/ssh',
},
{
label: i18n.global.t('ssh.loginLogs'),
path: '/hosts/ssh/log',
},
];
</script>

View File

@ -0,0 +1,117 @@
<template>
<div>
<FireRouter />
<LayoutContent v-loading="loading" :title="$t('ssh.loginLogs')">
<template #toolbar>
<el-row>
<el-col :span="16">
<el-tag type="success">{{ $t('commons.status.success') }} {{ successfulCount }}</el-tag>
<el-tag type="danger" style="margin-left: 5px">
{{ $t('commons.status.failed') }} {{ faliedCount }}
</el-tag>
</el-col>
<el-col :span="8">
<TableSetting @search="search()" />
<div class="search-button">
<el-input
v-model="searchInfo"
clearable
@clear="search()"
suffix-icon="Search"
@keyup.enter="search()"
@change="search()"
:placeholder="$t('commons.button.search')"
></el-input>
</div>
</el-col>
</el-row>
</template>
<template #search>
<el-select v-model="searchStatus" @change="search()" clearable>
<template #prefix>{{ $t('commons.table.status') }}</template>
<el-option :label="$t('commons.table.all')" value="All"></el-option>
<el-option :label="$t('commons.status.success')" value="Success"></el-option>
<el-option :label="$t('commons.status.failed')" value="Failed"></el-option>
</el-select>
</template>
<template #main>
<ComplexTable :pagination-config="paginationConfig" :data="data" @search="search">
<el-table-column min-width="40" :label="$t('logs.loginIP')" prop="ip">
<template #default="{ row }">{{ row.address }}:{{ row.port }}</template>
</el-table-column>
<el-table-column min-width="40" :label="$t('ssh.loginMode')" prop="authMode">
<template #default="{ row }">{{ $t('ssh.' + row.authMode) }}</template>
</el-table-column>
<el-table-column min-width="40" :label="$t('ssh.loginUser')" prop="user" />
<el-table-column min-width="40" :label="$t('logs.loginStatus')" prop="status">
<template #default="{ row }">
<div v-if="row.status === 'Success'">
<el-tag type="success">{{ $t('commons.status.success') }}</el-tag>
</div>
<div v-else>
<el-tooltip class="box-item" effect="dark" :content="row.message" placement="top-start">
<el-tag type="danger">{{ $t('commons.status.failed') }}</el-tag>
</el-tooltip>
</div>
</template>
</el-table-column>
<el-table-column
prop="date"
:label="$t('commons.table.date')"
:formatter="dateFormat"
show-overflow-tooltip
/>
</ComplexTable>
</template>
</LayoutContent>
</div>
</template>
<script setup lang="ts">
import FireRouter from '@/views/host/ssh/index.vue';
import ComplexTable from '@/components/complex-table/index.vue';
import TableSetting from '@/components/table-setting/index.vue';
import LayoutContent from '@/layout/layout-content.vue';
import { dateFormat } from '@/utils/util';
import { onMounted, reactive, ref } from '@vue/runtime-core';
import { loadSSHLogs } from '@/api/modules/host';
const loading = ref();
const data = ref();
const paginationConfig = reactive({
currentPage: 1,
pageSize: 10,
total: 0,
});
const searchInfo = ref();
const searchStatus = ref('All');
const successfulCount = ref(0);
const faliedCount = ref(0);
const search = async () => {
let params = {
info: searchInfo.value,
status: searchStatus.value,
page: paginationConfig.currentPage,
pageSize: paginationConfig.pageSize,
};
loading.value = true;
await loadSSHLogs(params)
.then((res) => {
loading.value = false;
data.value = res.data.logs || [];
faliedCount.value = res.data.failedCount;
successfulCount.value = res.data.successfulCount;
paginationConfig.total = res.data.failedCount + res.data.successfulCount;
})
.catch(() => {
loading.value = false;
});
};
onMounted(() => {
search();
});
</script>

View File

@ -0,0 +1,225 @@
<template>
<div v-loading="loading">
<FireRouter />
<LayoutContent style="margin-top: 20px" :title="$t('menu.ssh')" :divider="true">
<template #main>
<el-radio-group v-model="confShowType" @change="changeMode">
<el-radio-button label="base">{{ $t('database.baseConf') }}</el-radio-button>
<el-radio-button label="all">{{ $t('database.allConf') }}</el-radio-button>
</el-radio-group>
<el-row style="margin-top: 20px" v-if="confShowType === 'base'">
<el-col :span="1"><br /></el-col>
<el-col :span="10">
<el-form :model="form" label-position="left" ref="formRef" label-width="120px">
<el-form-item :label="$t('ssh.port')" prop="port" :rules="Rules.port">
<el-input v-model.number="form.port">
<template #append>
<el-button icon="Collection" @click="onSave(formRef, 'Port', form.port + '')">
{{ $t('commons.button.save') }}
</el-button>
</template>
</el-input>
<span class="input-help">{{ $t('ssh.portHelper') }}</span>
</el-form-item>
<el-form-item :label="$t('ssh.listenAddress')" prop="listenAddress">
<el-input v-model="form.listenAddress">
<template #append>
<el-button
icon="Collection"
@click="onSave(formRef, 'ListenAddress', form.listenAddress)"
>
{{ $t('commons.button.save') }}
</el-button>
</template>
</el-input>
<span class="input-help">{{ $t('ssh.addressHelper') }}</span>
</el-form-item>
<el-form-item :label="$t('ssh.permitRootLogin')" prop="permitRootLogin">
<el-select
v-model="form.permitRootLogin"
@change="onSave(formRef, 'PermitRootLogin', form.permitRootLogin)"
style="width: 100%"
>
<el-option :label="$t('ssh.rootHelper1')" value="yes" />
<el-option :label="$t('ssh.rootHelper2')" value="no" />
<el-option :label="$t('ssh.rootHelper3')" value="without-password" />
<el-option :label="$t('ssh.rootHelper4')" value="forced-commands-only" />
</el-select>
<span class="input-help">{{ $t('ssh.rootSettingHelper') }}</span>
</el-form-item>
<el-form-item :label="$t('ssh.passwordAuthentication')" prop="passwordAuthentication">
<el-switch
active-value="yes"
inactive-value="no"
@change="onSave(formRef, 'PasswordAuthentication', form.passwordAuthentication)"
v-model="form.passwordAuthentication"
></el-switch>
<span class="input-help">{{ $t('ssh.pwdAuthHelper') }}</span>
</el-form-item>
<el-form-item :label="$t('ssh.pubkeyAuthentication')" prop="pubkeyAuthentication">
<el-switch
active-value="yes"
inactive-value="no"
@change="onSave(formRef, 'PubkeyAuthentication', form.pubkeyAuthentication)"
v-model="form.pubkeyAuthentication"
></el-switch>
<span class="input-help">{{ $t('ssh.keyAuthHelper') }}</span>
<el-button link @click="onOpenDrawer" type="primary">
{{ $t('ssh.pubkey') }}
</el-button>
</el-form-item>
<el-form-item :label="$t('ssh.useDNS')" prop="useDNS">
<el-switch
active-value="yes"
inactive-value="no"
@change="onSave(formRef, 'UseDNS', form.useDNS)"
v-model="form.useDNS"
></el-switch>
<span class="input-help">{{ $t('ssh.dnsHelper') }}</span>
</el-form-item>
</el-form>
</el-col>
</el-row>
<div v-if="confShowType === 'all'">
<codemirror
:autofocus="true"
placeholder="# The SSH configuration file does not exist or is empty (/etc/ssh/sshd_config)"
:indent-with-tab="true"
:tabSize="4"
style="margin-top: 10px; height: calc(100vh - 330px)"
:lineWrapping="true"
:matchBrackets="true"
theme="cobalt"
:styleActiveLine="true"
:extensions="extensions"
v-model="sshConf"
/>
<el-button :disabled="loading" type="primary" @click="onSaveFile" style="margin-top: 5px">
{{ $t('commons.button.save') }}
</el-button>
</div>
</template>
</LayoutContent>
<PubKey ref="pubKeyRef" />
</div>
</template>
<script lang="ts" setup>
import { onMounted, reactive, ref } from 'vue';
import { Codemirror } from 'vue-codemirror';
import FireRouter from '@/views/host/ssh/index.vue';
import LayoutContent from '@/layout/layout-content.vue';
import { javascript } from '@codemirror/lang-javascript';
import { oneDark } from '@codemirror/theme-one-dark';
import PubKey from '@/views/host/ssh/ssh/pubkey/index.vue';
import i18n from '@/lang';
import { MsgSuccess } from '@/utils/message';
import { getSSHInfo, updateSSH } from '@/api/modules/host';
import { LoadFile, SaveFileContent } from '@/api/modules/files';
import { Rules } from '@/global/form-rules';
import { ElMessageBox, FormInstance } from 'element-plus';
const loading = ref(false);
const formRef = ref();
const extensions = [javascript(), oneDark];
const confShowType = ref('base');
const pubKeyRef = ref();
const sshConf = ref();
const form = reactive({
port: 22,
listenAddress: '',
passwordAuthentication: 'yes',
pubkeyAuthentication: 'yes',
encryptionMode: '',
primaryKey: '',
permitRootLogin: 'yes',
useDNS: 'no',
});
const onSaveFile = async () => {
loading.value = true;
await SaveFileContent({ path: '/etc/ssh/sshd_config', content: sshConf.value })
.then(() => {
loading.value = false;
MsgSuccess(i18n.global.t('commons.msg.operationSuccess'));
})
.catch(() => {
loading.value = false;
});
};
const onOpenDrawer = () => {
pubKeyRef.value.acceptParams();
};
const onSave = async (formEl: FormInstance | undefined, key: string, value: string) => {
if (!formEl) return;
let itemKey = key.replace(key[0], key[0].toLowerCase());
const result = await formEl.validateField(itemKey, callback);
if (!result) {
return;
}
ElMessageBox.confirm(
i18n.global.t('ssh.sshChangeHelper', [i18n.global.t('ssh.' + itemKey), value]),
i18n.global.t('ssh.sshChange'),
{
confirmButtonText: i18n.global.t('commons.button.confirm'),
cancelButtonText: i18n.global.t('commons.button.cancel'),
type: 'info',
},
)
.then(async () => {
loading.value = true;
await updateSSH(key, value)
.then(() => {
loading.value = false;
MsgSuccess(i18n.global.t('commons.msg.operationSuccess'));
})
.catch(() => {
loading.value = false;
});
})
.catch(() => {
search();
});
};
function callback(error: any) {
if (error) {
return error.message;
} else {
return;
}
}
const loadSSHConf = async () => {
const res = await LoadFile({ path: '/etc/ssh/sshd_config' });
sshConf.value = res.data || '';
};
const changeMode = async () => {
if (confShowType.value === 'all') {
loadSSHConf();
} else {
search();
}
};
const search = async () => {
const res = await getSSHInfo();
form.port = Number(res.data.port);
form.listenAddress = res.data.listenAddress;
form.passwordAuthentication = res.data.passwordAuthentication;
form.pubkeyAuthentication = res.data.pubkeyAuthentication;
form.permitRootLogin = res.data.permitRootLogin;
form.useDNS = res.data.useDNS;
};
onMounted(() => {
search();
});
</script>