http://ubuntuguide.net/10-cool-linux-commands-voted-from-commandlinefu

Here are the most popular 10 commands from this site:


sudo !!

Run the last command as root!
it’s very useful,when you execute a command and it tells you that permission denied or don’t have privilege.You can just type this to run again as root.


python -m SimpleHTTPServer

Quickly share current directory tree as HTTPServer,and other can access by type http://$HOSTNAME:8000/ in browser.Remember to replace the “$HOSTNAME”.


:w !sudo tee %

Save a file you edited in vim without the needed permissions!
When you forgot to edit a file with enough permission,you can still save the changes by this command in Vim.


cd -

change to the previous working directory


^foo^bar

Runs previous command but replacing
Really useful for when you have a typo in a previous command. Also, arguments default to empty so if you accidentally run:
echo "no typozs"
you can correct it with
^z


cp filename{,.bak}

Quickly backup a file to filename.bak.And mv filename{,.bak} quickly move a file to filename.bak.


mtr google.com

mtr combines the functionality of the traceroute and ping programs in a single.


!whatever:p

Check command history, but avoid running it
!whatever will search your command history and execute the first command that matches ‘whatever’. If you don’t feel safe doing this put :p on the end to print without executing. Recommended when running as superuser.


ssh-copy-id user@host

Copy ssh keys to user@host to enable password-less ssh logins.
To generate the keys use the command ssh-keygen


ffmpeg -f x11grab -s wxga -r 25 -i :0.0 -sameq /tmp/out.mpg

Capture video of a linux desktop.
it doesn’t work in my ubuntu machine,and finally I found this:

ffmpeg -f x11grab -s sxga -r 24 -i :0.0 /tmp/out.mpg

저작자 표시 비영리 동일 조건 변경 허락
Posted by 파이델
sudo 의 비밀번호 보관 시간은 기본적으로 5분으로 되어있습니다. (5분이 맞나?...15분인가? ;;;)

그럼 이 비밀번호의 보관 시간을 늘이거나 줄이는 설정하는법을 알아봅시다.


터미널 창에서 다음 명령어를 입력합니다.
$ sudo visudo

그러면 nano 편집기로 sudoers 라는 파일이 열리는데 다음 항목을 찾아 원하는 시간(분)을 입력합니다.
Defaults        env_reset,timestamp_timeout=600     # 10시간 = 600분

이렇게 하면 한번만 비밀번호를 입력해두면 10시간 동안은 비밀번호를 묻지 않습니다.

보안상 추천하지는 않지만 더 많이 설정하면 몇일, 몇달동안도 묻지 않겠죠?


ps: 다른 방법으로는 항상 묻지않게 아래와 같은 방법이 있는데 보안상 추천하지는 않습니다.
%admin ALL=NOPASSWD: ALL    # admin 그룹에 속한 유저는 패스워드를 물어보지 않는다.


그럼 마지막으로 혹시 모를일에 대비해 보관된 비밀번호를 지우는법도 알아야겠죠.
$ sudo -k



sudo 설정 파일인 sudoers 에 대하여 아래 출처에 자세히 나와있네요.

출처: http://lumitech.tistory.com/entry/sudoAndSudoer

sudoers

  • sudo를 사용하여 권한을 부여할 구체적인 설정을 하는 파일이 ''sudoers'' 파일이다. 시스템에 따라 약간씩 위치는 다르나, 이 파일을 편집할 권한을 얻으면  시스템의 모든 권한을 얻을 수도 있기 때문에 매우 높은 보안 레벨로 보호되어야 한다.
  • sudo su - 또는 sudo visudo등의 커맨드를 허용하는 것은 매우 신중해야 한다.
  • 이 파일의 편집은 visudo 명령을 실행하여 편집한다. visudo의 기본 편집기(보통은 vi 또는 nano)가 sudoers파일을 열은채로 실행된다.
  • visudo가 사용할 기본 편집기 역시 sudoers파일에 설정할 수 있다.
  • 각 Alias 설정은 문자열 단위로 매치시키기 때문에 주의깊게 작성해야 한다.
  • sudo /usr/bin/su 는 가능하나, cd /usr/bin; sudo ./su는 불가능할 수 있다.

