리눅스 (Linux)2016. 3. 30. 09:02


1. 설치할 OS 종류 확인

# cat /etc/redhat-release
CentOS release 6.5 (Final)

# getconf LONG_BIT
64

2. Samba란 ?

삼바는 리눅스와 윈도우간에 파일 및 프린터를 공유 할 수 있게 해주는 프로그램이다. 삼바를 통해 리눅스 서버를 타운영체제와 파일을 공유할 수 있는 파일서버로도 사용할 수 있다. 이와같이 삼바가 공유할 수있는 이유는 SMB(Server Message Block)/CIFS(Common Internet File System)라는 프로토콜을 이용함으로써 가능해졌다.


(참고)
SMB 란?
SMB(Server Message Block)는 마이크로소프트사와 인텔이 윈도우 시스템이 다른 시스템의 디스크나 프린터와 같은 자원을 공유할 있도록하기 위해 개발된 프로토콜이다. TCP/IP 기반하의 NetBIOS 프로토콜을 이용하기 때문에 이 프로토콜은 NFS, NIS, lpd 와 같은 유닉스의 분산인증구조와 유사하다. 따라서 윈도우 중심의 네트워크 환경에서는 리눅스를 이용한 공유시스템에서는 SMB가 필수적이다.


CIFS 란?
CIFS(Common Internet File System) 는 네트워크를 위한 SMB 파일 공유 프로토콜의 확장된 버전이며, 윈도우와 유닉스 환경을 동시에 지원하는 인터넷의 표준 파일 규약의 프로토콜이다. CIFS는 이전의 폐쇄적인 SMB 프로토콜과는 달리 CIFS 규약 정의는 여러 유닉스 업체의 참여하여 결정된 내용이기 때문에 삼바도 버전이 올라감에 따라(삼바 버전 2.2 이상) CIFS 규약을 잘 준수하여 안정성이 상당히 향상 되었다. 

