Tem 19

Akademik makaleler için otomatik özetleme servisi

sudo pico mcp_server5.py
from fastapi import FastAPI, HTTPException, status
from pydantic import BaseModel, Field, ConfigDict
from enum import Enum
from typing import Optional, Dict, List, Union
import requests
import uvicorn
from transformers import pipeline, AutoModelForSeq2SeqLM, AutoTokenizer
import torch
import os
import uuid
from datetime import datetime
import re

# MCP Standard Constants
MCP_VERSION = "1.0.0"
API_VERSION = "v1"

# Bellek optimizasyonu
os.environ["PYTORCH_CUDA_ALLOC_CONF"] = "expandable_segments:True"
torch.cuda.empty_cache()

app = FastAPI(
title="MCP Uyumlu Özetleme Servisi",
version=MCP_VERSION,
description="Model Communication Protocol 1.0.0 uyumlu akademik özetleme API'si"
)

# MCP Enumları
class TaskType(str, Enum):
SUMMARIZATION = "summarization"
TRANSLATION = "translation"
TEXT_GENERATION = "text_generation"

# MCP Request Modeli
class MCPRequest(BaseModel):
model_config = ConfigDict(protected_namespaces=()) # Uyarıyı çözmek için

model_uri: str = Field(
...,
example="huggingface://csebuetnlp/mT5_multilingual_XLSum",
description="Model URI format: {framework}://{model_path}"
)
task_type: TaskType
input_data: Dict[str, str] = Field(
...,
example={"query": "earthquake prediction using AI"},
min_items=1
)
hyperparameters: Optional[Dict[str, str]] = Field(
default={"max_length": "150", "min_length": "30"},
description="Model-specific parameters"
)
api_version: str = Field(
default=API_VERSION,
pattern=r"^v\d+$" # Düzeltme: raw string kullanıldı
)

# MCP Response Modeli
class MCPResponse(BaseModel):
model_config = ConfigDict(protected_namespaces=()) # Uyarıyı çözmek için

request_id: str = Field(
...,
example=str(uuid.uuid4()),
description="Unique request identifier"
)
model_uri: str
task_type: TaskType
timestamp: str = Field(
default_factory=lambda: datetime.utcnow().isoformat()
)
output_data: Dict[str, Union[str, int]] = Field(
example={
"title": "Deep Learning for Seismic Analysis",
"doi": "https://doi.org/10.1016/j.enggeo.2023.106552",
"summary": "This study presents...",
"original_abstract_length": 899
}
)
metrics: Dict[str, float] = Field(
default={"processing_time": 0.0, "confidence": 0.0}
)
api_version: str = Field(default=API_VERSION)
warnings: Optional[List[str]] = None

# Model Yükleme
def load_mcp_model(model_uri: str):
"""MCP URI standardına göre model yükleme"""
try:
framework, model_path = model_uri.split("://")
if framework == "huggingface":
model = AutoModelForSeq2SeqLM.from_pretrained(
model_path,
low_cpu_mem_usage=True
)
tokenizer = AutoTokenizer.from_pretrained(model_path)
return pipeline(
"summarization",
model=model,
tokenizer=tokenizer,
device="cpu"
)
raise ValueError(f"Unsupported framework: {framework}")
except Exception as e:
raise HTTPException(
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
detail=f"Model loading failed: {str(e)}"
)

# Veri Kaynakları
class DataFetcher:
@staticmethod
def get_openalex_data(query: str):
"""OpenAlex API entegrasyonu"""
url = f"https://api.openalex.org/works?search={query}&per-page=1"
try:
response = requests.get(url, timeout=10)
results = response.json().get("results", [])
return results[0] if results else None
except Exception as e:
raise HTTPException(
status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
detail=f"OpenAlex error: {str(e)}"
)

@staticmethod
def extract_abstract(paper: dict) -> Optional[str]:
"""Çoklu abstract çıkarma yöntemleri"""
# 1. Inverted index
if abstract_index := paper.get("abstract_inverted_index"):
return ' '.join(
word for word, _ in sorted(
[(k, v[0]) for k, v in abstract_index.items()],
key=lambda x: x[1]
)
)

# 2. Direct abstract
if abstract := paper.get("abstract"):
return abstract

# 3. DOI fallback
if doi := paper.get("doi"):
return DataFetcher.fetch_via_doi(doi)

return None

@staticmethod
def fetch_via_doi(doi: str) -> Optional[str]:
"""DOI üzerinden abstract çekme"""
try:
# CrossRef API
crossref_url = f"https://api.crossref.org/works/{doi.replace('https://doi.org/', '')}"
response = requests.get(crossref_url, timeout=5)
if response.status_code == 200:
return response.json().get('message', {}).get('abstract')
except:
return None

# MCP Endpoint'i
@app.post(
f"/{API_VERSION}/mcp/summarize",
response_model=MCPResponse,
tags=["MCP Services"],
summary="MCP uyumlu akademik özetleme"
)
async def mcp_summarize(request: MCPRequest):
try:
# 1. Model yükleme
summarizer = load_mcp_model(request.model_uri)