How to Write sudoers

  • Alias 정의 섹션, Default 정의 섹션, Privilege정의 섹션으로 나누어 볼 수 있다.
  • 라인당 하나의 정의
  • Aliases
    • Alias에는 User_Alias, Runas_Alias, Host_Alias, Cmnd_Alias의 4가지 Alias_Type이 있다.
    • 모든 Alias에 대해 ALL은 항상 매치되는 와일드카드로 미리 정의되어 있다(아래 예제 참조)
    • 각 Alias는 NAME = LIST의 형태로 만든다.
      • NAME은 알파벳 대문자로 시작하여야 하고, 두번째 글자부터는 알파벳 대소문자와 숫자, 언더스코어문자('_')를 쓸 수 있다.
      • LIST는 콤마(,)로 구분되고 공백은 무시된다.
      • LIST의 item앞에 '!'(negate operator)를 쓰면 리스트에서 해당 아이템만을 배제시킨다.
        예:[CODE]ALL, !/bin/su    # "/bin/su를 제외한 모두"라는 의미
        ALL, !!/bin/su    # "모두"의 의미, 짝수번 negate 의미 없다.[/CODE]
      • 같은 종류의 Alias는 콜론(:)으로 묶을 수 있다. 다른 라인에 새로운 정의로 포함시킬수도 있다.
    • Alias는 다음과 같은 형태가 된다.
      • Alias_Type NAME = item1, item2, item3, item4
      • Alias_Type NAME = item1, item2, item3 : Name = item4, item5
    • User_Alias
      • sudo 권한을 적용할 유저의 집합을 정의한다.
      • (sudoer 그룹명) = (List of login names)
      • 유저명 대신 %<group> 을 사용할 수도 있다.
        • 예: %admin # admin 그룹에 속하는 모든 유저
    • Runas_Alias
      • 어떤 유저 또는 그룹의 권한으로 명령을 수행할지를 지정할 수 있다.
      • 정의 방법은 User_Alias와 동일하나, #<uid> 의 형태도 사용할 수 있다.
      • 주의: root#0은 동일한 유저이지만, 문자열 매치를 하기 때문에 다른 것으로 간주된다. root, %0도 마찬가지.
    • Host_Alias
      • hostname, IP address, Network address, 다른 Host_Alias를 묶어 호스트 집합을 만들 수 있다.
    • Cmnd_Alias
      • 권한을 허용할 커맨드를 나열하여 집합으로 만든다.
      • 커맨드는 full path로 적는다. 디렉토리명을 커맨드로 지정할 수 있다. 디렉토리를 지정하면 그 디렉토리이하의 모든 커맨드에 대해 허용된다.
  • Defaults : 권한 부여의 기본 옵션을 지정한다.
    • 라인당 하나의 Default_Entry를 정의 한다.
    • Default_Entry는 Default_Type Parameter_List로 정의한다.
    • Default_Type는 다음의 4가지 정의 방법이 있다.
      • Defaults
      • Defaults@Host_Alias
      • Defaults:User_Alias
      • Defaults>runas_username
    • Parameter_List는 Parameter의 리스트를 적는다. Parameter는 다음과 같은 형태가 있다.
      • flag
      • !flag
      • flag=value
      • flag+=value
      • flag-=value
      • other Parameter_Lists
    • 여기서는 유용한 몇개 flag만 소개한다. 자세한 flags는 SUDOERS(5)를 참조한다 (이말을 쓰기 싫어서 작성한 문서에 쓸수 밖에 없다니;;;)
      • lecture: 앞절의 예제 이미지와 같이 타인의 권한으로 수행할때 기억해야 할 것에 대한 짧은 경고문.
        lecture=(never, once, always 중 하나)
      • lecture_file: lecture를 보여줄 때, 이 파일을 보여준다.
        lecture_file=(full path of lecture_file)
      • timestamp_timeout: sudo를 수행한 후 다시 수행할 때, 패스워드를 다시 물어볼지를 결정하는 타임아웃값. 0이면 항상 물어본다.
        timestamp_timeour=(분 단위 정수)
      • editor: visudo에서 사용할 기본 에디터
        editor=(/usr/bin/vim 등의 에디터 full path)
      • passwd_tries: 비밀번호를 틀렸을 경우 다시 물어보는 횟수.
        passwd_tries=(정수)
      • passwd_timeout: 비밀번호 입력대기시간 타임아웃값. 0이면 무한정 기다린다.
        passwd_timeout=(분 단위 정수)
      • fqdn: Host 이름에 Fully Qualified Domain Name을 사용할 것인지의 여부. 이 플래그를 사용하면, sudo수행시에 hostname을 DNS에 쿼리한다.
        fqdn (또는 !fqdn)
      • set_logname: runas user(타겟 유저라고도 함)의 LOGNAME과 USER 환경변수값을 가져오지 않고 현재 값을 유지한다.
        set_logname (또는 !set_logname)
  • User privilege specification
    • 앞서 정의한 Alias들의 조합으로 권한을 부여한다.
    • User_Alias (Host_Alias) = Cmnd_Alias의 형태로 정의한다.
    • Tag_Spec과 Runas_Spec을 사용하는 방법은 역시  SUDOERS(5)를 참조한다. (또.;; 그치만 많이 써본적은 없으므로 필요할때 읽어볼 것.)