(출처: https://www.linux.co.kr/home/lecture/?leccode=10644)


3. 설치

# yum install samba

설치시 의존성에 의해 모두 같이 되는 패키지이지만 꼭 필요한 패키지 목록

 samba 

 SMB 서비스 네트워크 데몬 및 기본 유틸리티 포함 

 samba-client

 공유 네트워크 내에 있는 서버리스트 출력

 samba-common

 설정 파일이나 설정 유틸리티, Man 페이지 포함

설치완료 후 생성되는 파일은 다음과 같다.

# ls /etc/samba
lmhosts  smb.conf  smbusers

 lmhosts 

 공유 네트워크 내에 있는 서버리스트 정보을 담은 파일

 smb.conf

 Samba 서버 설정 파일

 smbusers

 Samba 유저의 별칭을 담은 파일


4. 환경설정

4-1. smb.conf 설정을 위한 기본 내용


[root@seob01 samba]# cat smb.conf

# This is the main Samba configuration file. You should read the
# smb.conf(5) manual page in order to understand the options listed
# here. Samba has a huge number of configurable options (perhaps too
# many!) most of which are not shown in this example
#
# For a step to step guide on installing, configuring and using samba, 
# read the Samba-HOWTO-Collection. This may be obtained from:
#  http://www.samba.org/samba/docs/Samba-HOWTO-Collection.pdf
#
# Many working examples of smb.conf files can be found in the 
# Samba-Guide which is generated daily and can be downloaded from: 
#  http://www.samba.org/samba/docs/Samba-Guide.pdf
#
# Any line which starts with a ; (semi-colon) or a # (hash) 
# is a comment and is ignored. In this example we will use a #
# for commentry and a ; for parts of the config file that you
# may wish to enable
#
# NOTE: Whenever you modify this file you should run the command "testparm"
# to check that you have not made any basic syntactic errors. 
#
#---------------
# SELINUX NOTES:
#
# If you want to use the useradd/groupadd family of binaries please run:
# setsebool -P samba_domain_controller on
#
# If you want to share home directories via samba please run:
# setsebool -P samba_enable_home_dirs on
#
# If you create a new directory you want to share you should mark it as
# "samba_share_t" so that selinux will let you write into it.
# Make sure not to do that on system directories as they may already have
# been marked with othe SELinux labels.
#
# Use ls -ldZ /path to see which context a directory has
#
# Set labels only on directories you created!
# To set a label use the following: chcon -t samba_share_t /path
#
# If you need to share a system created directory you can use one of the
# following (read-only/read-write):
# setsebool -P samba_export_all_ro on
# or
# setsebool -P samba_export_all_rw on
#
# If you want to run scripts (preexec/root prexec/print command/...) please
# put them into the /var/lib/samba/scripts directory so that smbd will be
# allowed to run them.
# Make sure you COPY them and not MOVE them so that the right SELinux context
# is applied, to check all is ok use restorecon -R -v /var/lib/samba/scripts
#
#--------------
#
#======================= Global Settings =====================================

[global] // 전역 설정 부분, 여기 아래에 옵션을 넣게 되면 모든 Samba 정보에 설정된다.

# ----------------------- Network Related Options -------------------------
#
# workgroup = NT-Domain-Name or Workgroup-Name, eg: MIDEARTH
#
# server string is the equivalent of the NT Description field
#
# netbios name can be used to specify a server name not tied to the hostname
#
# Interfaces lets you configure Samba to use multiple interfaces
# If you have multiple network interfaces then you can list the ones
# you want to listen on (never omit localhost)
#
# Hosts Allow/Hosts Deny lets you restrict who can connect, and you can
# specifiy it as a per share option as well
#
workgroup = WORKGROUP// workgroup 부분이야 윈도우의 workgroup과 일치 시키거나 NT 도메인 이름으로 설정한다.

security = user // 서버의 사용자 계정만 사용할 수 있도록 한다. 

server string = Samba Server Version %v 
        // 윈도우의 컴퓨터 설명과 비슷, 나중에 공유를 받게 되면 폴더명 옆에 설명으로 나온다.
        // %h은 호스트이름, %L은 NetBIOS 이름, $v은 Samba Version 표기 

; netbios name = MYSERVER

 

  // 여기서부터 ; 이 앞에 있으면 주석처리
  // NetBIOS 네임을 설정하는 영역, 윈도우의 컴퓨터 이름과 동일.
  // 주석처리 할 경우 호스트 이름을 NetBIOs 네임으로 사용하게 된다. 현재 내가 seob01 라는 호스트 이름이면  NetBIOS 이름은 seob01이 된다.

; interfaces = lo eth0 192.168.12.2/24 192.168.13.2/24 
  // 두개의 네트워크에 Samba Server가 물려있는 경우 Samba가 양쪽 네트워크에 대해 브라우징 및 서비스가 가능하도록 설정. 설정방법은 < IP 주소 > / < 넷마스크 > 이렇게 표기.
; hosts allow = 127. 192.168.12. 192.168.13.
        // Samba Server에 대해 접근을 허락 할 호스트 네임 혹은 IP 주소를 지정.
        // 예를 들어 192.168.1.1~254 단위로 설정하고 다면. -> 192.168.1. 이렇게만 적으면 된다.

# --------------------------- Logging Options -----------------------------
#
# Log File let you specify where to put logs and how to split them up.
#
# Max Log Size let you specify the max size log files should reach

# logs split per machine
log file = /var/log/samba/log.%m
  // 서버에 접속한 호스트마다 개별적인 로그 파일을 생성하도록 설정 
# max 50KB per log file, then rotate
max log size = 50

# ----------------------- Standalone Server Options ------------------------
#
# Scurity can be set to user, share(deprecated) or server(deprecated)
#
# Backend to store user information in. New installations should 
# use either tdbsam or ldapsam. smbpasswd is available for backwards 
# compatibility. tdbsam requires no further configuration.

security = user
   // security 영역은 다음과 같이 설정할 수 있어
   // user = Samba Server에서 계정 및 패스워드를 통한 인증을 거친 사용자에 한하여 공유를 허가
   // share = 모든 공유 영역에 권한 없이 접근이 가능하도록 설정. 윈도우의 워크그룹 기본 모드.
   // server = 공유 영역에 대한 사용 권한은 다른 호스트(NT 패스워드 서버)의 인증 과정을 거친 사용자에 한하여 허가
passdb backend = tdbsam
   // 패스워드에 대한 인증 방식이야
   // tdbsam = samba 내장 TDB SAM 형식
   // ldapsam = LDAP 사용 (LDAP 라이브러리 필요)
   // smbpasswd = smbpasswd 텍스트 파일 인증 형식


# ----------------------- Domain Members Options ------------------------
#
# Security must be set to domain or ads
#
# Use the realm option only with security = ads
# Specifies the Active Directory realm the host is part of
#
# Backend to store user information in. New installations should 
# use either tdbsam or ldapsam. smbpasswd is available for backwards 
# compatibility. tdbsam requires no further configuration.
#
# Use password server option only with security = server or if you can't
# use the DNS to locate Domain Controllers
# The argument list may include:
#   password server = My_PDC_Name [My_BDC_Name] [My_Next_BDC_Name]
# or to auto-locate the domain controller/s
#   password server = *

; security = domain
; passdb backend = tdbsam
; realm = MY_REALM

; password server = <NT-Server-Name>
  // security에서 domain과 server을 할 경우 Samba 이외에 해당 기능을 수행하는 NT 서버가 필요.
  // 즉, 해당 NT 서버를 아래의 password server를 통해 지정.
# ----------------------- Domain Controller Options ------------------------
#
# Security must be set to user for domain controllers
#
# Backend to store user information in. New installations should 
# use either tdbsam or ldapsam. smbpasswd is available for backwards 
# compatibility. tdbsam requires no further configuration.
#
# Domain Master specifies Samba to be the Domain Master Browser. This
# allows Samba to collate browse lists between subnets. Don't use this
# if you already have a Windows NT domain controller doing this job
#
# Domain Logons let Samba be a domain logon server for Windows workstations. 
#
# Logon Scrpit let yuou specify a script to be run at login time on the client
# You need to provide it in a share called NETLOGON
#
# Logon Path let you specify where user profiles are stored (UNC path)
#
# Various scripts can be used on a domain controller or stand-alone
# machine to add or delete corresponding unix accounts
#
; security = user
; passdb backend = tdbsam

; domain master = yes 
; domain logons = yes

# the login script name depends on the machine name
; logon script = %m.bat
# the login script name depends on the unix user used
; logon script = %u.bat
; logon path = \\%L\Profiles\%u
# disables profiles support by specifing an empty path
; logon path =          

; add user script = /usr/sbin/useradd "%u" -n -g users
; add group script = /usr/sbin/groupadd "%g"
; add machine script = /usr/sbin/useradd -n -c "Workstation (%u)" -M -d /nohome -s /bin/false "%u"
; delete user script = /usr/sbin/userdel "%u"
; delete user from group script = /usr/sbin/userdel "%u" "%g"
; delete group script = /usr/sbin/groupdel "%g"


# ----------------------- Browser Control Options ----------------------------
#
# set local master to no if you don't want Samba to become a master
# browser on your network. Otherwise the normal election rules apply
#
# OS Level determines the precedence of this server in master browser
# elections. The default value should be reasonable
#
# Preferred Master causes Samba to force a local browser election on startup
# and gives it a slightly higher chance of winning the election
; local master = no
; os level = 33
; preferred master = yes

#----------------------------- Name Resolution -------------------------------
# Windows Internet Name Serving Support Section:
# Note: Samba can be either a WINS Server, or a WINS Client, but NOT both
#
# - WINS Support: Tells the NMBD component of Samba to enable it's WINS Server
#
# - WINS Server: Tells the NMBD components of Samba to be a WINS Client
#
# - WINS Proxy: Tells Samba to answer name resolution queries on
#   behalf of a non WINS capable client, for this to work there must be
#   at least one WINS Server on the network. The default is NO.
#
# DNS Proxy - tells Samba whether or not to try to resolve NetBIOS names
# via DNS nslookups.

; wins support = yes
; wins server = w.x.y.z
; wins proxy = yes

; dns proxy = yes

# --------------------------- Printing Options -----------------------------
#
# Load Printers let you load automatically the list of printers rather
# than setting them up individually
#
# Cups Options let you pass the cups libs custom options, setting it to raw
# for example will let you use drivers on your Windows clients
#
# Printcap Name let you specify an alternative printcap file
#
# You can choose a non default printing system using the Printing option

load printers = yes
  // Samba에서 별도의 프린터 설정을 하지 않고, printcap name에서 설정한 프린트 설정 파일을 불러와 쓰도록 설정.
  // 아래 printercap name 옵션을 참고.
cups options = raw

; printcap name = /etc/printcap
  // Samba에서 공유해서 사용할 프린트에 대한 설정이 포함되어 있는 파일을 지정하는 영역으로 /etc/printcap 파일을 지정
#obtain list of printers automatically on SystemV
; printcap name = lpstat
; printing = cups
  // 지원하는 프린트 시스템을 지정하는 영역으로 기존의 LPRng을 이용하여 프린트를 사용할 경우 lprng를, CPUS을 이용하여 프린트를 사용할 경우 cpus 지정필요.

# --------------------------- Filesystem Options ---------------------------
#
# The following options can be uncommented if the filesystem supports
# Extended Attributes and they are enabled (usually by the mount option
# user_xattr). Thess options will let the admin store the DOS attributes
# in an EA and make samba not mess with the permission bits.
#
# Note: these options can also be set just per share, setting them in global
# makes them the default for all shares

; map archive = no
; map hidden = no
; map read only = no
; map system = no
; store dos attributes = yes


#============================ Share Definitions ==============================
// 공유 영역 (무엇을 공유할지 쓰는 곳)

[homes] // 사용자 계정을 통해서 자기 홈 경로를 접근 할 수 있다. 접근 경로이다.
comment = Home Directories // 폴더에 대한 설명
browseable = no // 이 폴더가 리스트에 출력하게 할 것인지 여부. yes 할 경우 출력, no 할 경우 보이지 않음. yes로 하면 접속 권한이 없어도 같은 네트웍에 있는 모든 컴퓨터에서 폴더를 볼 수 있다.
#writable = yes // 읽고, 쓰기 권한(yes 허용, no 거부), 기존 버전에서 사용

 read only = no //버전에 따라서 writable or read only 사용

create mask = 0664 // 생성되는 파일 권한

directory mask = 0755 // 생성되는 폴더 권한

 
; valid users = %S // home 계정은 일반적으로 모든 사용자가 접근 가능하다. %S로 설정해 주면 username 사용 \\server\username을 사용할 수 있다. (공유 영역에 접근 가능한 사용자 혹은 그룹을 지정, 그룹일 경우 @(앳)을 꼭 붙여야한다)
         // ex) seob @seobgroup
; valid users = MYDOMAIN\%S

[printers]
comment = All Printers
path = /var/spool/samba
browseable = no
guest ok = no
writable = no
printable = yes

# Un-comment the following and create the netlogon directory for Domain Logons
; [netlogon]
; comment = Network Logon Service
; path = /var/lib/samba/netlogon
; guest ok = yes
; writable = no
; share modes = no


# Un-comment the following to provide a specific roving profile share
# the default is to use the user's home directory
; [Profiles]
; path = /var/lib/samba/profiles
; browseable = no
; guest ok = yes


# A publicly accessible directory, but read only, except for people in
# the "staff" group
; [public]
; comment = Public Stuff
; path = /home/samba
; public = yes
; writable = yes
; printable = no
; write list = +staff

 

# 여러 사용자가 함께 사용할 수 있는 공유 폴더 설정이다.'[]'안에 접속할 경로를 설정해 준다. 아래처럼 '[share]' 를 사용하면 '\\server\share'로 접속하면 된다.

# 이 부분은 설정 파일에 존재하지 않으므로 적당한 위치에 내용 전체를 추가해 주면 된다.

# 사용자간 공유할 필요 없으면 생략해도 된다.

[share]

comment = Shared Files

path = /data/samba/share //실제 파일이 저장될 공간으로, 설정이 끝나고 폴더를 생성 해 주어야 한다.

browseable = yes // no로 해도 무관

read only = no

create mask = 0664

directory mask = 0755

#guest ok = yes //Anonymous로 접속 가능하게 하려면 아래 주석을 풀어준다. 이때는 read only 을 추천한다. 

 

4-2. 옵션 설명

 path  경로 지정 
 browsable  해당 공유 내역을 브라우징 리스트에 나타나게 할 것인지에 대한 옵션
 writable 쓰기 가능 여부 writable=yes은 readonly=no와 동일해 
 printable 프린터 공유에만 사용하는 영역 yes를 할 경우 공유 이름으로 전역 영역에서 정의한 프린터를 공유하게 됨
 public nobody 사용자에 대한 접근 권한 설정. 전역 영역의 guest ok=yes와 연관있음
 hosts allow 공유 영역에 대한 호스트별 접근 허가 설정, IP 혹은 네트워크 주소를 지정
 vlid users 공유 영역에 접근 가능한 사용자 혹은 그룹 지정사용자를 여러 명 지정할 경우 공백으로 구분하여 그룹명
 일 경우 @(골뱅이)를 통해 그룹임을 명시

 ex) seob @seobgroup
 write list 공유 영역에 대한 쓰기 가능한 사용자 혹은 그룹 지정사용자를 여러 명 지정할 경우 공백으로 구분하여 그룹명
 일 경우 @(골뱅이)를 통해 그룹임을 명시

 ex) seob @seobgroup 

