scp보다 좀 더 기능이 많은 sftp도 있습니다.
sftp도 ssh를 기반으로 실행되며 sftp로 remote server로 접속 후 get 또는 put 명령으로 파일일 내려받거나 올릴 수 있습니다. shell(interactive command) 명령도 사용할 수 있습니다.
먼저 sftp로 remote server에 접속합니다.
$ sftp tongchun@10.10.0.118
tongchun@10.10.0.118's password:
Connected to tongchun@10.10.0.118.
sftp>
sftp로 접속하면 sftp 프롬프트 창이 생성됩니다.
sftp 프롬프트 창에서 ls -al, cd, mkdir 등의 interactive command를 실행할 수 있습니다.
사용할 수 있는 interactive command 명령은 아래 링크에서 확인할 수 있습니다.
https://www.mankier.com/1/sftp#Interactive_Commands
sftp - secure file transfer program - man page | ManKier
Batch mode reads a series of commands from an input batchfile instead of stdin. Since it lacks user interaction it should be used in conjunction with non-interactive authentication to obviate the need to enter a password at connection time (see sshd(8) and
www.mankier.com
가장 많이 사용하는 명령은 cd, mkdir, pwd, get, put, exit 정도입니다.
sftp로 remote server 접속 후 cd로 파일을 내려받거나 올리고자 하는 경로로 이동합니다.
그리고 get으로 파일을 다운 받거나, put으로 파일을 올릴 수 있습니다.
sftp 프롬프트 창을 종료하려면 exit 명령을 실행하면 됩니다.
위에서 접속한 10.10.0.118 서버에서 pwd 명령으로 디렉토리 경로를 확인해 봅니다.
sftp> pwd
Remote working directory: /home/tongchun
pwd 명령을 실행하면 remote server의 디렉토리 경로를 확인할 수 있습니다.
lpwd 명령을 실행하면 현재의 로컬 PC의 경로를 확인할 수 있습니다.
sftp> lpwd
Local working directory: /Users/tongchunkim
이번엔 파일 리스트를 확인해 봅니다.
sftp> ls -l
drwxrwxr-x 5 tongchun tongchun 39 Apr 17 05:59 go
-rw-rw-r-- 1 tongchun tongchun 127928770 Apr 11 22:09 go1.12.4.linux-amd64.tar.gz
-rw-r--r-- 1 root root 6140 Nov 12 2015 mysql-community-release-el7-5.noarch.rpm
go1.12.4.linux-amd64.tar.gz 파일을 다운받아 보겠습니다. 명령어는 get 입니다.
sftp> get go1.12.4.linux-amd64.tar.gz
Fetching /home/tongchun/go1.12.4.linux-amd64.tar.gz to go1.12.4.linux-amd64.tar.gz
/home/tongchun/go1.12.4.linux-amd64.tar.gz 100% 122MB 57.0MB/s 00:02
잘 받아졌는지 로컬 PC의 파일 리스트를 확인해 봅니다. 로컬 PC에 명령을 보내려면 remote server에서 사용한 명령 앞에 l를 붙여줍니다.
sftp> lls -l
total 263904
drwxr-xr-x 3 tongchunkim staff 96 7 30 2018 AndroidStudioProjects
drwx------@ 4 tongchunkim staff 128 12 12 2017 Applications
drwx------+ 6 tongchunkim staff 192 4 22 19:08 Desktop
drwx------+ 31 tongchunkim staff 992 3 18 10:00 Documents
drwx------+ 75 tongchunkim staff 2400 4 25 16:54 Downloads
drwx------@ 10 tongchunkim staff 320 1 28 19:18 Dropbox
drwx------@ 83 tongchunkim staff 2656 4 6 14:16 Library
drwx------+ 3 tongchunkim staff 96 12 12 2017 Movies
-rw-r--r-- 1 tongchunkim staff 127928770 4 26 14:44 go1.12.4.linux-amd64.tar.gz
-rw-r--r-- 1 tongchunkim staff 9180 1 12 2018 jmeter.log
drwxr-xr-x 14 tongchunkim staff 448 2 6 2018 macaronRamlProject
-rw-r--r-- 1 tongchunkim staff 26484 7 29 2018 package-lock.json
drwxr-xr-x 3 tongchunkim staff 96 9 16 2018 snakepit
go1.12.4.linux-amd64.tar.gz이 보이네요.
이번에는 파일을 업로드해 보겠습니다. jmeter.log 파일을 올려봅시다. 파일을 올리는 명령은 put입니다.
sftp> put jmeter.log
Uploading jmeter.log to /home/tongchun/jmeter.log
jmeter.log 100% 9180 268.9KB/s 00:00
파일이 잘 올라갔는지 확인해 봅니다.
sftp> ls -l
drwxrwxr-x 5 tongchun tongchun 39 Apr 17 05:59 go
-rw-rw-r-- 1 tongchun tongchun 127928770 Apr 11 22:09 go1.12.4.linux-amd64.tar.gz
-rw-r--r-- 1 tongchun tongchun 9180 Apr 26 01:49 jmeter.log
-rw-r--r-- 1 root root 6140 Nov 12 2015 mysql-community-release-el7-5.noarch.rpm
파일이 잘 올라가네요.
sftp를 종료할 때는 exit 입니다.
다른 interactive command를 확인하면 더 유용하게 사용할 수 있을 것 같습니다.
rcp remote 상에서의 파일 전송 (0) | 2021.07.06 |
---|---|
rlogin (0) | 2021.05.12 |
리눅스 환경 변수 설정 (0) | 2021.03.27 |
linux 패키지 관리 프로그램 snap apt (0) | 2021.03.26 |
ubuntu 에서 github-desktop 설치하기 (0) | 2021.03.26 |
2. 원격접속과 파일전송
■ 원격 접속 명령어 : telnet, rlogin, rsh, ssh
■ 파일 전송 명령어 : ftp, rcp, scp, sftp
■ 암호화를 하지 않는 명령어: telnet, ftp, rlogin, rsh, rcp
■ 암호화를 하는 명령어 : ssh, scp, sftp
3. 원격접속 & 파일전송 명령어(System V 계열)
가. telnet
1) telnet 명령어 실행 모드
▪ 대화형 모드 (Interractive Mode)
# telnet
telnet>
▪ 비대화형 모드(Noninterractive Mode)
# telnet solaris254
# telnet 172.16.8.254
2) 기본 사용법
# telnet 172.16.8.254
# telnet 172.16.8.254 23 (/etc/services 정의)
# telnet solaris254 (/etc/hosts 정의, /etc/inet/ipnodes 정의)
/etc/inet/hosts <--- /etc/hosts
/etc/inet/hosts <--- /etc/inet/ipnodes
---------------------------------------
포트 서비스명
---------------------------------------
20,21 FTP
22 SSH
23 TELNET
25 SMTP
53 DNS
67,68 DHCP(Bootp)
80 WEB
110 POP3
111 sunrpc
123 NTP
143 IMAP
---------------------------------------
3) telnet 연결 화면시 에러 메세지
가) 상대편 서버의 이름을 잘못 지정한 경우
메시지 : Unknown host
나) 서버가 정상적으로 동작하지 않는 경우
메시지 : Connection refused
메시지 : Connection timed out
- ping 명령으로 확인
다) 로그인시 암호가 틀린 경우
메시지 : Login incorrect
라) root 사용자로 로그인시 CONSOLE 변수가 잘못 지정된 경우
메시지 : Not on system console
- Solaris 기본 설정으로 /etc/default/login 파일을 열어서 CONSOLE변수 부분을 #으로 주석처리
마) TCP_Wrapper에 의해 막힌 경우
메시지 : Connection to solaris254 closed by foreign host.
가. ftp
1) ftp 명령어 실습1
가) 업로드/다운로드 포인터맞추기(upload/download pointer)
[참고] 업로드/다운로드 포인터
===== HOSTA ===== ===== HOSTB =====
현재 디렉토리 ----------------> 홈디렉토리
(예) /test /
upload /tmp/test.solarisXXX ---> /test
download /root <------------------ /test/test.solarisXXX
나) 편리한 기능 설정(FTP function)
ftp> bin (ftp> binary) binary모드로 전송
ftp> ascii ascii 모드로 전송
ftp> hash 8K마다 #표시
ftp> prompt 대화형모드설정(토글)
다) 업로드/다운로드(upload/download)
ftp> put test.solarisXXX 한개의 파일 업로드
ftp> get test.solarisXXX 한개의 파일 다운로드
ftp> mput test.* 여러개의 파일 업로드
ftp> mget test.* 여러개의 파일 다운로드
라). 확인 및 접속 종료
ftp> ls [-al] 파일 확인(서버쪽)
ftp> dir [-al] 파일 확인(서버쪽)
[참고] ftp> ! ls 파일 확인(자기자신)
[참고] 자동 파일 업/다운로드 스크립트
# rcp 172.16.8.254:/root/shell/suto_ftp.sh /test
# cat /test/auto_ftp.sh
내용
------------------------------------------------------
#! bin/ksh
ftp -n 172.16.8.254 21 << EOF
user user01 user01 /* user <사용 ID> <사용P/W> */
bin /* 편리한 기능 설정*/
hash
prompt
cd download /* 업로드/다운로드 포인터 맞추기 */
lcd /test
put test.solarisXXX /* 파일 전송 */
bye
EOF
------------------------------------------------------
3) ftp 명령어 실습 2
4) ftp 관련 파일들
가) /etc/ftpd/ftpusers FTP 접속 불가 사용자 정의
(FTP 서버 사용자 기본 정책)
- root 사용자는 FTP 서버에 접속 불가능
- 일반 사용자는 접속 가능(예: user01, user02....)
나) /etc/shells FTP 접속시 할당할 수 있는 쉘 정의
- ftp 접속시 해당유저에 할당되어 있는(/etc/passwd파일의 끝) 쉘을 기본으로 할당
- /etc/shells가 있으면 파일 안에 있는 설정의 쉘을 할당 받는다.
-> 해당 쉘을 사용하는 사용자만 FTP 서버에 로그인이 가능하다
[EX] 실무적인 예(/etc/shells)
사용자 (예: user01, user02 ...., test01, test02, ...., solaris01, solaris02,...)
/bin/ksh /bin/csh /bin/bash
- 호스트별 FTP 접근 제어 : /etc/ftpd/ftphosts, TCP_Wrapper, Firewall(IPFilter), ...
- 사용자별 FTP 접근 제어 : /etc/ftpd/ftpusers
- 쉘별 FTP 접근 제어 : /etc/shells
4. 원격접속 & 파일전송 명령어(BSD계열)
Remote Connection & File Transmission for BSD
■ rlogin 명령어 Remote Login CMD
■ rsh 명령어 Remote Shell CMD
■ rcp 명령어 Remote Copy CMD
가. r 명령어(CMD) 동작원리
Remote Connection & File Transmission for BSD
HOSTA ----------> HOSTB
# telnet B Auth(ID/PASS)
# rlogin B Auth(/etc/hosts.equiv, ~/.rhosts)
/etc/hosts.equiv System wild Conf.
~/.rhosts System specific Conf.
____________________
(호스트이름) (사용자이름)
HOSTA
HOSTA user01
+
HOSTA -------> HOSTB
/etc/hosts.equiv (All users, root 사용자 인증 제외)
---------------------
HOSTA HOSTA의 모든 사용자 인증(단, 이름이 같은 사용자)
HOSTA + HOSTA의 모든 사용자 인증
HOSTA user01 HOSTA의 user01 사용자만 인증
+ user01 모든 호스트의 user01 사용자 인증
+ + 모든 호스트의 모든 사용자 인증
HOSTA -------> HOSTB
~user01/.rhosts (user01)
---------------------
HOSTA HOSTA의 모든 사용자 인증(단, 이름이 같은 사용자)
HOSTA + HOSTA의 모든 사용자 인증
HOSTA user01 HOSTA의 user01 사용자만 인증
+ user01 모든 호스트의 user01 사용자 인증
+ + 모든 호스트의 모든 사용자 인증
나. rlogin
- 명령어 사용법
# rlogin hostname
# rlogin -l username hostname (-l : login name)
# rlogin username@hostname
다. rsh
# rsh hostname CMD
# rsh 172.16.8.254 hostname
# rsh 172.16.8.254 ls -l /tmp
# rsh 172.16.8.254 ls -l /root/docs
라. rcp
# rcp file1 172.16.8.254:/tmp
# rcp 172.16.8.254:/tmp/file1 /tmp
# rcp -r dir1 172.16.8.254:/tmp
# rcp -r 172.16.8.254:/root/shell /root
# rcp -r 172.16.8.254:/root/* .
# rcp file1 user01@172.16.8.254:/tmp
[참고] .rhosts 파일 정책(Policy)
(a). 사용자 홈디렉토리에 .rhosts 파일을 정기적으로 지우는정책
# find /export/home -name .rhosts -type f -exec rm {} \;
(b). 사용자 홈디렉토리에 .rhosts 파일을 못 만들도록 하는 정책
user01 Home Directory : /export/home/user01
# cd /export/home/user01
# mkdir .rhosts (rwxr-xr-x root other)
# touch .rhosts/.notperm (rw-r--r-- root other)
# chmod 000 .rhosts
# chmod 000 .rhosts/.notperm
5. 원격접속 & 파일전송 명령어(암호화 방식)
Remote Connection & File Transmission for Securiy
■ ssh 명령어 Secure Shell
■ scp 명령어 Secure Copy
■ sftp 명령어 Secure FTP
가. ssh
- rsh를 기반으로 만들어져 사용법이 비슷하다.
# ssh hostname
# ssh -l username hostname
# ssh username@hostname
나. sftp
- ftp 명령어를 기반으로 만들어져 사용법이 비슷하다.
# sftp 172.16.8.254
# sftp user01@solaris254
다. scp
- rcp 명령어를 기반으로 만들어져 사용법이 비슷하다.
# scp /tmp/file1 172.16.8.254:/tmp
# scp -r /root/test 172.16.8.254:/tmp
# scp -r 172.16.8.254:/tmp/* /test
# scp -r file1 user01@172.16.8.254:/tmp
sftp - telnet ,ssh 상에서 파일 업로드/ 다운로드 전송 (0) | 2021.07.06 |
---|---|
rlogin (0) | 2021.05.12 |
리눅스 환경 변수 설정 (0) | 2021.03.27 |
linux 패키지 관리 프로그램 snap apt (0) | 2021.03.26 |
ubuntu 에서 github-desktop 설치하기 (0) | 2021.03.26 |
예전에 디지털 디톡스에 집착하던 친구가 있었다. 그 당시의 나는 굳이 저렇게 해야 되는걸까 하면서 유난떤다고 생각했던 기억이 난다.
그랬던 내가 요즘 스스로 디지털 디톡스라고 되뇌이며 핸드폰을 멀리하기를 하고 있다.
아- 중독인 사람들이 하는거구나.
좀더 구체적으로 말하자면 현실을 외면하고 핸드폰으로 sns를 보고 있으면서 나도 그들 틈에 껴서 함께이기를 바라는 것 같다.
지금 나는 현실에서 꽤나 힘든 시간을 보내고 있으니깐 그걸 도피하기 위해서 반짝반짝한 이미지를 보고 있으면 나아지는 것 같지만 사실은 그냥 도피일뿐이다. 현실로 돌아오면 느껴지는 피로감들.
조금씩 핸드폰을 내려놓고 현실을 보려고 노력한다.
그동안은 달리기를 하러 갈때도 핸드폰으로 nrc를 켜고 꼭 인스타에 올렸었는데 이제는 일부러 놓고 간다.
손목시계와 헤어밴드 그리고 비상용 신용카드 한장.
길거리의 풍경이 이랬었구나. 여기에도 꽃들이 많구나. 이쯤 오면 1키로 구간이었던가? 지금쯤이면 조금더 가야되지 않았을까? 엄지발가락으로 밀어낸다는 느낌이 이거구나. 발목이 많이 상태가 안좋은것 같아.
그동안 잊고 지나가던 풍경들이 조금씩 더 보이기 시작한다.
조금더 무서워하던 내 모습에 직면하기 시작한다.
어제는 달리기 하던 중에 도로를 지나가던 달팽이를 보았어. 요즘에 비도 많이 오고 해서 그런지 천변가에서 도로쪽으로 횡당하는 중이었지. 처음엔 그저 피해가다가 다시 돌아가서 달팽이를 맞은편 수풀로 옮겨주고 왔다.
핸드폰을 가지고 왔으면 또 기록을 본다고 하면서 sns도 조금씩 보면서 달팽이따위는 신경도 안썼겠지.
아 난 현실에 있구나.
만족스럽거나 행복한 현실은 아니지만 단단한 땅에 굳건히 서 있는 현실 속의 사람.이 되었으면 해.
누군가 보고 싶다는 것이 (0) | 2021.05.25 |
---|---|
오늘의 등교길 (0) | 2021.05.24 |
ref by
https://velog.io/@ohzzi/Entity-DAO-DTO가-무엇이며-왜-사용할까
Entity, DAO, DTO가 무엇이며 왜 사용할까?
개인적으로 Spring Boot를 가지고 CRUD를 구현한 Todo-list를 만들어면서, Spring Data JPA를 사용하게 되었다. JPA를 사용하면서, 생전 처음 보는 Entity, DAO, DTO 개념을 사용하게 되었는데, 앞으로 계속 많이
velog.io
개인적으로 Spring Boot를 가지고 CRUD를 구현한 Todo-list를 만들어면서, Spring Data JPA를 사용하게 되었다. JPA를 사용하면서, 생전 처음 보는 Entity, DAO, DTO 개념을 사용하게 되었는데, 앞으로 계속 많이 쓰게 될 것 같아서 정리하는 시간을 가지려고 한다.
Entity 클래스는 DB의 테이블에 존재하는 Column들을 필드로 가지는 객체를 말한다. Entity는 DB의 테이블과 1대 1로 대응되며, 때문에 테이블이 가지지 않는 컬럼을 필드로 가져서는 안된다. 또한 Entity 클래스는 다른 클래스를 상속받거나 인터페이스의 구현체여서는 안된다.
예를 들어 post 라는 테이블이 title, content, author 라는 컬럼들을 가지고 있다면, 이에 대응하는 Entity 클래스 Post는
@Entity public class Post { private String title; private String content; private String author; }
와 같이 post 테이블의 컬럼들을 필드로 가져야 한다.
JPA를 사용할 때 Entity 클래스에는 @Entity 어노테이션을 붙여서 Entity임을 명시해 줘야 하며, 내부의 필드에는 @Column, @Id 어노테이션 등을 사용한다. Entity는 외부에서 최대한 Entity의 Getter를 사용하지 않도록 내부에 로직을 구현하는데, 이 때 Domain 로직만 구현하고 Presentation 로직은 구현하지 않는다.
Entity의 Getter 사용을 최대한 피하라고 했지만, 기본적으로 Entity를 만들 때 Getter는 만들어줘야 한다. 그런데 이동욱님이 쓰신 책을 보니, Entity 클래스에서 Setter를 만드는 것은 피하라는 조언이 있었다.
일반적으로 자바 클래스를 만들때 private 필드들을 가지고 습관적으로 Getter와 Setter를 만들고는 하는데, 문제는 Setter의 사용이 Entity의 일관성을 해칠 수 있다는 것이다.
Setter를 무분별하게 사용하게 되면, Entity의 인스턴스 값들이 언제 어디서 변하는지 명확히 알 수 없다. 따라서 Setter 대신 다른 방법으로 필드에 값을 넣어 주는 것이 좋다. 그런데 일반적으로 생각할 수 있는 인스턴스의 생성 시점에 생성자로 필드에 값을 넣어주는 방법 또한 그다지 좋지 않은 방법일 수 있는데, 생성자에 현재 넣는 값이 어떤 필드인지 명확히 알 수 없고, 매개변수끼리의 순서가 바뀌더라도 코드가 모두 실행되기 전까지는 문제를 알 수 없다는 단점이 있기 때문이다.
따라서 Builder 패턴을 사용하는 것이 가장 좋다. 멤버 변수가 많아지더라도 어떤 값을 어떤 필드에 넣는지 코드를 통해 확인할 수 있고, 필요한 값만 집어넣는 것이 가능하기 때문이다.
Entity 클래스 생성 및 Builder 패턴 예시@Getter @Entity @NoArgsConstructor public class Membmer member { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private long id; private String name; private String email; @Column(length = 13, nullable = false) private String phoneNumber; @Builder public Member(long id, String name, String email, String phoneNumber) { this.id = id; this.name = name; this.email = email; this.phoneNumber = phoneNumber; } } // 사용 방법 Member member = new member.builder() .name("홍길동") .email("test@gmail.com") .phoneNumber("010-1234-5678") .build();
DAO는 Data Access Object의 약자로, 실제로 DB에 접근하는 객체다. DAO는 프로젝트의 서비스 모델과 실제 데이터베이스를 연결하는 역할을 하며, JPA에서는 DB에 데이터를 CRUD 하는 Repository 객체들이 DAO라고 볼 수 있다.
엄밀히 말하면 Repository가 DAO를 대체한다고 보는 것이 맞는 것 같은데, DAO와 Repository 모두 DB에 직접 쿼리를 날려 CRUD를 하는 것은 동일하나, 개념적인 측면에서 차이가 있는 것 같다. 참고 자료를 한번 가져와봤다.
DAO와 REPOSITORY 모두 퍼시스턴스 로직에 대한 객체-지향적인 인터페이스를 제공하고 도메인 로직과 퍼시스턴스 로직을 분리하여 관심의 분리(separation of concerns) 원리를 만족시키는데 목적이 있다. 그러나 비록 의도와 인터페이스의 메소드 시그니처에 유사성이 존재한다고 해서 DAO와 REPOSITORY를 동일한 패턴으로 취급하는 것은 성급한 일반화의 오류를 범하는 것이다.
DAO는 퍼시스턴스 로직인 Entity Bean을 대체하기 위해 만들어진 개념이다. DAO가 비록 객체-지향적인 인터페이스를 제공하려는 의도를 가지고 있다고 하더라도 실제 개발 시에는 하부의 퍼시스턴스 메커니즘이 데이터베이스라는 사실을 숨기려고 하지 않는다. DAO의 인터페이스는 데이터베이스의 CRUD 쿼리와 1:1 매칭되는 세밀한 단위의 오퍼레이션을 제공한다. 반면 REPOSITORY는 메모리에 로드된 객체 컬렉션에 대한 집합 처리를 위한 인터페이스를 제공한다. DAO가 제공하는 오퍼레이션이 REPOSITORY 가 제공하는 오퍼레이션보다 더 세밀하며, 결과적으로 REPOSITORY에서 제공하는 하나의 오퍼레이션이 DAO의 여러 오퍼레이션에 매핑되는 것이 일반적이다. 따라서 하나의 REPOSITORY 내부에서 다수의 DAO를 호출하는 방식으로 REPOSITORY를 구현할 수 있다.
출처 : http://egloos.zum.com/aeternum/v/1160846
솔직히 완벽히 이해되지는 않는다. 이 부분은 개념적으로 좀 더 공부가 필요할 것 같다.
DTO는 Data Transfer Object의 약자로, 계층 간 데이터 교환 역할을 한다. DB에서 꺼낸 데이터를 저장하는 Entity를 가지고 만드는 일종의 Wrapper라고 볼 수 있는데, Entity를 Controller 같은 클라이언트단과 직접 마주하는 계층에 직접 전달하는 대신 DTO를 사용해 데이터를 교환한다.
DTO는 그저 계층간 데이터 교환이 이루어 질 수 있도록 하는 객체이기 때문에, 특별한 로직을 가지지 않는 순수한 데이터 객체여야 한다. 또한 DB에서 꺼낸 값을 DTO에서 임의로 조작할 필요가 없기 때문에 DTO에는 Setter를 만들 필요가 없고 생성자에서 값을 할당한다. 개인적으로는 생성자 또한 사용하지 않고 Entity처럼 Builder 패턴을 통해 값을 할당하는 것이 가장 좋은 것 같다.
Entity와 DTO를 분리하는 이유
Entity의 값이 변하면 Repository 클래스의 Entity Manager의 flush가 호출될 때 DB에 값이 반영되고, 이는 다른 로직들에도 영향을 미친다. 때문에 View와 통신하면서 필연적으로 데이터의 변경이 많은 DTO 클래스를 분리해주어야 한다.
또한 도메인 설계가 아무리 잘 되었다 해도 Getter만을 이용해서 원하는 데이터를 표시하기 어려운 경우가 발생할 수 있는데, 이 경우에 Entity와 DTO가 분리되어 있지 않다면 Entity 안에 Presentation을 위한 필드나 로직이 추가되게 되어 객체 설계를 망가뜨리게 된다. 때문에 이런 경우에는 분리한 DTO에 Presentation 로직 정도를 추가해서 사용하고, Entity에는 추가하지 않아서 도메인 모델링을 깨뜨리지 않는다.
DTO와 VO와의 차이
VO(Value Object)도 DTO와 동일한 개념이다. 다만 DTO와의 차이는, DTO는 데이터를 계층간 교환(Transfer)하는데 의미가 있고, VO는 읽기만 가능한 read-only 속성을 가진 객체로서 데이터 그 자체에 의미를 두고 있다는 점이다.
참고자료
https://gmlwjd9405.github.io/2018/12/25/difference-dao-dto-entity.html
http://egloos.zum.com/aeternum/v/1160846
https://iri-kang.tistory.com/5
mongodb user 생성관리(몽고 db 공식) (0) | 2021.05.27 |
---|---|
mongodb user 생성 관리 (0) | 2021.05.27 |
database dml / ddl / dcl (0) | 2021.05.14 |
궃이.. 이걸 따로 포스팅 하는게 의미가 있을긴 하지만..
db.updateUser( username, update, writeConcern )
Updates the user's profile on the database on which you run the method. An update to a field completely replaces the previous field's values. This includes updates to the user's roles array.
WARNING
When you update the roles array, you completely replace the previous array's values. To add or remove roles without replacing all the user's existing roles, use the db.grantRolesToUser()or db.revokeRolesFromUser() methods.
The db.updateUser() method uses the following syntax:
TIP
Starting in version 4.2 of the mongo shell, you can use the passwordPrompt() method in conjunction with various user authentication/management methods/commands to prompt for the password instead of specifying the password directly in the method/command call. However, you can still specify the password directly as you would with earlier versions of the mongo shell.
db.updateUser( |
"<username>", |
{ |
customData : { <any information> }, |
roles : [ |
{ role: "<role>", db: "<database>" } | "<role>", |
... |
], |
pwd: passwordPrompt(), // Or "<cleartext password>" |
authenticationRestrictions: [ |
{ |
clientSource: ["<IP>" | "<CIDR range>", ...], |
serverAddress: ["<IP>", | "<CIDR range>", ...] |
}, |
... |
], |
mechanisms: [ "<SCRAM-SHA-1|SCRAM-SHA-256>", ... ], |
passwordDigestor: "<server|client>" |
}, |
writeConcern: { <write concern> } |
) |
The db.updateUser() method has the following arguments.
ParameterTypeDescription
username | string | The name of the user to update. |
update | document | A document containing the replacement data for the user. This data completely replaces the corresponding data for the user. |
writeConcern | document | Optional. The level of write concern for the update operation. The writeConcern document takes the same fields as the getLastError command. |
The update document specifies the fields to update and their new values. All fields in the update document are optional, but must include at least one field.
The update document has the following fields:
FieldTypeDescription
customData | document | Optional. Any arbitrary information. |
roles | array | Optional. The roles granted to the user. An update to the roles array overrides the previous array's values. |
pwd | string | Optional. The user's password. The value can be either:
Starting in version 4.2 of the mongo shell, you can use the passwordPrompt() method in conjunction with various user authentication/management methods/commands to prompt for the password instead of specifying the password directly in the method/command call. However, you can still specify the password directly as you would with earlier versions of the mongoshell. |
authenticationRestrictions | array | Optional. The authentication restrictions the server enforces upon the user. Specifies a list of IP addresses and CIDR ranges from which the user is allowed to connect to the server or from which the server can accept users. New in version 3.6. |
mechanisms | array | Optional. The specific SCRAM mechanism or mechanisms for the user credentials. If authenticationMechanisms is specified, you can only specify a subset of the authenticationMechanisms. If updating the mechanisms field without the password, you can only specify a subset of the user's current mechanisms, and only the existing user credentials for the specified mechanism or mechanisms are retained. If updating the password along with the mechanisms, new set of credentials are stored for the user. Valid values are:
|
passwordDigestor | string | Optional. Indicates whether the server or the client digests the password. Available values are:
|
In the roles field, you can specify both built-in roles and user-defined roles.
To specify a role that exists in the same database where db.updateUser() runs, you can either specify the role with the name of the role:
"readWrite" |
Or you can specify the role with a document, as in:
{ role: "<role>", db: "<database>" } |
To specify a role that exists in a different database, specify the role with a document.
New in version 3.6.
The authenticationRestrictions document can contain only the following fields. The server throws an error if the authenticationRestrictions document contains an unrecognized field:
Field NameValueDescription
clientSource | Array of IP addresses and/or CIDRranges | If present, when authenticating a user, the server verifies that the client's IP address is either in the given list or belongs to a CIDR range in the list. If the client's IP address is not present, the server does not authenticate the user. |
serverAddress | Array of IP addresses and/or CIDRranges | A list of IP addresses or CIDR ranges to which the client can connect. If present, the server will verify that the client's connection was accepted via an IP address in the given list. If the connection was accepted via an unrecognized IP address, the server does not authenticate the user. |
IMPORTANT
If a user inherits multiple roles with incompatible authentication restrictions, that user becomes unusable.
For example, if a user inherits one role in which the clientSource field is ["198.51.100.0"]and another role in which the clientSource field is ["203.0.113.0"] the server is unable to authenticate the user.
For more information on authentication in MongoDB, see Authentication.
The db.updateUser() method wraps the updateUser command.
If run on a replica set, db.updateUser() is executed using majority write concern by default.
WARNING
By default, db.updateUser() sends all specified data to the MongoDB instance in cleartext, even if using passwordPrompt(). Use TLS transport encryption to protect communications between clients and the server, including the password sent by db.updateUser(). For instructions on enabling TLS transport encryption, see Configure mongod and mongos for TLS/SSL.
MongoDB does not store the password in cleartext. The password is only vulnerable in transit between the client and the server, and only if TLS transport encryption is not enabled.
You must have access that includes the revokeRole action on all databases in order to update a user's rolesarray.
You must have the grantRole action on a role's database to add a role to a user.
To change another user's pwd or customData field, you must have the changePassword and changeCustomData actions respectively on that user's database.
To modify your own password and custom data, you must have privileges that grant changeOwnPassword andchangeOwnCustomData actions respectively on the user's database.
Given a user appClient01 in the products database with the following user info:
{ |
_id : "products.appClient01", |
userId : UUID("c5d88855-3f1e-46cb-9c8b-269bef957986"), // Starting in MongoDB 4.0.9 |
user : "appClient01", |
db : "products", |
customData : { empID : "12345", badge : "9156" }, |
roles : [ |
{ |
role : "readWrite", |
db : "products" |
}, |
{ |
role : "read", |
db : "inventory" |
} |
], |
mechanisms : [ // Starting in MongoDB 4.0 |
"SCRAM-SHA-1", |
"SCRAM-SHA-256" |
], |
authenticationRestrictions : [ { |
clientSource: ["69.89.31.226"], |
serverAddress: ["172.16.254.1"] |
} ] |
} |
The following db.updateUser() method completely replaces the user's customData and roles data:
use products |
db.updateUser( "appClient01", |
{ |
customData : { employeeId : "0x3039" }, |
roles : [ |
{ role : "read", db : "assets" } |
] |
} ) |
The user appClient01 in the products database now has the following user information:
{ |
_id : "products.appClient01", |
userId : UUID("c5d88855-3f1e-46cb-9c8b-269bef957986"), // Starting in MongoDB 4.0.9 |
user : "appClient01", |
db : "products", |
customData : { employeeId : "0x3039" }, |
roles : [ |
{ |
role : "read", |
db : "assets" |
} |
], |
mechanisms : [ // Starting in MongoDB 4.0 |
"SCRAM-SHA-1", |
"SCRAM-SHA-256" |
], |
authenticationRestrictions : [ { |
clientSource: ["69.89.31.226"], |
serverAddress: ["172.16.254.1"] |
} ] |
} |
NOTE
To use SCRAM-SHA-256, the featureCompatibilityVersion must be set to 4.0. For more information on featureCompatibilityVersion, see View FeatureCompatibilityVersion andsetFeatureCompatibilityVersion.
The following operation updates a user who currently have both SCRAM-SHA-256 and SCRAM-SHA-1credentials to have only SCRAM-SHA-256 credentials.
NOTE
use reporting |
db.updateUser( |
"reportUser256", |
{ |
mechanisms: [ "SCRAM-SHA-256" ] |
} |
) |
db.updateUser() — MongoDB Manual
Reference > mongo Shell Methods > User Management Methods db.updateUser( username, update, writeConcern )Updates the user's profile on the database on which you run the method. An update to a field completely replaces the previous field's values. This incl
docs.mongodb.com
MongoDB employs role-based access control (RBAC) to determine access for users. A user is granted one or more roles that determine the user's access or privileges to MongoDB resources and the actions that user can perform. A user should have only the minimal set of privileges required to ensure a system of least privilege.
Each application and user of a MongoDB system should map to a distinct user. This access isolation facilitates access revocation and ongoing user maintenance.
If you have enabled access control for your deployment, you can use the localhost exception to create the first user in the system. This first user must have privileges to create other users. As of MongoDB 3.0, with the localhost exception, you can only create users on the admin database. Once you create the first user, you must authenticate as that user to add subsequent users. Enable Access Control provides more detail about adding users when enabling access control for a deployment.
For routine user creation, you must possess the following permissions:
The userAdmin and userAdminAnyDatabase built-in roles provide createUser and grantRole actions on their respective resources.
To create a user in a MongoDB deployment, you connect to the deployment, and then use the db.createUser() method or createUser command to add the user.
The following operation creates a user in the reporting database with the specified name, password, and roles.
TIP
Starting in version 4.2 of the mongo shell, you can use the passwordPrompt() method in conjunction with various user authentication/management methods/commands to prompt for the password instead of specifying the password directly in the method/command call. However, you can still specify the password directly as you would with earlier versions of the mongo shell.
use reporting |
db.createUser( |
{ |
user: "reportsUser", |
pwd: passwordPrompt(), // or cleartext password |
roles: [ |
{ role: "read", db: "reporting" }, |
{ role: "read", db: "products" }, |
{ role: "read", db: "sales" }, |
{ role: "readWrite", db: "accounts" } |
] |
} |
) |
Enable Access Control provides more details about enforcing authentication for your MongoDB deployment.
Users that will authenticate to MongoDB using an external authentication mechanism, such as Kerberos, must be created in the $external database, which allows mongos or mongod to consult an external source for authentication.
Changed in version 3.6.3: To use sessions with $external authentication users (i.e. Kerberos, LDAP, x.509 users), the usernames cannot be greater than 10k bytes.
For Kerberos authentication, you must add the Kerberos principal as the username. You do not need to specify a password.
The following operation adds the Kerberos principal reportingapp@EXAMPLE.NET with read-only access to the records database.
use $external |
db.createUser( |
{ |
user: "reportingapp@EXAMPLE.NET", |
roles: [ |
{ role: "read", db: "records" } |
] |
} |
) |
Configure MongoDB with Kerberos Authentication on Linux and Configure MongoDB with Kerberos Authentication on Windows provide more details about setting up Kerberos authentication for your MongoDB deployment.
Users that will authenticate to MongoDB using an external authentication mechanism, such as LDAP, must be created in the $external database, which allows mongos or mongod to consult an external source for authentication.
Changed in version 3.6.3: To use sessions with $external authentication users (i.e. Kerberos, LDAP, x.509 users), the usernames cannot be greater than 10k bytes.
For LDAP authentication, you must specify a username. You do not need to specify the password, as that is handled by the LDAP service.
The following operation adds the reporting user with read-only access to the records database.
use $external |
db.createUser( |
{ |
user: "reporting", |
roles: [ |
{ role: "read", db: "records" } |
] |
} |
) |
Authenticate Using SASL and LDAP with ActiveDirectory and Authenticate Using SASL and LDAP with OpenLDAP provide more detail about using authenticating using LDAP.
Users that will authenticate to MongoDB using an external authentication mechanism, such as x.509 Client Certificate Authentication, must be created in the $external database, which allows mongos or mongod to consult an external source for authentication.
Changed in version 3.6.3: To use sessions with $external authentication users (i.e. Kerberos, LDAP, x.509 users), the usernames cannot be greater than 10k bytes.
For x.509 Client Certificate authentication, you must add the value of the subject from the client certificate as a MongoDB user. Each unique x.509 client certificate corresponds to a single MongoDB user. You do not need to specify a password.
The following operation adds the client certificate subjectCN=myName,OU=myOrgUnit,O=myOrg,L=myLocality,ST=myState,C=myCountry user with read-only access to the records database.
use $external |
db.createUser( |
{ |
user: "CN=myName,OU=myOrgUnit,O=myOrg,L=myLocality,ST=myState,C=myCountry", |
roles: [ |
{ role: "read", db: "records" } |
] |
} |
) |
Use x.509 Certificates to Authenticate Clients provides details about setting up x.509 Client Certificate authentication for your MongoDB deployment.
Enable Access Control — MongoDB Manual
Starting in version 4.2 of the mongo shell, you can use the passwordPrompt() method in conjunction with various user authentication/management methods/commands to prompt for the password instead of specifying the password directly in the method/command cal
docs.mongodb.com
entity dao dto 컨셉 (0) | 2021.05.27 |
---|---|
mongodb user 생성 관리 (0) | 2021.05.27 |
database dml / ddl / dcl (0) | 2021.05.14 |
mongodb 사용자 관리
MongoDB 설치후 데이터베이스 위치, 로그, 인증 등에 관련한 서버 구성과 설정을 정리한다. MongoDB 2.6 과 MongoDB Community Edition 3.x 버전을 사용했다. mongoDB 접근제어 mongoDB 는 설치과정 중에 인증과..
emong.tistory.com
기본적으로 셋업 후 유저나 admin셋팅이 되어 있지 않다.
mongoDB 는 설치과정 중에 인증과 관련해 설정하는 부분이 없어서 설치 후 누구나 DB에 접속 할 수 있다. 인증을 추가해 데이터베이스 관리자와 데이터베이스 사용자로 구분해서 이용하고, 각 데이터베이스의 사용자는 허가된 역할(Role)을 가지고 데이터베이스에 접근 가능하도록 구성한다.
여기서는 다음 두 가지를 다루고 있다.
Ubuntu/Debian 리눅스 배포본에 MongoDB 3.x 버전이 지원되지 않으면, MongoDB Community Edition 를 패키지 혹은 소스로 설치할 수 있다.
mongod가 비인증 모드로 실행중인 상태에서, mongo 클라이언트로 데이터베이스에 접속한다.접속에 성공하면 > 프롬프트가 표시된다. 그리고 접속한 후에 admin 데이터베이스로 전환한다.
> use admin switched to db admin >
mongo 클라이언트로 접속해 mongoDB 데이터베이스 관리자 admin 추가해서, 사용자 롤로 userAdminAnyDatabase 롤을 추가해준다.
mongoDB 2.6 이후 관리자 계정 추가
mongoDB 2.6 이후는 db.createUser() 로 사용자를 추가한다. 1 다음은 admin 데이터베이스에서 사용자를 관리하는 admin 계정을 생성하고 있다.
> > db.createUser({ user:'admin', pwd:'****', roles:['userAdminAnyDatabase'] }) Successfully added user: { "user" : "admin", "roles" : [ "userAdminAnyDatabase" ] } > > db.getUsers() // 데이터베이스 사용자 확인 [ { "_id" : "admin.admin", "user" : "admin", "db" : "admin", "roles" : [ { "role" : "userAdminAnyDatabase", "db" : "admin" } ] } ]
mongoDB 2.4 이전 관리자 계정 추가
mongoDB 2.4 까지는 새로운 사용자는 db.addUser() 로 추가한다.2
$ mongo // mongo client 로 접속 >use admin // admin DB 사용 >db.addUser( { user: "<username>", // admin name pwd: "<password>", roles: [ "userAdminAnyDatabase" ] // Database role } )
mongoDB 2.6까지 32bit 버전을 지원하고 있다.
관리자 계정을 만든후 MongoDB에 mongo 클라이언트로 인증 로그인을 한 후에 데이터베이스를 생성하고 해당 데이터베이스 사용자에 접근 권한을 추가해 준다.
관리자 로그인
이제 데이터베이스 관리자 계정으로 로그인해서 사용하려는 데이터베이스를 use로 선택하고 해당 데이터베이스 사용자를 추가해준다.
mongo 클라이언트 로그인시 -u <username>, -p <password> 와 --authenticationDatabase <database> 를 지정해 주어야 한다.
$ mongo --port 27017 -u "admin" -p "****" --authenticationDatabase "admin" MongoDB shell version v3.4.0 connecting to: mongodb://127.0.0.1:27017 MongoDB server version: 3.4.0
혹은 인증없이 mongo 클라이언트로 데이터베이스에 접속한 후에 db.auth() 명령을 사용할 수 있다.
> use admin switched to db admin > db.auth("admin", "****") 1 > show users { "_id" : ObjectId("5733676238ac1ddf4cf745c2"), "user" : "admin", "readOnly" : false, "pwd" : "24413999168dccff96dcc735720c85ce" } >
이제 각 데이터베이스에 사용자를 생성해서 사용해서 인증한 사용자만 데이터베이스를 사용하게 할 수 있다.
mongoDB v3.x 사용자 관리
mongoDB v2.6 히우는 대부분 mongoDB v3.4와 호환되는 사용자 관리 명령을 사용한다. 여기서는 User Management Methods (v3.4)를 참고하고 있다.
NameDescription
db.auth() | 데이터베이스에 사용자 인증 |
db.createUser() | Creates a new user. |
db.updateUser() | Updates user data. |
db.changeUserPassword() | 사용자 패스워드 변경 |
db.dropAllUsers() | 데이터베이스에 관련된 모든 사용자를 삭제한다. |
db.dropUser() | 한 사용자를 삭제한다 |
db.grantRolesToUser() | 롤과 권한을 사용자에 허용한다 |
db.revokeRolesFromUser() | 사용자에 부여한 롤을 삭제한다 |
db.getUser() | 지정한 사용자의 정보를 반환한다 |
db.getUsers() | 데이터베이스에 관련된 모든 사용자의 정보를 반환한다 |
createUser()
db.createUser() 는 두 개의 도큐멘트를 인자로 사용한다:
db.createUser(user, writeConcern)
여기서 user 도큐멘트는 아래 같은 형식을 갖는다:
{ user: "<name>", pwd: "<cleartext password>", customData: { <any information> }, roles: [ { role: "<role>", db: "<database>" } | "<role>", ... ] }
다음은 product 데이터베이스로 전환해서 product 데이터베이스 사용자를 추가하고 있다. customeData 를 주목하자.
> use products db.createUser( { user: "user1", pwd: "changeMe", customData: { employeeId: 12345 }, // prducts roles: [ { role: "clusterAdmin", db: "admin" }, { role: "readAnyDatabase", db: "admin" }, "readWrite"] }, { w: "majority" , wtimeout: 5000 } )
다양한 사례는 createUser() Exmaple 를 참고하자.
mongoDB v2.4는 사용자 추가 방법이 조금 다르다.
출처: https://emong.tistory.com/237 [에몽이]
entity dao dto 컨셉 (0) | 2021.05.27 |
---|---|
mongodb user 생성관리(몽고 db 공식) (0) | 2021.05.27 |
database dml / ddl / dcl (0) | 2021.05.14 |
사실 단 한사람만이 사라진 것인데
이렇게 삶이 텅 비어버리다니
사람이란 삶의 무게란 잘 모르겠는것이다.
고양이를 키웠던적이 있다.
자취를 하면서 퇴근하고 집에 돌아오면 그 공간이 온전히 고양이 한마리로 가득 찬다.
집안 곳곳이 있는 고양이 털들. 스크래치 흔적. 그리고 어딜 가나 내 시선 안에 들어와 있는 고양이.
그렇게 집이란 공간이 돌아가고픈 곳으로 바뀐다.
주말마다 가능하면 요리를 해먹으려고 한적도 있다.
그러면 집안이 온통 더러워지고 요리 냄새로 가득해진다.
또 치운다고 한나절 걸리지만 그렇게 텅비고 차갑던 집이 뭔가로 채워지면 사람 사는 느낌이 나서 좋았다.
보고 싶고 그립다.
하지만 내가 보고 싶고 그리는 사람이 지금 그 사람은 아닐것이다.
그 사람이 좋아하고 그리던 나 역시 지금의 내가 아닐것이다.
종종 니가 좋아했던 함께했던 것들을 마주칠때마다
과거의 너와 나를 생각해
그랬었구나
나는 그랬었구나
후회하는것 말고는 아무것도 할수 없다.
그리고 다시 일어나서 걷고 또 잊어버려야지.
문득 출근하는 길이 중고등학교의 등교길 같은 느낌을 받았다.
어떤 느낌이냐면 매일 똑같은 하루가 끝없이 이어질것 같은 느낌이랄까.
신기루인걸 뻔히 알면서 사막 한가운데를 묵묵히 걸어가고 있는 느낌.
누군가는 학교가 또 너무 재밌고 신나는 공간일수 있겠지만
나는 하루하루가 너무 지루하고 재미없고 매일 똑같은 학교를 가는게 힘들어서 오히려 생각을 내려놓고 다녔었어.
뭔가 기대하거나 그러면 더 힘드니깐. 그냥 내려놓는거야.
오늘 출근하는 길에서 문득 그때의 느낌을 다시 받았어
뭔가 그동안의 출근 사이클과 이사한 집주변 환경이 달라서 일수도 있지만
이런 아무런 일도 일어나지 않고 기대되지 않는 하루가 계속 반복되는걸까 싶었어-
디지털 디톡스 (0) | 2021.06.12 |
---|---|
누군가 보고 싶다는 것이 (0) | 2021.05.25 |