sample

  • 가장 소극적인 보안책으로 사용할수 있는 sudoers 예제
    # 아무런 Alias를 정의하지 않고,
    # admin group에 속한 계정 전체에 대해서
    # 모든 커맨드를 root권한으로 수행할수 있도록 허용함
    # sudo를 사용하기 위해서 항상 패스워드를 물어본다.

    # Host alias specification

    # User alias specification

    #Cmnd alias specification

    # Defaults
    Defaults   lecture=always,tty_tickets,!fqdn,timestamp_timeout=0,editor=/usr/bin/vi

    # User privilege specification
    root    ALL=(ALL) ALL

    # Members of the admin group may gain root privileges
    %admin ALL=(ALL) ALL

  • 다양한 용법과 문법의 예
    # User alias specification
    # 3가지의 유저셋을 정의한다.
    User_Alias     FULLTIMERS = millert, mikef, dowdy
    User_Alias     PARTTIMERS = bostley, jwfox, crawl
    User_Alias     WEBMASTERS = will, wendy, wim

    # Runas alias specification
    # 2가지 Runas 유저셋을 정의한다.
    Runas_Alias    OP = root, operator
    Runas_Alias    DB = oracle, sybase

    # Host alias specification
    # 4가지 호스트셋을 정의한다.

    # IP/NETMASK 지정방법, 호스트명 지정방법의 예가 모두 나와있다.
    Host_Alias     CUNETS = 128.138.0.0/255.255.0.0
    Host_Alias     CSNETS = 128.138.243.0, 128.138.204.0/24, 128.138.242.0
    Host_Alias     SERVERS = master, mail, www, ns
    Host_Alias     CDROM = orion, perseus, hercules

    # Cmnd alias specification
    # 커맨드셋을 정의한다.
    Cmnd_Alias     DUMPS = /usr/bin/mt, /usr/sbin/dump, /usr/sbin/rdump,\
                           /usr/sbin/restore, /usr/sbin/rrestore
    Cmnd_Alias     KILL = /usr/bin/kill
    Cmnd_Alias     SHUTDOWN = /usr/sbin/shutdown
    Cmnd_Alias     HALT = /usr/sbin/halt
    Cmnd_Alias     REBOOT = /usr/sbin/reboot
    Cmnd_Alias     SHELLS = /usr/bin/sh, /usr/bin/csh, /usr/bin/ksh, \
                            /usr/local/bin/tcsh, /usr/bin/rsh, \
                            /usr/local/bin/zsh
    Cmnd_Alias     SU = /usr/bin/su

    # Override built-in defaults
    # 기본 옵션을 지정한다.
    # lecture를 항상 보여준다. fqdn 사용하지 않는다. 3분내에 다시 sudo하면 패스워드를 물어보지 않는다. visudo의 편집기로 /usr/bin/vi를 사용한다.
    Defaults   lecture=always,!fqdn,timestamp_timeout=3,editor=/usr/bin/vi

    # runas user가 root가 될때는 set_logname 하지 않는다.
    # 즉, root 의 환경을 가져오지 않는다
    Defaults>root          !set_logname

    # FULLTIMER에게는 lecture를 보여주지 않는다.
    Defaults:FULLTIMERS    !lecture

    # SERVERS에서는 패스워드 입력을 1분내로 해야 한다. sudo 로그 파일을 별도로 지정한다.
    Defaults@SERVERS       passwd_timeout=1, logfile=/var/log/sudo.log

    # User privileges
    # root도 sudo를 수행할 수 있다.
    root           ALL = (ALL) ALL

    # wheel그룹에 속한 모든 유저는 sudo를 통해 모든 명령을 수행할 수 있다.
    %wheel         ALL = (ALL) ALL

    # FULLTIMERS에게는 패스워드를 물어보지 않는다.
    FULLTIMERS     ALL = NOPASSWD: ALL

    # PARTTIMERS에게는 패스워드를 물어본다.
    PARTTIMERS     ALL = ALL

    # operator에게는 패스워드를 물어보고, 지정된 커맨드셋을 허용한다.
    operator       ALL = DUMPS, KILL, SHUTDOWN, HALT, REBOOT, PRINTING,\
                   sudoedit /etc/printcap, /usr/oper/bin/

    # joe는 operator가 될수 있다.
    joe            ALL = /usr/bin/su operator

    # fred는 DB 유저권한이 필요할때에만 패스워드를 물어보지 않고 모든 권한이 허용된다.
    fred           ALL = (DB) NOPASSWD: ALL

    # john은 SERVERS호스트셋에서 옵션없이 su를 수행할 수 있다. su에 옵션을 줄수 없고 root로의 su는 불허한다.
    john           SERVERS = /usr/bin/su [!-]*, !/usr/bin/su *root*

    # jen은 SERVERS호스트셋을 제외한 모든 호스트에서 모든 권한을 패스워드를 물어본후 얻을 수 있다.
    jen            ALL, !SERVERS = ALL


저작자 표시 비영리 동일 조건 변경 허락
Posted by 파이델