(출처: http://leegaworld.blogspot.kr/search?q=samba)


4-3. 설정 추가 


공유 디렉토리 생성





#mkdir /home/share



#chmod 777 /home/share


     74         workgroup = WORKGROUP
     75         server string = LJM21C Samba Server Version %v

    289 [ljm21c]
    290 comment=ljm21c Directories
    291 browseable = yes
    292 writable = yes
    293
    294 path = /home/share


4-4. 방화벽 예외처리

4-4-1. Samba 서버에서 사용중인 포트 확인

# service smb start
SMB서비스를 시작하고 있습니다:                             [  OK  ]

# netstat -anp | grep LISTEN
tcp        0      0 0.0.0.0:139                 0.0.0.0:*                   LISTEN      3725/smbd          
tcp        0      0 0.0.0.0:22                  0.0.0.0:*                   LISTEN      976/sshd           
tcp        0      0 127.0.0.1:25                0.0.0.0:*                   LISTEN      1052/master        
tcp        0      0 0.0.0.0:445                 0.0.0.0:*                   LISTEN      3725/smbd 

=> 139, 445 포트를 사용하고 있다.

(혹은 # vi /etc/services 에서 서버 확인 가능)

(참고) 삼바서버 포트 번호

135/UDP
137/UDP
138/UDP
139/TCP (설정 안해도 작동함)
445/TCP (설정 안해도 작동함)

#vi /etc/sysconfig/iptables
-A INPUT -m state --state NEW -m tcp -p tcp --dport 139 -j ACCEPT
-A INPUT -m state --state NEW -m tcp -p tcp --dport 445 -j ACCEPT

# service iptables restart
iptables: 체인을 ACCEPT 규칙으로 설정 중:  filter          [  OK  ]
iptables: 방화벽 규칙을 지웁니다:                          [  OK  ]
iptables: 모듈을 언로드하는 중:                            [  OK  ]
iptables: 방화벽 규칙 적용 중:                             [  OK  ]


4-5. 사용자 인증

현재 존자하는 계정에 smb 인증 필요.


4-5-1. samba 계정 등록 절차
    1) 시스템 사용자 등록(useradd) 및 패스워드 등록 (passwd)
    2) 그룹 사용자 등록(gpasswd)
    3) samba 사용자 등록(smbpasswd)