# 2. Veri çekme
paper = DataFetcher.get_openalex_data(request.input_data["query"])
if not paper:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail="No relevant paper found"
)

# 3. Abstract çıkarma
abstract = DataFetcher.extract_abstract(paper)
if not abstract:
raise HTTPException(
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
detail={
"message": "Abstract content unavailable",
"suggestions": [
"Provide full text in input_data",
f"Try alternative DOI: {paper.get('doi')}",
"Use different search terms"
]
}
)

# 4. Özetleme
params = {
"max_length": int(request.hyperparameters.get("max_length", 150)),
"min_length": int(request.hyperparameters.get("min_length", 30)),
"do_sample": request.hyperparameters.get("do_sample", "false").lower() == "true"
}

summary = summarizer(abstract[:1000], **params)[0]['summary_text']

return MCPResponse(
request_id=str(uuid.uuid4()),
model_uri=request.model_uri,
task_type=request.task_type,
output_data={
"title": paper.get("title", ""),
"doi": paper.get("doi", ""),
"summary": summary,
"original_abstract_length": len(abstract)
},
metrics={
"processing_time": 0.0,
"compression_ratio": len(summary)/len(abstract)
}
)

except HTTPException as he:
raise he
except Exception as e:
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail=str(e)
)

# Model Metadata Endpoint'i (MCP Requirement)
@app.get(
f"/{API_VERSION}/mcp/models/{{model_uri}}/metadata",
tags=["MCP Services"],
summary="Model metadata bilgisi"
)
def get_model_metadata(model_uri: str):
return {
"model_card": f"https://huggingface.co/{model_uri.split('://')[1]}",
"input_schema": {
"query": {"type": "str", "description": "Search query or full text"},
"language": {"type": "optional[str]", "default": "en"}
},
"output_schema": {
"title": "str",
"doi": "str",
"summary": "str",
"original_abstract_length": "int"
},
"mcp_compatibility": {
"version": MCP_VERSION,
"supported_tasks": [TaskType.SUMMARIZATION.value]
}
}

if __name__ == "__main__":
uvicorn.run(
app,
host="0.0.0.0",
port=8000,
workers=1,
timeout_keep_alive=30
)

uvicorn mcp_server5:app –reload –workers 1

curl -X POST http://localhost:8000/v1/mcp/summarize -H "Content-Type: application/json" -d '{
"model_uri": "huggingface://csebuetnlp/mT5_multilingual_XLSum",
"task_type": "summarization",
"input_data": {"query": "deep learning for seismic analysis"},
"hyperparameters": {"max_length": "150"},
"api_version": "v1"
}'