4-5-1-1.  시스템 사용자 등록(useradd) 및 패스워드 등록 (passwd)
# useradd ljm21c
# passwd ljm21c
ljm21c 사용자의 비밀 번호 변경 중
새  암호:
새  암호 재입력:
passwd: 모든 인증 토큰이 성공적으로 업데이트 되었습니다.

# cat /etc/group

wbpriv:x:88:
ljm21c:x:500:


4-5-1-2. 그룹 사용자 등록(gpasswd)

# groupadd WORKGROUP
[root@ljm21c samba]# gpasswd -a ljm21c WORKGROUP
Adding user ljm21c to group WORKGROUPljm21c:x:500:

# cat /etc/group

ljm21c:x:500:
WORKGROUP:x:501:ljm21c


4-5-1-3. samba 사용자 등록(smbpasswd)

# smbpasswd -a ljm21c
New SMB password:
Retype new SMB password:
Added user ljm21c.


5. 윈도우에서 접속

탐색기 혹은 브라우저에서 \\{ip or 호스트} 으로 접속 하면 된다.


6. 문제발생

6-1. 접속은 되지만 공유 디렉토리에 액세스할 수 없음.

[Content]
\\192.168.153.150\ljm21c에 액세스할 권한이 없습니다. 네트워크 관리자에게 액세스 권한을 요청하십시오.

      1) SELinux 서비스 사용 안함으로 설정

(참조: SELinux 는 리눅스 배포판을 설치할 때 리눅스 서버의 보안 강화의 목적으로 설치되고운용되는  , 일종의 보안 툴 같은 개념이다.)

- root 권한으로 아래 명령어 실행

# setenforce 0 

- #vi /etc/sysconfig/selinux 

SELINUX=enforcing OR SELINUX=permissive 을 SELINUX=disabled로 수정

(setenforce 1 은 enforcing 모드를 의미한다)

     2) 해당 공유 디렉토리의 퍼미션 확인

6-2. 접속 자체가 되지 않음.

=> 방화벽 설정 확인한다.

6-3. 접속 시 아이디/패스워드가 일치하지 않음.

=> smbpasswd -a {사용자 계정} 으로 다시 암호 변경

6-4. 인증이 이상하게 될 경우.

=> smb.conf 에서 WORKGROUP = { } 부분을 Windows Group이 동일한지 확인.


7. Windows 에서 Samba 서버 세션 끊기

7-1. 현재 samba 서버와의 세션 연결 확인

C:\> net use [공유이름] /delete

옵션들은 net ? 또는 net use ? 입력으로 확인

C:\> net session /delete


8. 기본 설정 smb.conf 내용

[global]

        workgroup = WORKGROUP

        server string = Samba Server Version %v


        log file = /var/log/samba/log.%m

        max log size = 50


        security = user

        passdb backend = tdbsam



[ljm21c]

comment = ljm21c Shared Directories

browseable = yes

writable = yes

path = /home/share

Posted by 랩퍼우