{“request_id”:”26f746e9-87c0-4e87-9e0d-b586896e27c7″,”model_uri”:”huggingface://csebuetnlp/mT5_multilingual_XLSum”,”task_type”:”summarization”,”timestamp”:”2025-07-18T21:35:57.163512″,”output_data”:{“title”:”Deep Learning for Accelerated Seismic Reliability Analysis of Transportation Networks”,”doi”:”https://doi.org/10.1111/mice.12359″,”summary”:”Scientists have developed a deep learning framework to assess the impact of earthquakes and tsunamis on infrastructure systems.”,”original_abstract_length”:899},”metrics”:{“processing_time”:0.0,”compression_ratio”:0.14126807563959956},”api_version”:”v1″,”warnings”:null}

—————————————————————————————————————
cat mcp_server6.py

cat mcp_server6.py
from fastapi import FastAPI
from pydantic import BaseModel
from enum import Enum
import requests
import uuid

app = FastAPI()

# MCP Standard Components
class ToolType(str, Enum):
SEARCH = "search"
DATABASE = "database"

class MCPRequest(BaseModel):
session_id: str = str(uuid.uuid4())
task: str
tools: list[ToolType]
model: str = "huggingface://t5-small"

class MCPResponse(BaseModel):
session_id: str
output: dict
used_tools: list[str]
confidence: float

# OpenAlex Entegrasyonu
def search_openlex(query: str) -> list[dict]:
url = f"https://api.openalex.org/works?search={query}&per-page=5"
response = requests.get(url)
return [
{
"title": paper.get("title"),
"abstract": ' '.join(
word for word, _ in sorted(
[(k, v[0]) for k, v in paper.get("abstract_inverted_index", {}).items()],
key=lambda x: x[1]
)
),
"doi": paper.get("doi")
}
for paper in response.json().get("results", [])
]

# LLM Entegrasyonu
def analyze_with_llm(model: str, context: str, papers: list[dict]) -> dict:
# Basit bir özetleme simülasyonu (Gerçekte model çağrısı yapılır)
combined_abstracts = " ".join(p["abstract"] for p in papers[:3])
summary = f"Recent studies ({len(papers)} papers) show {model} can analyze seismic data with: " + \
combined_abstracts[:150] + "..."
return {
"summary": summary,
"key_findings": [p["title"] for p in papers],
"confidence": 0.87
}

# MCP Endpoint

@app.post("/v1/mcp/execute")
async def execute_mcp(request: MCPRequest):
# 1. Arama araçlarını çalıştır
tool_outputs = []
if ToolType.SEARCH in request.tools:
papers = search_openlex(request.task)
tool_outputs.append({"tool": "search", "results": papers})

# 2. LLM analizi (Geliştirilmiş kısım)
detailed_analysis = []
for paper in papers[:3]: # İlk 3 makale için detaylı özet
summary = f"**{paper['title']}**\n" \
f"DOI: {paper.get('doi', 'N/A')}\n" \
f"Abstract: {paper['abstract'][:200]}...\n" \
f"Key Findings: {paper['abstract'].split('.')[0]}"
detailed_analysis.append(summary)

llm_output = {
"summary": "Recent studies show:",
"papers": detailed_analysis,
"confidence": min(0.90, len(papers)*0.18) # Makale sayısına göre confidence
}

return MCPResponse(
session_id=request.session_id,
output={
"task": request.task,
"analysis": llm_output,
"full_sources": [{"title": p["title"], "doi": p.get("doi")} for p in papers]
},
used_tools=[t.value for t in request.tools],
confidence=llm_output["confidence"]
)

curl -X POST http://localhost:8000/v1/mcp/execute \
-H “Content-Type: application/json” \
-d ‘{
“task”: “transformer models in seismology”,
“tools”: [“search”],
“model”: “huggingface://facebook/bart-large-cnn”
}’

isteğine cevap

{“session_id”:”b1226306-580c-43fe-a84f-a0c306536be4″,”output”:{“task”:”transformer models in seismology”,”analysis”:{“summary”:”Recent studies show:”,”papers”:[“**Siamese Earthquake Transformer: A Pair‐Input Deep‐Learning Model for Earthquake Detection and Phase Picking on a Seismic Array**\nDOI: https://doi.org/10.1029/2020jb021444\nAbstract: Abstract Earthquake detection and phase picking play a fundamental role in studying seismic hazards the Earth’s interior. Many deep‐learning‐based methods, including state‐of‐the‐art model called Tran…\nKey Findings: Abstract Earthquake detection and phase picking play a fundamental role in studying seismic hazards the Earth’s interior”,”**EQCCT: A Production-Ready Earthquake Detection and Phase-Picking Method Using the Compact Convolutional Transformer**\nDOI: https://doi.org/10.1109/tgrs.2023.3319440\nAbstract: We propose to implement a compact convolutional transformer (CCT) for picking the earthquake phase arrivals (EQCCT). The proposed method consists of two branches, with each them responsible arrival ti…\nKey Findings: We propose to implement a compact convolutional transformer (CCT) for picking the earthquake phase arrivals (EQCCT)”,”**SeisCLIP: A Seismology Foundation Model Pre-Trained by Multimodal Data for Multipurpose Seismic Feature Extraction**\nDOI: https://doi.org/10.1109/tgrs.2024.3354456\nAbstract: In seismology, while training a specific deep learning model for each task is common, it often faces challenges such as the scarcity of labeled data and limited regional generalization. Addressing the…\nKey Findings: In seismology, while training a specific deep learning model for each task is common, it often faces challenges such as the scarcity of labeled data and limited regional generalization”],”confidence”:0.8999999999999999},”full_sources”:[{“title”:”Siamese Earthquake Transformer: A Pair‐Input Deep‐Learning Model for Earthquake Detection and Phase Picking on a Seismic Array”,”doi”:”https://doi.org/10.1029/2020jb021444″},{“title”:”EQCCT: A Production-Ready Earthquake Detection and Phase-Picking Method Using the Compact Convolutional Transformer”,”doi”:”https://doi.org/10.1109/tgrs.2023.3319440″},{“title”:”SeisCLIP: A Seismology Foundation Model Pre-Trained by Multimodal Data for Multipurpose Seismic Feature Extraction”,”doi”:”https://doi.org/10.1109/tgrs.2024.3354456″},{“title”:”Finite-Frequency Tomography Reveals a Variety of Plumes in the Mantle”,”doi”:”https://doi.org/10.1126/science.1092485″},{“title”:”Earthquake transformer—an attentive deep-learning model for simultaneous earthquake detection and phase picking”,”doi”:”https://doi.org/10.1038/s41467-020-17591-w”}]},”used_tools”:[“search”],”confidence”:0.8999999999999999}


sequenceDiagram
participant User
participant MCP
participant OpenAlex
participant LLM

User->>+MCP: POST /v1/mcp/execute
Note right of User: {"task": "deep learning
for seismic analysis",
"tools": ["search"]}

MCP->>+OpenAlex: GET /works?search="deep learning"
AND "seismic analysis"
OpenAlex-->>-MCP: 5 makale (title+abstract+DOI)

loop Her makale için
MCP->>MCP: Abstract işleme
MCP->>MCP: Özet oluştur
end

MCP->>+LLM: Özet analizi isteği
LLM-->>-MCP: {"summary": "CNN-LSTM modelleri...",
"confidence": 0.87}

MCP-->>-User: HTTP 200
Note left of MCP: {"analysis": {
 "summary": "Recent studies...",
 "papers": [
  "**Title1**
Abstract:...",
  "**Title2**
Abstract:..."
 ],
 "sources": [...]
}}

Şub 23

Matlab’ımız yoksa ücretsiz/beleş Octave ile çalışmayalım mı? :/

Matlab’ımız yoksa ücretsiz/beleş Octave ile çalışmayalım mı? :/
MacOS’çularda https://lnkd.in/dJuFx9NX kullanabilir 😉
Screenshot oda beleş Shutter – Torned paper Plugin’i ile alınmıştır:/

Gereksinimler:
Ubuntu 24.04.1 LTS (noble) – GNU Octave, version 8.4.0’de,
pkg install -forge fuzzy-logic-toolkit (fcm için)
pkg load fuzzy-logic-toolkit

pkg install -forge statistics (kmeans için)
pkg load statistics

tansig içinde kendiniz fonksiyon yazıverin :),
function y = tansig(x)
y = 2 ./ (1 + exp(-2*x)) – 1;
end
https://lnkd.in/dZhgPmWu sayfasındaki veri seti üzerinde temel ELM’i karşılaştırmak için gerekli parametre ayarları ve koşturunca elde edilen sonuçlar:

C=0.001; %Regularization parameter
N=15; %Fuzzy Nodes
L=203; %Hidden Nodes
Act=5; %Activation Function 5 = tansig

%% Clustering Methods
cluster=[1,2,3]; % K-Means: clus=1, Fuzzy C-Means: clus=2, R-Means: clus=3
clus=2; % Fuzzy C-Means Cluster

Gerçi ELM üstün olsada bu karşılaştırma hoşuma gitmedi :/ Fuzzy_ELM yapısını kurgulamak lazım yada düz RVFL ile ELM ve FRIS destekli Constrained-Meta karşılaştırılsa daha iyi olabilir 😉

Birde paketleri kalıcı hale getirmek lazım :/
sudo nano ~/.octaverc
pkg load fuzzy-logic-toolkit
pkg load statistics

Şub 23

Sınıf ve lablarda RaspberryPi (Rpi) 4 üzerinde hw 477 li ds18b20 ile basit sıcaklık ölçer:

Sınıf ve lablarda RaspberryPi (Rpi) 4 üzerinde hw 477 li ds18b20 ile basit sıcaklık ölçer:
pinout ile Rpi pinleri check ediyoruz.
Beslemeler hariç sensör pin4 üzerinden haberleşiyor.

sudo modprobe w1-gpio
sudo pico /boot/firmware/config.txt
[all]
enable_uart=1
dtoverlay=w1-gpio,gpiopin=4

sudo pico sicaklik.py
#!/usr/bin/python3
import glob, os

def Read_DS18B20(SensorID):
try:
fichier = open( “/sys/bus/w1/devices/” + SensorID + “/w1_slave”)
texte = fichier.read()
fichier.close()
ligne1 = texte.split(“\n”)[0]
crc = ligne1.split(“crc=”)[1]
if crc.find(“YES”)<0:
return None
except:
return None
ligne2 = texte.split("\n")[1]
texte_temp = ligne2.split(" ")[9]
return (float(texte_temp[2:])/1000.0)

Her 0.5 sn'de tekrar okutma işlemi:
watch -n 0.5 python sicaklik.py

Şub 23

Herhangi bir saldırı, anomaly ve hardware’in fazla akım çektiği durumları kontrol etmek için Raspberry Pi ile PZEM-004T (100A) akım sensörü testi:

Herhangi bir saldırı, anomaly ve hardware’in fazla akım çektiği durumları kontrol etmek için Raspberry Pi ile PZEM-004T (100A) akım sensörü testi:
Windows’ta direk app var:
https://lnkd.in/dSWARySJ

Arm tabanlı Raspberry Pi 4’te ise:
sudo raspi-config ile interface seçeneklerinden serial portu aktif etmek lazım.
dmesg | grep tty ile hangi USB interface’ine sensörü taktık bakmak lazım.
sudo pip3 install modbus-tk Rpi ile sensör modbus haberleşeceği için paketin yüklenmesi gerekiyor.

Temel haberleşme python kodu:
import time
import json
import serial
import modbus_tk.defines as cst
from modbus_tk import modbus_rtu

if __name__ == “__main__”:
try:
# Connect to the slave
serial = serial.Serial(
port=’/dev/ttyUSB0′,
baudrate=9600,
bytesize=8,
parity=’N’,
stopbits=1,
xonxoff=0
)

master = modbus_rtu.RtuMaster(serial)
master.set_timeout(2.0)
master.set_verbose(True)
# Changing power alarm value to 100 W
# master.execute(1, cst.WRITE_SINGLE_REGISTER, 1, output_value=100)
dict_payload = dict()

while True:
data = master.execute(1, cst.READ_INPUT_REGISTERS, 0, 10)

dict_payload[“voltage”]= data[0] / 10.0
dict_payload[“current_A”] = (data[1] + (data[2] << 16)) / 1000.0 # [A]
dict_payload["power_W"] = (data[3] + (data[4] << 16)) / 10.0 # [W]
dict_payload["energy_Wh"] = data[5] + (data[6] << 16) # [Wh]
dict_payload["frequency_Hz"] = data[7] / 10.0 # [Hz]
dict_payload["power_factor"] = data[8] / 100.0
dict_payload["alarm"] = data[9] # 0 = no alarm
str_payload = json.dumps(dict_payload, indent=2)
print(str_payload)

time.sleep(1)

except KeyboardInterrupt:
print('exiting pzem script')
except Exception as e:
print(e)
finally:
master.close()

ESP 32 ile Rpi maliyetinden uyguna ayni çözüme ulasilabilir 😉

Şub 23

OpenSCAP ile bir sistemin güvenlik yapılandırma ayarlarını kontrol edebilir ve standartlara ve spesifikasyonlara dayalı kuralları kullanarak sistemi bir uzlaşma belirtisi açısından inceleyebiliriz.

Wazuh ölçeklenebilir, multi platformu, açık kaynaklı bir host-tabanlı intrusion detection (HIDS) sistemidir. Güçlü bir korelasyon ve analiz motoru olan OSSEC’in bir forku olarak doğmuştur. Wazuh Elastic Stack ve OpenSCAP ile entegre edilerek daha kapsamlı bir çözüm haline gelmiştir. Wazuh, log analizi, dosya bütünlüğü denetimi (file integrity checking), Windows kayıt defteri izleme (Windows registry monitoring), rootkit tespiti, gerçek zamanlı uyarı ve aktif response yapısına sahip olmakla birlikte Linux, OpenBSD, FreeBSD, dahil olmak üzere MacOSX, Solaris ve Windows gibi birçok işletim sisteminde çalışabilmektedir.

OpenSCAP, sistem yapılandırmalarını kontrol etmek ve güvenlik açığı olan uygulamaları tespit etmek için kullanılan bir OVAL (Open Vulnerability Assessment Language) ve XCCDF (Extensible Configuration Checklist Description Format) yorumlayıcısıdır.

OpenSCAP (Kaynak – https://lnkd.in/dS3pAj25), NIST tarafından sürdürülen bir dizi spesifikasyon olan SCAP’ı kullanır. SCAP, sistem güvenliğini sağlamak için standartlaştırılmış bir yaklaşım sağlamak üzere oluşturulmuştur. OpenSCAP temel olarak bir kontrol listesi içeriğini ifade etmenin standart bir yolu olan XCCDF’yi işler ve güvenlik kontrol listelerini tanımlar. Ayrıca CPE, CCE ve OVAL gibi diğer spesifikasyonlarla birleşerek SCAP onaylı ürünler tarafından işlenebilen SCAP ile ifade edilmiş bir kontrol listesi oluşturur (Kaynak – https://lnkd.in/dx8ANe5i).

Kurulum:
apt install openscap-common
apt install openscap-scanner
apt install openscap-utils
apt install ssg-base ssg-debderived ssg-debian ssg-nondebian ssg-applications

1. Sistemin güvenlik yapılandırma profilini XCCDF ile denetlersiniz.
2. Sistemdeki açıkları ve zafiyetleri OVAL ile tararsınız.

Tarama:
1. oscap xccdf eval –profile xccdf_org.ssgproject.content_profile_standard –report xccdf_report.html /usr/share/xml/scap/ssg/content/ssg-debian11-ds.xml
2. oscap oval eval –report oval_report.html /usr/share/xml/scap/ssg/content/ssg-debian11-oval.xml

Oca 11

USOM’dan veri çekme betiği

totalCount=10582 11.01.2025 tarihinde alınmıştır.


#!/bin/bash

# Toplam kayıt sayısı ve sayfa başına kayıt sayısı
totalCount=10582
perPage=20
totalPages=$(( (totalCount + perPage - 1) / perPage ))

# Çıktı dosyası
outputFile="all_data.json"

# JSON array başlangıcı
echo "[" > "$outputFile"

# Her sayfayı çek ve JSON'a ekle
for ((page=1; page/dev/null; then
if [[ -n "$response" && "$response" != "[]" ]]; then
echo "$response" | jq -c '.[]' >> "$outputFile"
success=1
break
else
echo "Empty JSON response for page $page. Retrying ($((retryCount + 1))/$maxRetries)..."
retryCount=$((retryCount + 1))
sleep 3 # 3 saniye bekle ve tekrar dene
fi
else
echo "Invalid JSON response for page $page: $response. Retrying ($((retryCount + 1))/$maxRetries)..."
retryCount=$((retryCount + 1))
sleep 3 # 3 saniye bekle ve tekrar dene
fi
done

# Başarısız olursa, hata mesajı yaz ve devam et
if [ $success -eq 0 ]; then
echo "Failed to fetch page $page after $maxRetries attempts. Skipping..."
fi

# Son sayfa değilse, JSON array'e virgül ekle
if [ $page -ne $totalPages ]; then
echo "," >> "$outputFile"
fi

# Her 100 sayfada 1 ms bekle
if (( page % 100 == 0 )); then
sleep 0.001
fi
done

# JSON array sonu
echo "]" >> "$outputFile"

echo "All data has been saved to $outputFile"

Page-page veri çektiğim için bazı atıkları kaldırmak lazım Colab’ta işleme kolayıma geldi:/

# Dosyayı oku ve veriyi ayrıştır
def read_and_combine_json(file_path):
combined_data = []
with open(file_path, "r", encoding="utf-8") as file:
for line in file:
line = line.strip()
if line.startswith("[") and line.endswith("]"): # JSON formatındaki satırları bul
try:
data = json.loads(line) # JSON satırını ayrıştır
combined_data.extend(data) # Veriyi birleştir
except json.JSONDecodeError as e:
print(f"JSON ayrıştırma hatası: {e}")
return combined_data

# JSON verisini dosyaya kaydet
def save_json(data, output_file):
with open(output_file, "w", encoding="utf-8") as file:
json.dump(data, file, indent=4, ensure_ascii=False)
print(f"JSON verisi {output_file} dosyasına kaydedildi.")

# Dosya yolu
input_file = "USOM_110125.json"
output_file = "combined_USOM_110125.json"

# JSON verisini oku ve birleştir
combined_data = read_and_combine_json(input_file)

# Birleştirilmiş JSON verisini kaydet
save_json(combined_data, output_file)

Eyl 12

Korumalı: Earthquake Prediction through Advanced Feature Engineering and Machine Learning Regression Techniques

Bu içerik parola ile korunmaktadır. Görmek için lütfen aşağı parolanızı girin:

Eyl 12

Ubuntu 22.04’ten 24.04’e güncelleme sonrası Timezone problemi

timedatectl list-timezones | grep -o 'Europe/Ist.*' ile timezones içinde Istanbul kontrolü yaptım.

Europe/Istanbul çıktısını görünce sevindim.

sudo timedatectl set-timezone Europe/Istanbul komutuyla set ettim.
Böyle bir hata ile karşılaştım : Failed to set time zone: Invalid or not installed time zone 'Europe/Istanbul'

sudo ln -sf /usr/share/zoneinfo/Europe/Istanbul /etc/localtime bu komutu verip tekrar Istanbul’u set etmeye çalıştım yine olmadı.

Çözüm olarak sudo apt install --reinstall tzdata ile tzdatayi yeniden yükleyince oldu, reinstall etmeden önce yüklü olduğunu check ettim vardı ama güncellemede bazı şeyler gittiğini düşünerek tekrar yükleyip problem giderilmiş oldu 🙂

Nis 17

Remote Raspbian OS’deki Mariadb’nin yedeğini Windows Lokaline yedekleyen C# desktop uygulaması

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.IO.Compression;
using System.Security.Cryptography;
using System.Text;
using System.Linq;
using System.Security.Policy;
using System.Threading.Tasks;
using System.Windows.Forms;

private void btnReports_Click(object sender1, EventArgs e1)
{

StreamReader sRead = File.OpenText(@”config.txt”);
string metin;
while ((metin = sRead.ReadLine()) != null)
{
// Okunan veriler textbox içerisine atılıyor.
string phrase = metin;
string[] words = phrase.Split(‘,’);

if (words[0] != null && words[1] != null && words[2] != null && words[3] != null)
{
server = words[0];
veritabaniAdi = words[1];
kullaniciAdi = words[2];
sifre = Descrpyt(words[3]);
}

}

// İşlem nesnesini oluşturun
string dateTimeString = DateTime.Now.ToString(“yyyy.MM.dd__HH.mm”);
Process process = new Process();

// Hedef dizini oluştur
string targetDirectory = @”C:\DB_YEDEK”;
if (!Directory.Exists(targetDirectory))
{
Directory.CreateDirectory(targetDirectory);
}

// Başlangıç bilgilerini ayarlayın
process.StartInfo.FileName = @”C:\Program Files\MySQL\MySQL Workbench 8.0 CE\mysqldump.exe”;
// –skip-triggers –no-create-info : parametrelerini kullanarak yalnızca verileri içeren ve tablo yapısını içermeyen bir SQL dosyası oluşturur.
process.StartInfo.Arguments = $” –result-file=\”C:\\DB_YEDEK\\{dateTimeString}.sql\” –user={kullaniciAdi} -p{sifre} –host={server} –port=3306 –default-character-set=utf8 –protocol=tcp –skip-triggers –no-create-info \”h4ck3r_charge\””;
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.RedirectStandardError = true;
process.StartInfo.CreateNoWindow = true;

// Olayları tanımlayın
process.OutputDataReceived += (sender, e) =>
{
if (!String.IsNullOrEmpty(e.Data))
{
Console.WriteLine(e.Data);
}
};
process.ErrorDataReceived += (sender, e) =>
{
if (!String.IsNullOrEmpty(e.Data))
{
Console.WriteLine(“Error: ” + e.Data);
}
};

// Komutu çalıştırın
process.Start();

// Çıktı ve hata akışlarını başlatın
Console.WriteLine(“VERİTABANI YEDEKLEME İŞLEMİ DEVAM EDİYOR…”);
//MessageBox.Show(“VERİTABANI YEDEKLEME İŞLEMİ DEVAM EDİYOR…”, “Bilgi”, MessageBoxButtons.OK, MessageBoxIcon.Information);
process.BeginOutputReadLine();

process.BeginErrorReadLine();

// İşlem tamamlanana kadar bekle
process.WaitForExit();

// Yedek dosyasını sıkıştırın
string backupFilePath = $”{targetDirectory}\\{dateTimeString}.sql”;
string compressedFilePath = $”{targetDirectory}\\{dateTimeString}.gz”;
using (FileStream fileToCompress = File.OpenRead(backupFilePath))
{
using (FileStream compressedFileStream = File.Create(compressedFilePath))
{
using (GZipStream compressionStream = new GZipStream(compressedFileStream, CompressionMode.Compress))
{
fileToCompress.CopyTo(compressionStream);
}
}
}

string inputFile = $”{targetDirectory}\\{dateTimeString}.sql”;
string compressedFile = $”{targetDirectory}\\{dateTimeString}.gz”;
string encryptedFile = $”{targetDirectory}\\{dateTimeString}.zip”;
string decryptedFile = $”{targetDirectory}\\{dateTimeString}.sql2″;
string password = “AnahtarSecret24April”;

// Dosyayı sıkıştır
CompressFile(inputFile, compressedFile);

// Dosyayı şifrele
EncryptFile(compressedFile, encryptedFile, password);

// Dosyayı çöz
//DecryptFile(encryptedFile, decryptedFile, password);

// Orijinal dosyayı sil
DeleteFile(inputFile);

Console.WriteLine(“Dosya sıkıştırma, şifreleme ve çözme işlemi tamamlandı.”);

Console.WriteLine(“Yedekleme tamamlandı.”);
MessageBox.Show($”VERİTABANI YEDEKLEME İŞLEMİ TAMAMLANDI…\n\n DOSYA KONUMU: {targetDirectory}\\{dateTimeString}.zip”, “Bilgi”, MessageBoxButtons.OK, MessageBoxIcon.Information);
}

static void CompressFile(string inputFile, string compressedFile)
{
using (FileStream inputStream = File.OpenRead(inputFile))
{
using (FileStream compressedStream = File.Create(compressedFile))
{
using (GZipStream gzipStream = new GZipStream(compressedStream, CompressionMode.Compress))
{
inputStream.CopyTo(gzipStream);
}
}
}
}

static void EncryptFile(string inputFile, string encryptedFile, string password)
{
byte[] salt = GenerateSalt(); // Tuz oluştur

using (Aes aesAlg = Aes.Create())
{
aesAlg.KeySize = 256; // 256-bit AES kullan
aesAlg.BlockSize = 128; // 128-bit blok boyutu
aesAlg.Padding = PaddingMode.PKCS7; // Dolgu modu
aesAlg.Mode = CipherMode.CBC; // CBC modu

// Anahtar ve IV oluştur
var keyDerivationFunction = new Rfc2898DeriveBytes(password, salt, 10000);
aesAlg.Key = keyDerivationFunction.GetBytes(aesAlg.KeySize / 8);
aesAlg.IV = keyDerivationFunction.GetBytes(aesAlg.BlockSize / 8);

using (FileStream inputFileStream = File.OpenRead(inputFile))
{
using (FileStream encryptedFileStream = File.Create(encryptedFile))
{
using (CryptoStream cryptoStream = new CryptoStream(encryptedFileStream, aesAlg.CreateEncryptor(), CryptoStreamMode.Write))
{
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = inputFileStream.Read(buffer, 0, buffer.Length)) > 0)
{
cryptoStream.Write(buffer, 0, bytesRead);
}
}
}
}
}
}

static void DecryptFile(string encryptedFile, string decryptedFile, string password)
{
byte[] salt = GenerateSalt(); //

using (Aes aesAlg = Aes.Create())
{
aesAlg.KeySize = 256; // 256-bit AES kullan
aesAlg.BlockSize = 128; // 128-bit blok boyutu
aesAlg.Padding = PaddingMode.PKCS7; // Dolgu modu
aesAlg.Mode = CipherMode.CBC; // CBC modu

// Anahtar ve IV oluştur
var keyDerivationFunction = new Rfc2898DeriveBytes(password, salt, 10000);
aesAlg.Key = keyDerivationFunction.GetBytes(aesAlg.KeySize / 8);
aesAlg.IV = keyDerivationFunction.GetBytes(aesAlg.BlockSize / 8);

try
{
using (FileStream encryptedFileStream = File.OpenRead(encryptedFile))
{
using (FileStream decryptedFileStream = File.Create(decryptedFile))
{
using (CryptoStream cryptoStream = new CryptoStream(encryptedFileStream, aesAlg.CreateDecryptor(), CryptoStreamMode.Read))
{
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = cryptoStream.Read(buffer, 0, buffer.Length)) > 0)
{
decryptedFileStream.Write(buffer, 0, bytesRead);
}
}
}
}
}
catch (CryptographicException ex)
{
Console.WriteLine(“Hata: ” + ex.Message);
}
}
}

static byte[] GenerateSalt()
{
byte[] salt = new byte[16];
using (var rng = new RNGCryptoServiceProvider())
{
rng.GetBytes(salt);
}
return salt;
}

static void DeleteFile(string filePath)
{
if (File.Exists(filePath))
{
File.Delete(filePath);
}
}

}

Şub 15

TFTP ile anahtarlara Firmware yükleme ve Config dosyalarını yedekleme

TFTP (Trivial File Transfer Protocol) kurulum faydalanılan link:

sudo apt install tftpd-hpa

sudo systemctl status tftpd-hpa

sudo nano /etc/default/tftpd-hpa

TFTP_USERNAME =”ftp”.

TFTP_DIRECTORY =”/tftp”

TFTP_ADDRESS =”:69″

TFTP_OPTIONS =” –secure –create”

sudo mkdir /tftp

sudo chown tftp:tftp /tftp

sudo systemctl restart tftpd-hpa

sudo systemctl status tftpd-hpa

 

 

Bazı test edilen anahtarlara ait güncel firmwareler:

ProCurve J9085A Switch 2610-24 R.11.123 Released on Mar 1, 2021
HP J9565A Switch 2615-8-PoE Released on Dec 6, 2022  A.15.16.0025 günceli A.15.16.0026
HP J9623A 2620-24 Switch Released on Nov 2, 2022 RA.16.04.0026 günceli  RA.16.04.0027
Aruba JL558A 2930F-48G-740W-PoE+-4SFP+ Switch WC.16.11.0011 Released on Apr 11, 2023 günceli WC.16.11.0015
HP J9773A 2530-24G-PoEP Switch YA.16.11.0011 Released on Apr 11, 2023 günceli  YA.16.11.0015
Aruba JL677A 6100 24G CL4 4SFP+ Swch ArubaOS-CX_6100-6000_10.11.1021 Released on May 15, 2023 günceli PL.10.12.1000
Dell EMC Networking N1524P/N1548P 6.7.1.20  günceli 6.7.1.21 18.03.2023
juniper / EX2200-48T-4G 12.3R8.7 ve 12.3R6.6  modelleri var güncel firmware araştırılıyor.

 

tftp_server_adresi_örnek: 10.1.1.1 olsun.  Secondary için güncel firmwareler yüklendikten sonra active imaj o seçilerek reboot edildikten sonra sorun olmazsa primary içinde yüklenebilir.

 

hp 2615 serisi için firmware güncelleme ve config yedeği alma:

copy tftp flash 10.1.1.1 A_15_16_0021.swi secondary allow-no-signature

copy running-config tftp://10.1.1.1/config-backups/hp2615-192.168.1.11/config.cfg

hp 2610 serisi için:

copy tftp flash 10.1.1.1 R_11_123.swi secondary

copy running-config tftp://10.1.1.1/config-backups/hp2610-192.168.1.51/config.cfg

hp 2620 serisi için:

copy tftp flash 10.1.1.1 RA_16_04_0025.swi secondary

copy running-config tftp://10.1.1.1/config-backups/hp2620-192.168.1.91/config.cfg

dell 1524 ve 1548 serisi için:

copy tftp://10.1.1.1/N1500v6.7.1.21.stk active

write file tftp://10.1.1.1/config-backups/dell1500-192.168.1.111/config.cfg

 

Gerekli güncellemeleri yaptıktan sonra https://metacpan.org/pod/App::Netdisco adresinden açık kaynaklı web destekli snmp ile cihazların her türlü bilgilerini toplayan güzel bir yazılım Netdisco‘yuda kurarsanız tadından yenmez.

 

Cisco anahtarlarda konfig yedeğini tftp sunucusuna yollama:

Periyodik yedeklemede Cisco IOS güzel/kullanışlı archive komutunu sunuyor.

archive

path tftp://10.1.1.1/config-backups/cisco-192.168.1.2/

maximum 14

time-period 60

write-memory

 

burada time-period 60 dk yani 1 saati ifade eder. Yedekleme sıklığını uzatmak istersek mesela 24 saatte bir için time-period 1440 set edilir.

 

Umarım faydalı olur 🙂

 

 

Eski yazılar «