顯示具有 Shell 標籤的文章。 顯示所有文章
顯示具有 Shell 標籤的文章。 顯示所有文章

2020年11月20日 星期五

Linux ls 指令

-l:輸出 Long Listing 格式,包括下列資訊:
  • 檔案 type and permissions:有 10 個字母,第 1 個字母是 file type:
    • -:一般檔案
    • b:block device
    • c:character device
    • d:directory 目錄
    • l:Symbolic link
    • n:Network file
    • p:FIFO
    • s:socket
    剩下 9 個字母是 permissions
  • hard link 數目
  • owner
  • group
  • size
  • 最後更動日期時間
  • 名稱

-i:inode

參考

https://linuxize.com/post/how-to-list-files-in-linux-using-the-ls-command

2020年3月21日 星期六

bash exit status

bash 結束狀態 (exit status)
指令執行的結束狀態是 waitpid 系統呼叫或等效函數的回傳值,範圍 0 ~ 255,0 表示成功 (true),否則表示失敗 (false)。shell 特別定義 126 以上的值。
  • 2:所有內建指令回傳 2 表示使用不正確,一般是 invalid options 或 missing arguments。
  • 126:檔案有找到,但不含可執行屬性。
  • 127:檔案沒找到。
  • 128+N:因 fatal signal N 而結束
指令因 expansion 或 redirection 錯誤也是回傳失敗。bash 本身回傳最後執行指令的結束狀態。見內建指令 exit。

參考:man bash 的 EXIT STATUS

2019年11月23日 星期六

ssh client

ssh client 的系統設定在 /etc/ssh/ssh_config,如果要個人設定,是寫在 ~/.ssh/config。

有個方便的用處是,當 ssh 伺服器不是使用預設通訊埠時,可以寫在設定檔裡,這樣 ssh 連線時就不用再額外指定通訊埠。此外也可以設定別名。

連線到伺服器有些情況會有 locale 問題,可以關掉 SendEnv。但由於 SendEnv 是累加的,不是不設 SendEnv 或將 SendEnv 設為空白就可以,如果 /etc/ssh/ssh_config 有設 SendEnv,也需要移除。

問題:no matching key exchange method found. Their offer: diffie-hellman-group1-sha1
  • 加參數 -oKexAlgorithms=+diffie-hellman-group1-sha1
  • 設定加入連線加密方法
  • 參考
ssh 是一個透過 SSH 加密連線登入遠端機器執行指令的程式,同時這個連線也可以用來轉送 X11 連線、任意 TCP port、和 UNIX-domain socket。

指令參數

  • -N:不執行遠端指令
  • -nNT:不開 tty
  • -f:背景執行 
  • -L:local port forwarding
  • -D:dynamic port forwarding
  • -R:remote port forwarding
  • -X:X11 Forwarding

SSH tunnel

local port forwarding

ssh client 近端一個 port 透過 SSH 通到 ssh server,然後存取遠端 remotehost:remoteport:

ssh -L localport:remotehost:remoteport user@example.com

連 ssh client 的 localport,相當於連到遠端的 remotehost:remoteport,SSH server 會去解析 remotehost。遠端位置可能是 Web Server、RDP Server、VNC Server 等。

dynamic port forwording

同 local port forwarding,但最終位置不指定,改依 L5 SOCKS 協定的 handshake 得知。可用於任何 TCP/UDP socket 連線。provide a local SOCKS 4/4A/5 proxy on a local port

ssh -D localport user@example.com

所有連 ssh client 的 localport,都會連到 SSH server 再去進行連線到最終位置。例如 Firefox 等瀏覽器可設定 SOCKS proxy 為 SSH client 的 localport,網頁就會透過 SSH server 去連線。參考:https://linuxize.com/post/how-to-setup-ssh-socks-tunnel-for-private-browsing/

remote port forwarding

遠端 ssh server 的一個 port 透過 SSH 通到 ssh client,然後存取近端的 localhost:port:

ssh -R 9000:localhost:3000 user@example.com

SSH server 預設不允許 remote port forwarding,啟用需要在 /etc/ssh/sshd_config

GatewayPorts yes

然後重啟

sudo service ssh restart

連遠端 ssh server 的 port,相當於連到近端的 localhost:port。

ssh client


PuTTY pieTTY Xshell FireSSH zterm
安裝 可免安裝 可免安裝 需要安裝,個人用免費 JavaScript 版,給 Firefox 使用 Java 版,用於各式瀏覽器,需要 Java 執行環境
拖曳傳擋
有 (sftp,需要輸入密碼、選目錄) 有 (sftp)

Tab



中文



判斷字元自動輸入



其它說明
基於 PuTTY,但沒隨時跟上更新

選項設定

ssh 依照下列優先來源取得設定:

  1. command-line options
  2. 個人設定檔:~/.ssh/config
  3. 系統設定檔:/etc/ssh/ssh_config

設定檔包含 host 規範的 section,只要符合指令行的主機名稱就有效 (見 CanonicalizeHostname)。由於每個參數使用第一個取得的值,越 host 特殊的宣告應該要放在前面,越通用的放後面。

設定檔包含 keyword-argument 對,每對一行。# 開始的行和空白行是註解。argument 可用双引號包起來,為了包含空白。Configuration options may be separated by whitespace or optional whitespace and exactly one ‘=’; the latter format is useful to avoid the need to quote whitespace when specifying configuration options using the ssh, scp, and sftp -o option.

keyword argument

keyword=argument

keyword =arguemnt

keyword 不分大小寫,argument 分大小寫。

Host

接下來設定區塊 (到下個的 Host 或 Match 為止) 適用的 host,多個用 whitespace 分隔。「*」表示所有 host。The host is usually the hostname argument given on the command line (見 CanonicalizeHostname).

A pattern entry may be negated by prefixing it with an exclamation mark (‘!’).  If a negated entry is matched, then the Host entry is ignored, regardless of whether any other patterns on the line match.  Negated matches are therefore useful to provide exceptions for wildcard matches.

See PATTERNS for more information on patterns.

Match

接下來設定區塊 (到下個的 Host 或 Match 為止) 適用的條件,可多個,前置驚嘆號否定。

all: 都符合。必須單獨使用或緊接著 canonicalfinal 之後。

canonical:遠端 hostname 有 canonicalization 時額外套用。

final:最後額外套用。

exec 指令:在 shell 在執行指令回 0 時。指令有 whitespace characters 要quoted,接受 token %%、%h、%i、%L、%l、%n、%p、%r、和 %u。

The other keywords' criteria must be single entries or comma-separated lists and may use the wildcard and negation operators described in the PATTERNS section.

host hostname:比對 HostnameCanonicalizeHostname 轉換過後 hostname 符合。

originalhost hostname:比對指令行原始 hostname 符合。

user user:比對遠端帳號符合。

localuser user:比對本地帳號符合。在系統設定檔較有用。

BatchMode
如果設為 yes,user interaction such as password prompts and host key confirmation requests will be disabled. In addition, the ServerAliveInterval option will be set to 300 seconds by default (Debian-specific). This option is useful in scripts and other batch jobs where no user is present to interact with ssh(1), and where it is desirable to detect a broken network swiftly. The argument must be yes or no (the default).
CanonicalizeHostname
控制是否進行 hostname canonicalization。參考:https://sleeplessbeastie.eu/2020/08/24/how-to-perform-hostname-canonicalization/

預設 no:使用系統 resolver 處理 hostname lookups。

設為 yes:不用 ProxyCommand 或 ProxyJump 的連線,嘗試使用 CanonicalDomains 後綴和 CanonicalizePermittedCNAMEs 規則來canonicalize 指令行的 hostname。

設為 always:也用在 proxied 的連線。

設為 enabled:the configuration files are processed again using the new target name to pick up any new configuration in matching Host and Match stanzas.

CheckHostIP

預設是 yes,額外檢查 known_hosts 檔的 host IP 位址,無論 StrictHostKeyChecking 的設定都會加 host 位址到 ~/.ssh/known_hosts,用來偵測 host key 是否因為 DNS spoofing 而改變。

If the option is set to no, the check will not be executed.

Hostname
實際要登入的 host name,可以是 nicknames or abbreviations,接受 token %% and %h,可以是數字 IP (both on the command line and in Hostname specifications). The default is the name given on the command line.
KexAlgorithms
指定可用的 KEX (Key Exchange) 演算法. Multiple algorithms must be comma-separated. If the specified list begins with a ‘+’ character, then the specified methods will be appended to the default set instead of replacing them. If the specified list begins with a ‘-’ character, then the specified methods (in‐ cluding wildcards) will be removed from the default set instead of replacing them. If the specified list begins with a ‘^’ char‐ acter, then the specified methods will be placed at the head of the default set. The default is: curve25519-sha256,curve25519-sha256@libssh.org, ecdh-sha2-nistp256,ecdh-sha2-nistp384,ecdh-sha2-nistp521, diffie-hellman-group-exchange-sha256, diffie-hellman-group16-sha512, diffie-hellman-group18-sha512, diffie-hellman-group14-sha256 The list of available key exchange algorithms may also be ob‐ tained using "ssh -Q kex".
NumberOfPasswordPrompts
密碼嘗試次數,預設是 3。
PasswordAuthentication
是否使用密碼認證,yes (預設) 或 no。
Port
遠端 port,方便不是預設的 22。
PreferredAuthentications
嘗試認證方式的順序,預設是 gssapi-with-mic,hostbased,publickey,keyboard-interactive,password。
ServerAliveInterval
Sets a timeout interval 秒數 after which if no data has been received from the server, ssh 會送 message to request a response from the server. The default is 0, indicating that these messages will not be sent to the server, or 300 if the BatchMode option is set (Debian-spe‐ cific). ProtocolKeepAlives and SetupTimeOut are Debian-specific compatibility aliases for this option.
StrictHostKeyChecking

預設是 ask,新 host 的 key 在使用者同意後加入 ~/.ssh/known_hosts。host key 改變會拒絕連線。

設為 accept-new,自動加新 host 的 key。host key 改變會拒絕連線。

設為 yes,使用者必須手動加入新 host 的 key。host key 改變會拒絕連線。提供 man-in-the-middle (MITM) 攻擊最大的保護, though it can be annoying when the /etc/ssh/ssh_known_hosts file is poorly maintained or when connections to new hosts are frequently made.

設為 no 或 off,自動加新 host 的 key。host key 改變會檢查,除了一些限制外,仍允許連線。

User
指定登入帳號。
UserKnownHostsFile

Specifies one or more files to use for the user host key database, separated by whitespace. 預設是「~/.ssh/known_hosts ~/.ssh/known_hosts2」。

設為 UserKnownHostsFile=/dev/null

VerifyHostKeyDNS

Specifies whether to verify the remote key using DNS and SSHFP resource records.

設為 yes, the client will implicitly trust keys that match a secure fingerprint from DNS. Insecure fingerprints will be handled as if this option was set to ask.

設為 ask, information on fingerprint match will be displayed, but the user will still need to confirm new host keys according to the StrictHostKeyChecking option.

預設是 no。

See also VERIFYING HOST KEYS in ssh(1).

PATTERNS

pattern 是 0 或更多 non-whitespace characters

*:代表 0 或更多 characters

?:代表 1 個 character

pattern-list 是逗號分隔的 pattern 列表。裡面的 pattern 可以前置驚嘆號來否定。要注意的是否定符合本身不會變成正面的符合結果,例如下列結果 host3 並不符合:

from="!host1,!host2"

一種解決方式是包含一項達到正面符合,如 wildcard:

from="!host1,!host2,*"

TOKENS

有些 keyword 的 argument 可用 token,意思如下:

%%%
%CHash of %l%h%p%r。
%d自己的家目錄。
%h遠端 hostname。
%i自己 user ID。
%L自己 hostname。
%l自己 hostname, including the domain name。
%n原始指令行的遠端 hostname。
%p遠端 port。
%r遠端 username。
%T請求 tunnel forwarding 指定的 tun 或 tap 網路界面,無則 "NONE"。
%u自己 username。

      CertificateFile accepts the tokens %%, %d, %h, %i, %l, %r, and %u.

      ControlPath accepts the tokens %%, %C, %h, %i, %L, %l, %n, %p, %r, and
     %u.

    

     IdentityAgent and IdentityFile accept the tokens %%, %d, %h, %i, %l, %r,
     and %u.

     LocalCommand accepts the tokens %%, %C, %d, %h, %i, %l, %n, %p, %r, %T,
     and %u.

     ProxyCommand accepts the tokens %%, %h, %n, %p, and %r.

     RemoteCommand accepts the tokens %%, %C, %d, %h, %i, %l, %n, %p, %r, and
     %u.

問題

參考

  1. http://stackoverflow.com/questions/7332124/gitolite-with-non-default-port
  2. man ssh
  3. 基於 sftp 的 sshfs
  4. http://blog.trackets.com/2014/05/17/ssh-tunnel-local-and-remote-port-forwarding-explained-with-examples.html
  5. Bash ssh 由歷史資料來自動補齊主機名稱
  6. man ssh_config

SEE ALSO

     scp(1), ssh-add(1), ssh-agent(1), ssh-argv0(1), ssh-keygen(1),
     ssh-keyscan(1), tun(4), ssh-keysign(8), sshd(8)
待讀
https://www.bitvise.com/remote-desktop
http://www.howtogeek.com/114812/5-cool-things-you-can-do-with-an-ssh-server/
http://www.linuxjournal.com/content/more-secure-ssh-connections?utm_source=feedburner&utm_medium=feed&utm_campaign=Feed%3A+linuxjournalcom+%28Linux+Journal+-+The+Original+Magazine+of+the+Linux+Community%29
http://www.cyberciti.biz/faq/install-ssh-identity-key-remote-host/
[Linux 透過 SSH SOCKS 連線 來 使用 Firefox / Pidgin(MSN, GTalk..)](https://blog.longwin.com.tw/2010/01/linux-ssh-socks-firefox-pidgin-2010/)

2018年10月27日 星期六

bash PARAMETERS

bash 或其它 shell 的參數 (parameter),是一個儲存值的地方,可以是
  • 變數 (variable),名稱 (name) 非數字開頭由英文字母、數字及「_」組成的字,有一個值,並有屬性 (attribute) 可由內建指令 declare 指定。陣列。Shell 有內動的變數。
  • 一個數字
  • 一個特殊字元
參數經過指定或空字串 (沒) 產生。
參數=[]
透過內建指令 unset 移除。

所有值會經歷 tilde 擴展、參數和變數擴展、指令取代、算術擴展、及 quote 移除 (見 EXPANSION)。如果變數的屬性為整數 (integer),即使沒 $((...)) 也會以[算術表示式](見 bash Arithmetic Expansion) evaluated。除了「$@」外,不進行 Word splitting。不進行 Pathname expansion。變數指定亦可放在內建指令 alias、declare、typeset、export、readonly、及 local (declaration 指令) 的引數。
當用在 posix 模式,這些內建指令 may appear in a command after one or more instances of the command builtin and retain these assignment statement properties。

使用 += 運算指定一個值給 shell 變數或 array index 可進行 append 或加法運算,包括前面接受變數指定作為引數的內建指令。:
  • 整數變數:加法運算加上目前的值。
  • 使用 compound assignment 應用在陣列:indexed 陣列最後會多加一個值,associative 陣列新增 key-value 對。
  • 字串變數:值擴展後附加到字串後面。

Positional Parameters 位置參數

位置參數是從 1 開始的數字,由執行時的引數依序指定,不能由指定 statement 指定,可由內建指令 set 重新指定。執行 shell 函數時,位置參數暫時由函數引數取代。

當位置參數是多位數字時,需要用 braces 括起來。

註:$0 不算是位置參數。

Special Parameters 特殊參數

只能讀,不能指定。
*從 1 開始的所有位置參數,每個位置參數擴展為個別的字。依據進行的 context,可能會進行進一步 word splitting 和 pathname expansion。如果在雙引號裡面 ("$*"),擴展為一個字。位置參數間由特殊變數 IFS 第一個字元連接起來的。如果 IFS 沒設,則用 space 連接。如果 IFS 是 null,則不插入字元直接連接。
@從 1 開始的所有位置參數。如果在雙引號裡面 ("$@"),每個位置參數擴展為個別的字,相當於 "$1" "$2" ...  If the double-quoted expansion occurs  within  a word,  the  expansion of the first parameter is joined with the beginning part of the original word, and the expansion  of  the last  parameter  is  joined  with the last part of the original word.
#位置參數的數目。
?最後前景執行 pipeline 的 exit statu。
-目前 option flags。
$shell 的 process ID。在 ()  subshell,是 current shell 的 process ID,不是 subshell 的。
!最後背景執行的 process ID。
0shell 或 shell script 的名稱。
_shell 一開始時,設為 the absolute pathname used  to  invoke the shell or shell script being executed as passed in the environment or argument list.  Subsequently, expands  to  the  last argument to the previous command, after expansion.  Also set to the full pathname used to  invoke  each  command  executed  and placed  in  the  environment  exported  to  that command.  When checking mail, this parameter holds the name of the  mail  file currently being checked.

Shell Variables

下列變數由 shell 設定:
BASH:執行的完整檔名。
BASHOPTS
BASHPID
BASH_ARGC
BASH_ARGV
BASH_CMDS
BASH_COMMAND
BASH_EXECUTION_STRING
BASH_LINENO



BASH_REMATCH
由指令 [[ 的 =~ 運算指定的唯讀陣列,其中 index 0 是整個比對符合的字串,index n 是 第 n 個 parenthesized subexpression 比對的結果。
BASH_SOURCE
BASH_SUBSHELL
BASH_VERSINFO
BASH_VERSION
COMP_CWORD
COMP_KEY
COMP_LINE
COMP_POINT
COMP_TYPE
COMP_WORDBREAKS
COMP_WORDS
COPROC
DIRSTACK
EUID
FUNCNAME
GROUPS
HISTCMD
HOSTNAME
HOSTTYPE
LINENO
MACHTYPE
MAPFILE
OLDPWD
OPTARG
OPTIND
OSTYPE
PIPESTATUS
PPID
PWD
RANDOM
READLINE_LINE
READLINE_POINT
REPLY
SECONDS
SHELLOPTS
SHLVL
UID

下列變數 shell 會使用到,有時 bash 會指定預設值:

BASH_COMPAT
BASH_ENV
BASH_XTRACEFD
CDPATH
CHILD_MAX
COLUMNS
COMPREPLY
EMACS
ENV
FCEDIT
FIGNORE
FUNCNEST
GLOBIGNORE
HISTCONTROL
HISTFILE
HISTFILESIZE
HISTIGNORE
HISTSIZE
HISTTIMEFORMAT


HOME
目前使用者的家目錄。作為內建指令 cd 的預設引數及進行 tilde 擴展用。

每個使用者帳戶在 /etc/passwd 會有一行,包含用「:」分隔的 7 個欄位,其中最後第二欄是使用者的家目錄,login 程式用來設 $HOME。
HOSTFILE
IFS
IGNOREEOF
INPUTRC
LANG
LC_ALL
LC_COLLATE
LC_CTYPE
LC_MESSAGES
LC_NUMERIC

LINES
MAIL
MAILCHECK
MAILPATH
OPTERR
PATH
POSIXLY_CORRECT
PROMPT_COMMAND
PROMPT_DIRTRIM
PS1
PS2
PS3
PS4
SHELL
TIMEFORMAT
TMOUT
TMPDIR
auto_resume
histchars

Arrays

nameref 參考變數

變數可使用內建指令 declare 或 local 的 -n 選項設定 nameref 屬性,參照另一個變數,讓變數間接修改,此時除了改變 nameref 屬性外,指定、移除和其它屬性修改都進行在參照的變數。
declare -n ref=$R #建立 nameref 變數 ref
unset ref #移除變數 $R
unset -n ref #移除 nameref ref

nameref 常用在 shell 函數裡參照函數引數。例如在 shell 函數裡:
declare -n ref=$1
建立 nameref 變數 ref 參照第 1 個引數。

如果 for 迴圈的 control variable 有 nameref 屬性, the list of words can be a list of shell variables, and a name reference will be established for each word in the list, in turn,  when the loop is executed.

陣列變數不能指定 nameref 屬性,但 nameref 變數可以參照陣列變數和 subscripted  array variables。

參考

man bash 的 PARAMETERS

2018年10月6日 星期六

bash EXPANSION

bash 指令行切成字後會進行7 種擴展,依下列順序:
  1. brace ({}):
  2. tilde (~):目錄擴展
  3. $ parameter and variable 擴展、arithmetic 擴展、command substitution ($)
  4. word splitting:上面 ($) 類擴展如不在雙引號內,會依據 IFS 進行字切割。
  5. pathname
有些系統還支援額外的 process substitution,在上述順序 2 和 3 同時進行。

最後移除一開始就有的、未 quoted 的 quote 字元。

只有 brace expansion, word splitting, 及 pathname expansion 會改變字的數目,其它擴展擴展一個字為一個字,唯一的例外是 "$@" 及 "${name[@]}" 的擴展 (見 PARAMETERS).

Brace Expansion {}

{} 間一系列以「,」區隔的字串個別擴展為 word,或是兩個數字或兩個單一字元以「..」區隔的序列擴展 {x..y[..incr]}。序列擴展如果是數字的,前面可以加 0 來嘗試強迫產生相同位
數的數字。數字或字元間的序列擴展預設的增減值是 1 或 -1,可以再加「..數字」設定增減值。{} 裡可以有 {} 進行巢狀擴展。

「${」不做 brace 擴展,以免跟 parameter 擴展衝突。

例如
  • 「a{d,c,b}e」會擴展成「ade ace abe」
  • mkdir /usr/local/src/bash/{old,new,dist,bugs}
  • chown root /usr/{ucb/{ex,edit},lib/{ex?.?*,how_ex}}
傳統的 sh 沒有 Brace 擴展,要停用 Brace 擴展可以使用 +B 選項。

Tilde Expansion ~

tilde-prefix

Parameter Expansion

$ 字元引入參數擴展、指令取代、或算術擴展。

$參數 或 ${參數} 取代為變數值,參數名稱可用 {} 包起來避免跟緊接著的字元有錯誤連結。名稱是兩位以上數子,必須用 {} 包起來。

間接變數

下面 word 的部份會進行 tilde expansion、參數擴展、指令取代、和算術擴展。


${parameter:-word}
當 parameter unset 或 null 時,使用預設值 word。
${parameter:=word}
當 parameter unset 或 null 時,使用預設值 word 並指定給 parameter。位置參數和特殊參數不能用這種方式指定。
${parameter:?word}
${parameter:+word}
${parameter:offset}
${parameter:offset:length}
${!prefix*}
${!prefix@}
${!name[*]}
${!name[@]}
${#parameter}
參數長度
${parameter#word}
移除字串開頭最短符合 word 的部份。
${parameter##word}
移除字串開頭最長符合 word 的部份。
${parameter%word}
移除字串結尾最短符合 word 的部份。
${parameter%%word}
移除字串結尾最長符合 word 的部份。
${parameter/pattern/string}
${parameter//pattern/string}
${parameter/#pattern/string}
???
${parameter^pattern}
${parameter^^pattern}
轉換成大寫。
${parameter,pattern}
${parameter,,pattern}
轉換成小寫。

Command Substitution 指令取代

$(指令) 或 `指令`,取代為指令執行的輸出 (移除最後換行)。

$(cat file) 可以用更快的 $(< file) 取代。

Arithmetic Expansion

$((expression))

Process Substitution

Word Splitting 切割字

Pathname Expansion 路徑擴展

Pattern Matching

Quote Removal

移除所有非上述擴展產生的,unquoted 用的「\」、「'」、及「"」。

參考

  1. man bash 的 EXPANSION 節
  2. http://godleon.blogspot.tw/2007/06/shell-script-linux-pipe.html

2018年8月6日 星期一

bash: INVOCATION

login shell:選項有 -l 或 --login,或者指令名稱由「-」開頭,有登入 (或登出) 動作。

interactive shell:指令搭配 prompt 從標準輸入讀取,shell 需要支援一些互動所需要的動作。
  • 沒有非選項的引數,或有選項 -s。其標準輸入及錯誤輸出連接到 isatty() 決定的終端機。或者有選項 -i。不能有選項 -c 在引數指定指令。
  • 會設定 PS1 作為輸入指令的 prompt,且 $- 包含 i,讓 shell 指令檔或起始執行的檔案測試是否為 interactive。
接下來說明 bash 開始和結束時執行的檔案,如果檔案存在但無法讀取,bash 回報錯誤。檔名 tilde 擴展見 bash EXPANSION 的 Tilde Expansion。

當 bash 以名稱 sh 執行,會採用傳統 sh 的起始行為,並進入 posix 模式。

shelllogin
(不管是否為 interactive)
interactive
(不含 login)
非 interacitve
bashshbashshbashsh
啟始/etc/profile
~/.bash_profile
~/.bash_login
~/.profile 三者之一
/etc/profile
~/.profile
/etc/bash.bashrc
~/.bashrc
. "$ENV". "$BASH_ENV"
選項--noprofile --norc
--rcfile file
結束~/.bash_logout
bash 由 rshd 或 sshd 等 remote shell daemon 執行時,偵測標準輸入是否連到網路連線,使用 intreactive shell 的行為。

如果 shell 開始時 effective user (group) ID 跟 real user (group) ID 不同,啟始檔案不執行,且不自環境繼承 shell function,忽略變數 SHELLOPTS、BASHOPTS、CDPATH、和 GLOBIGNORE。此時選項 -p 沒設,effective user ID 設為 real user ID。

判定是否在互動模式

方式一:看 $- 是否有 i
case "$-" in
*i*) echo This shell is interactive ;;
*)   echo This shell is not interactive ;;
esac

方式二:PS1 有設

if [ -z "$PS1" ]; then
    echo This shell is not interactive
else
    echo This shell is interactive
fi

參考來源

man bash INVOCATION 節

延伸閱讀

2018年7月22日 星期日

bash: SHELL BUILTIN COMMANDS

內建指令是 shell 本身提供的指令,有些 shell 用外部指令取代。

除非特別說明,接受「-」開頭選項的內建指令也接受「--」來表示選項的結束。但「:」、「true」、「false」、及「test」並不接受選項,也就不處理「--」。「exit」、「logout」、「break」、「continue」、「let」、及「shift」接受及處理「-」開始的引數,不需要「--」作為結束。其它接受引數、但不接受選項的內建指令,「-」開始的引數會解釋為無效的選項,需要「--」來避免這種情況。

: [arguments]

只是擴展 arguments 及進行指定的轉向。

.  filename [arguments]
source filename [arguments]

在當下的 shell 環境執行 filename。如果 filename 不含 slash,會去 PATH 找 filename (不需要可執行)。如果 bash 不在 posix  模式,會再找目前目錄。如果內建指令 shopt 的選項 sourcepath 關閉,不找 PATH。如果有任何 arguments,會成為位置參數。

如果 -T 選項啟用,繼承 DEBUG trap。如果沒啟用,DEBUG trap 字串會備份後清掉,執行完再回復。參考內建指令 set。

alias [-p] [name[=value] ...]

bg [jobspec ...]


bind [-m keymap] [-lpsvPSVX]
bind [-m keymap] [-q function] [-u function] [-r keyseq]
bind [-m keymap] -f filename
bind [-m keymap] -x keyseq:shell-command
bind [-m keymap] keyseq:function-name
bind [-m keymap] keyseq:readline-command

bash readline 按鍵對應功能的顯示和綁定、或設定 readline 變數。

每個非選項的引數是如同 .inputrc 的指令,但 binding 跟 command 需要用不同引數傳遞
。例如「"\C-x\C-r":  re-read-init-file」.

選項:
  • -m keymap:keymap 可為 emacs (emacs-standard)、emacs-meta、emacs-ctlx、vi (vi-command)、vi-move、及 vi-insert,影響後續的綁定。
  • -l:列出所有 readline 功能名稱
  • -p:顯示 readline 功能名稱及綁定 (可輸入格式)
  • -P:顯示 readline 功能名稱及綁定
  • -s:顯示 readline key sequences bound to macros and the strings they output (可輸入格式)
  • -S:顯示 readline key sequences bound to macros and the strings they output.
  • -v:顯示 readline 變數名稱及值 (可輸入格式)
  • -V:顯示 readline 變數名稱及值
  • -f filename:自 filename 讀取 key bindings
  • -q function:詢問 function 綁定的 key
  • -u function:取消 function 綁定的 key
  • -r keyseq:移除任何目前 keyseq 的綁定
  • -x keyseq:shell-command:輸入 keyseq 執行 shell-command。shell-command 執行時, shell 設定變數 READLINE_LINE 為 readline line buffer 內容及 READLINE_POINT 為目前游標位置。如果執行的指令改變 READLINE_LINE 或 READLINE_POINT 的值,將會反應在編輯狀態。
  • -X:列出綁定到 shell command 的 key sequence 和 shell command (可輸入格式)

break [n]

跳脫 n 層 for、while、until、或 select 迴圈,n 預設為 1。

builtin shell-builtin [arguments]

用內建指令執行。
當定義的 function 名稱跟內建指令相同時,用來強制使用內建指令。

內建指令 cd 常常用 function 重新定義。

如果 shell-builtin 不是一個內建指令,回傳值是 false。

caller [expr]


cd [-L|[-P [-e]] [-@]] [dir]


command [-pVv] command [arg ...]


compgen [option] [word]


complete [-abcdefgjksuv] [-o comp-option] [-DE] [-A action]  [-G glob‐pat] [-W wordlist] [-F function] [-C command] [-X filterpat] [-P prefix] [-S suffix] name [name ...]
complete -pr [-DE] [name ...]


compopt [-o option] [-DE] [+o option] [name]


continue [n]

直接開始下一回 for、while、until、或 select 的控制迴圈。如果有 n,開始第 n 層封閉迴圈。如果 n 超出所有封閉迴圈層數,則使用最外層。

declare [-aAfFgilnrtux] [-p] [name[=value] ...]
typeset [-aAfFgilnrtux] [-p] [name[=value] ...]


dirs [-clpv] [+n] [-n]


disown [-ar] [-h] [jobspec ... | pid ... ]


echo [-neE] [arg ...]


enable [-a] [-dnps] [-f filename] [name ...]

啟用及停用內建指令。
停用某個內建指令可以不用指令完整路徑執行同名的外部指令

範例:
  • `enable -n test` 停用內建指令 test
  • `enable test` 啟用內建指令 test
  • `enable` 或 `enable -p` 列出啟用的內建指令
  • `enable -n` 列出停用的內建指令
  • `enable -a` 列出所有內建指令,無論啟用及停用的
  • `enable -s` 列出啟用的 POSIX 內建指令
  • `enable -f filename name` 載入 filename (shared object 檔) 作為內建指令 name。
  • `enable -d` 移除之前透過 -f 載入的內建指令

eval [arg ...]

exec [-cl] [-a name] [command [arguments]]

執行 command 取代原本 process。
  • -l:在引數 0 前置「-」,如同指令 login。
  • -c:以空的環境變數執行。
  • -a name:使用 name 作為引數 0 (指令名稱)
shopt 選項 execfail 啟用:command 在非 interactive shell 無法執行時,不離開,改回傳失敗。

exit [n]


export [-fn] [name[=word]] ...
export -p


fc [-e ename] [-lnr] [first] [last]
fc -s [pat=rep] [cmd]


fg [jobspec]


getopts optstring name [args]


hash [-lr] [-p filename] [-dt] [name]

help [-dms] [pattern]


history [n]
history -c
history -d offset
history -anrw [filename]
history -p arg [arg ...]
history -s arg [arg ...]


jobs [-lnprs] [ jobspec ... ]
jobs -x command [ args ... ]


kill [-s sigspec | -n signum | -sigspec] [pid | jobspec] ...
kill -l|-L [sigspec | exit_status]


let arg [arg ...]

每個 arg 是要 evaluated 的 arithmetic expression。如果最後 arg evaluates 為 0,回傳 1,否則回傳 1。

local [option] [name[=value] ... | - ]


logout

登出,離開 login shell。

mapfile  [-d  delim] [-n count] [-O origin] [-s count] [-t] [-u fd] [-C callback] [-c quantum] [array]
readarray [-d delim] [-n count] [-O origin] [-s count] [-t] [-u fd] [-C callback] [-c quantum] [array]


popd [-n] [+n] [-n]


printf [-v var] format [arguments]


pushd [-n] [+n] [-n]
pushd [-n] [dir]


pwd [-LP]


read [-ers] [-a aname] [-d delim] [-i text] [-n nchars] [-N nchars] [-p prompt] [-t timeout] [-u fd] [name ...]


readonly [-aAf] [-p] [name[=word] ...]


return [n]


set [--abefhkmnptuvxBCEHPT] [-o option-name] [arg ...]
set [+abefhkmnptuvxBCEHPT] [+o option-name] [arg ...]

shift [n]

所有位置參數往前位移 n 個位置,沒給 n 值時當作 1。n 超出範圍不動作,回傳失敗。

shopt [-pqsu] [-o] [optname ...]


suspend [-f]


test expr 或 [ expr ]


times

印出 shell 和透過其執行的累計使用者和系統時間。

trap [-lp] [[arg] sigspec ...]


type [-aftpP] name [name ...]


ulimit [-HSabcdefiklmnpqrstuvxPT [limit]]

控制 shell 和啟始的 process 可用的資源。選項 -H 及 -S 分別指定只設定 hard limt 或 soft limit,不然兩者都設。hard limit 設定之後只有 root 可以增加。soft limit 不能增加超過 hard limit。limit 可以是一個數字 (依據特定資源的單位),或是 hard、soft、或 unlimited 之一。如果省略 limit,預設印出目前的 soft limit,除非加 -H 選項。如果一次要印出多個資源,資源名稱及單位會印在值之前。參數沒指定資源時,預設是 -f,指檔案最大可寫入的大小。值大多以 1024-byte 為單位,-c 和 -f 在 posix 模式以 512-byte 為單位。其它選項說明如下:
  • -a:印出所有資源限制。
  • -b:最大 socket buffer 數目。
  • -c:最大建立的 core files 大小。
  • -d:最大 process 的 data segment 大小。
  • -e:最大 scheduling priority ("nice")。
  • -f:最大檔案可寫入的大小。
  • -i:最多 pending signals 的數目。
  • -k:最多可配置的 kqueue 數目。
  • -l:最大可 locked into memory 的大小。
  • -m:最大 resident set 大小 (許多系統不 honor this limit)。
  • -n:最多可開啟的 file descriptor (大部分系統不允許設定)。
  • -p:pipe 大小,以 512-byte block 為單位。(可能不能設。)
  • -q:在 POSIX message queues 最大 byte 數。
  • -r:最大 real-time scheduling priority。
  • -s:最大 stack 大小。
  • -t:最大 cpu time 秒數。
  • -u:單一使用者最多 process 數目。
  • -v:shell (或其 children) 最大 virtual memory。
  • -x:最多可鎖定的檔案數目。
  • -P :最多虛擬終端機數目。
  • -T:最大 thread 數目。

umask [-p] [-S] [mode]


unalias [-a] [name ...]

unset [-fv] [-n] [name ...]


wait [-n] [n ...]

參考來源

bash man page 的 SHELL BUILTIN COMMANDS

2018年7月21日 星期六

bash: DEFINITIONS, RESERVED WORDS & COMMENTS

定義
  • blank:space 或 tab 字元。
  • word 或 token:字,視為一個單元的一系列字元,由 metacharacter 切割。token 可以是字或運算子。
  • name 或 identifier:由英文字母、數字及「_」組成的字,不能以數字開頭,可作為 shell 變數或 function 名稱。
  • metacharacter:沒 quoted 時切割出 word 的字元,包括:
    • space、tab
    • 「<」與「>」:亦有輸出入導向功能 (redirection operator)
    • 「|」「&」「;」「(」「)」<newline>:組合出所有控制運算子 (control operator),亦區隔出子指令並控制執行方式。
  • control operator:進行執行控制功能的 token,包括:
    • 「|」或「|&」:串接前後指令的輸出入成為 pipeline。
    • 「&&」:AND,前面指令執行成功 (回傳值 0) 才執行下個指令。
    • 「||」:OR,前面指令執行失敗 (回傳值不為 0) 才執行下個指令。
    • 「&」:背景執行
    • 「;」或 <newline>:執行
    • ( ):subshell 執行
    • 「;;」、「;&」、「;;&」:用在 case
保留字:在 shell 有特殊意義的字,用在 simple command 第一個字 (見 bash SHELL GRAMMAR) 或指令 case、for 的第三個字。
  • !
  • case esac
  • coproc
  • do done
  • for
  • function
  • if then elif else fi
  • in select
  • until
  • while
  • { }
  • time
  • [[ ]]
註解
  • 字元 # 開始的字到行末都會忽略。互動式 shell 可用內建指令 shopt 的 interactive_comments 關閉註解功能。

參考來源

man bash 的 DEFINITIONS, RESERVED WORDS & COMMENTS 節

bash: ALIASES

alias 意思是「化名」。在 bash,每個 simple command 的第一個字符合某個 alias 名稱,會取代為對應的 alias 值。取代後的第一個字再繼續進行 alias,但如果是已經用過的 alias 名稱,就不再進行。例如 ls alias 為 ls -F 只會進行一次。如果 alias 的值的最後字元是一個 blank (依定義,blank 是 space 或 tab),指令下個字也進行 alias。

shell 有個 alias 列表,可透過內建指令 alias 和 unalias 來列出、設定和消除。alias 名稱不能包含字元 /、$、`、=、metacharacter 或 quoting 字元。alias 值可以包含任何 valid shell input,包括 metacharacters。

alias 用在互動式 shell,如果非互動式 shell 也要用,使用內建指令 shopt 設 expand_aliases。

alias 是在整行指令讀取時進行,而不是執行時進行。同行的新 alias 定義要等到指令執行完才會生效,並不會對同行指令生效。在 function 也是同樣的,alias 是在 function 定義讀取時進行,function 裡的新 alias 定義要等到 function 執行才會生效。安全的作法是把 alias 定義放在自己獨立一行,不要用在 compound command。

alias 進行優先於 shell function。

內建指令:alias [-p] [name[=value] ...]

alias 或 alisa -p 以 alias name=value 格式印出所有 alias 或印指定 name 的 alias。
設定 name 的 alias 為 value。

內建指令:unalias [-a] [name ...]

移除 alias 名稱 name。選項 -a 移除所有 alias。

shell 變數 BASH_ALIASES

由 alias 名稱作為 index 的一個  associative  陣列,成員是 alias 表。陣列新增成員會出現在 alias 表,但清除成員目前並不會從 alias 表移除。如果 unset BASH_ALIASES 會失去其特殊 properties。

列出 BASH_ALIASES
$ declare -p BASH_ALIASES

$ for k in "${!BASH_ALIASES[@]}"; do printf '%s => %s\n' "$k" "${BASH_ALIASES[$k]}"; done

參考來源

  1. bash 的 ALIASES 節、內建指令 alias、shell 變數 BASH_ALIASES
  2. https://unix.stackexchange.com/questions/109124/bash-aliases-not-equal-to-alias

bash: OPTIONS 和內建指令 set

bash 指令格式是 bash [--選項] [-選項] [引數],多字元選項「--選項」必須放在單字元選項「-選項」前面,之後是引數。通常第一個引數是指令 ($0),剩下引數傳給指令使用 ($1, $2, ...)。

單字元選項可使用內建指令 set 支援的單字元選項外,還可以用下列選項:
  • -c:第一個引數還是一樣是指令,但傳給指令的 $0 是第二個引數,位置參數 $1 從第三個引數開始。$0 作為警告和錯誤訊息的指令名稱。
  • -iinteractive shell
  • -l 或 --login:啟動為 login shell
  • -r:見 RESTRICTED SHELL
  • -s:指令從標準輸入讀取,不用引數的指令。在 interactive shell 設定為位置參數。
  • -D--dump-strings:在標準輸出印出所有前置 $ 的雙引號字串,當 locale 不為 C 或 POSIX 時會做語言轉換。隱含 -n 選項,不執行指令。
  • [-+]O [shopt_option]:-O 設定內建指令 shopt 的 shell 選項,+O 清掉。沒有 shopt_option 時,印出這些選項的名稱及值,如果用 +O 輸出可作為輸入的格式。
  • ---:表示選項結束,之後的引數視為檔名及其引數。
其它多字元選項:
  • --debugger:在 shell 開始前安排執行 debugger profile,啟用 extended 除錯模式 (見 bash 內建指令 shopt 選項 extdebug 的說明)
  • --dump-po-strings:相當於 -D,但以 GNU gettext po (portable object) 檔案格式輸出。
  • --help:顯示使用說明。
  • --init-file file--rcfile file:在 interactive shell 改執行 file 取代 /etc/bash.bashrc 及 ~/.bashrc (見 bash INVOCATION)。
  • --noediting:在 interactive shell 不使用 GNU readline 函式庫來讀取指令行。
  • --noprofile:不執行 /etc/profile、~/.bash_profile、~/.bash_login、或 ~/.profile。login shell 預設執行這些檔案 (見 bash INVOCATION)
  • --norc:在 interactive shell 不執行 /etc/bash.bashrc 及 ~/.bashrc。以 sh invoke 時預設啟用。
  • --posix:行為符合 POSIX 標準模式。見 SEE ALSO 參考  how posix mode affects bash's behavior 細節的文件。
  • --restricted:restricted shell (見 bash RESTRICTED SHELL).
  • --verbose:相當於 -v。
  • --version:顯示版本訊息。

內建指令 set

功能有設定 shell 選項、設定位置參數、列變數

set [--abefhkmnptuvxBCEHPT] [-o option-name] [arg ...]
set [+abefhkmnptuvxBCEHPT] [+o option-name] [arg ...]
set #依順序列出所有 shell 變數
set arg ... #依序設定位置參數 $1、$2、 ...

指令的選項用來設定或清除 shell 選項。除非特別說明,選項預設是關閉的。使用 --o 開啟選項,++o 關閉選項。

$- 可看到目前的選項。

指令選項說明如下:

-a 或 -o allexport

每個新建或更改的變數,export 到接下來指令的環境。

-b 或 -o notify

立刻回報結束的背景工作,而不是等到下個指令提示。

-e 或 -o errexit

待續

-f 或 -o noglob

停用 pathname 擴展。

-h 或 -o hashall

記憶執行時查到的指令路徑,預設是開啟的。

-k 或 -o keyword

待續

-m 或 -o monitor

待續

-n 或 -o noexec

讀取指令但不執行。可用來檢查 shell 指令搞是否有 syntax errors。在 interactive shell 沒作用。

-o option-name

沒 option-name 時列出目前 shell 選項設定,+o 顯示一系列 set 指令,可用來重新建立目前選項設定。

option-name 大多搭配有單字元格式,沒有的有:
  • emacs:使用 emacs-style 指令行編輯界面。interactive shell 預設啟用,除非 shell 時使用選項 --noediting。同時影響編輯界面用來讀取 -e。
  • history:啟用指令歷史功能 (見 bash HISTORY)。interactive shell 預設啟用。
  • ignoreeof:等同執行 shell 指令 ``IGNOREEOF=10''。(見 Shell Variables).
  • nolog:目前忽略
  • pipefail:回傳最後失敗指令的回傳值。
  • posix:使用 posix 模式。.
  • vi:使用 vi-style 指令行編輯界面。同時影響編輯界面用來讀取 -e。

-p 或 -o privileged

開啟特權 (privileged) 模式,此時 $ENV 及 $BASH_ENV 的檔案不處理,不自環境繼承 shell 函數,忽略變數 SHELLOPTS、BASHOPTS、CDPATH、及 GLOBIGNORE。
如果 shell 開始時的 effective user (group) ID 和 real user (group) ID 不同,也進行
這些動作。此時如果 -p 沒設,effective user id (group) 會設為 real user (group) id;如果有設,則不動 effective user (group) id。

-t 或 -o onecmd

讀完執行一個指令離開。

-u 或 -o nounset

待續

-v 或 -o verbose

印出讀到的輸入行。

-x 或 -o xtrace

trace 模式。擴展每個 simple command、for、case、select、或 arithmetic for 後,顯示 PS4 和指令。

-B 或 -o braceexpand

進行 brace expansion (見 bash Brace Expansion),預設啟用。

-C 或 -o noclobber

>,  >&,  and <> redirection operators 不覆寫存在的檔案。對 >| 則不影響。

-E 或 -o errtrace

待續

-H 或 -o histexpand

待續

-P 或 -o physical

待續

-T 或 -o functrace

待續

--

表示是最後的指令選項,接下來有引數的話,設定位置參數,否則重置位置參數。

-

表示是最後的指令選項,接下來有引數的話,設定位置參數。關閉指令選項 -x 和 -v。

參考來源

man bash OPTIONS 節、內建指令 set

2018年7月19日 星期四

bash

GNU 的 Bash (Bourne-Again SHell) 是一個指令語言直譯器,執行來自標準輸入或檔案的指令,與 sh 相容並結合 Korn shell (ksh) 及 C shell (csh) 的優點,相容 IEEE POSIX 標準的 Shell and Utilities 部份。

指令格式:
bash [options] [command_string | file]
整個指令由空白字元分成許多字,一開始可有一些選項 (option)。如果選項沒設 -c 或 -s 且之後還有引數,第一個引數會認定是一個檔名,並設為 $0。之後的引數依序設為位置參數 $1、$2、...。bash 會讀取並執行檔案內的指令,然後離開,離開狀態碼預設 0,最後執行的指令有最後決定權。檔案首先會在目前目錄找,如沒有再找 PATH 指定的目錄。

INVOCATION
DEFINITIONS, RESERVED WORDS, & COMMENTS
SHELL GRAMMAR
QUOTING
PARAMETERS
EXPANSION
REDIRECTION
ALIASES 別名
FUNCTIONS
ARITHMETIC EVALUATION
CONDITIONAL EXPRESSIONS
SIMPLE COMMAND EXPANSION
COMMAND EXECUTION
COMMAND EXECUTION ENVIRONMENT
ENVIRONMENT
EXIT STATUS 結束狀態
SIGNALS
JOB CONTROL
PROMPTING
READLINE
HISTORY
HISTORY EXPANSION
SHELL BUILTIN COMMANDS 內建指令
RESTRICTED SHELL
SEE ALSO
FILES

參考來源
  1. man bash
延伸閱讀

2018年7月18日 星期三

nc

netcat 在 Linux 中的指令為 nc,網路的 cat 工具程式,透過網路連結 stdin 和 stdout,原汁原味傳送資料。另外也可以掃描通訊埠。

     nc [-46bCDdFhklNnrStUuvZz] [-I length] [-i interval] [-M ttl] [-m minttl]
        [-O length] [-P proxy_username] [-p source_port] [-q seconds]
        [-s source] [-T keyword] [-V rtable] [-w timeout] [-X proxy_protocol]
        [-x proxy_address[:port]] [destination] [port]

nc 可作為基於指令稿的 Client 或 Server,可用在 TCP、UDP、或 UNIX-domain sockets,作通訊埠掃描,可處理 IPv4 和 IPv6。
  • destination 是 IP 位址或主機名稱,當伺服器端時 (使用 -l 選項) 不指定是指本機。在 UNIX-domain 是 socket 路徑。
  • port 可以是數字或服務名稱,或數字範圍。

使用可直接看下面範例。

    基本 client/server 連線

    在特定埠等待連線,server 端使用選項 -l (listen 等待進來連線。不能搭配選項 -p、-s、-z 使用,-w timeout 選項沒作用。)
    $ nc -l 1234
    在另一個終端機當 client,進行連線
    $ nc 127.0.0.1 1234
    任何一方的輸入,在另一方會出現。Ctrl-C 結束連線 (EOF (‘^D’) ?)。

    nc 沒有選項將收到的資料作為指令執行 (例如其它指令的選項 -c 或 -e),但可透過輸出轉向和 fifo 解決。server 輸出導給 fifo,取出給 /bin/sh 執行,再將結果傳給 server 顯示到 client。
    伺服器端:
    $ rm -f /tmp/f; mkfifo /tmp/f
    $ cat /tmp/f | /bin/sh -i 2>&1 | nc -l 127.0.0.1 1234 > /tmp/f
    使用者端:
    $ nc host.example.com 1234
    $ (shell prompt from host.example.com)
    註:busybox nc 有 -e 選項。

    當連線結束,nc 就結束。想要持續 listening 使用 -k 選項。

    傳送檔案

    接收端:
    $ nc -l 1234 > filename.out
    傳送端:
    $ nc -N host.example.com 1234 < filename.in

    傳送目錄

    接收端:
    nc -l 1234 | tar xvf -

    傳送端:
    tar cvf - /path/to/dir | nc host.example.com 1234

    遠端備份硬碟

    接收端:
    nc -l 1234 | dd of=sdb-backup.img.gz
    傳送端:
    dd if=/dev/sdb | gzip -c | nc hostB.com 1234
    回復接收端:
    nc -l 5000 | gzip -d | sudo dd of=/dev/sdb
    回復傳送端:
    nc hostA.com 5000 < sdb-backup.img.gz

    連線到伺服器

    取網頁:(註:echo 參數,n 不送換行,e 解釋反斜線跳脫。)
    $ echo -ne "GET / HTTP/1.0\r\n\r\n" | nc host.example.com 80
    送電子郵件到 SMTP 伺服器:
    $ nc [-C] localhost 25 << EOF
    HELO host.example.com
    MAIL FROM:<user@host.example.com>
    RCPT TO:<user2@host.example.com>
    DATA
    Body of email.
    .
    QUIT
    EOF

    偵測通訊埠

    用 -v 選項啟用 stderr verbose 輸出
    $ nc -v host.example.com 1234
    nc: connect to host.example.com (tcp) failed: Connection refused
    有開啟的話,通常 greeting banner 訊息含有伺服器執行的軟體和版本:
    $ nc -v host.example.com 22
    Connection to host.example.com 22 port [tcp/ssh] succeeded!
    SSH-2.0-OpenSSH_6.0p1 Debian-4
    使用 -z 選項和依序掃描通訊埠範圍:
    $ nc -zv host.example.com 20-30
    Connection to host.example.com 22 port [tcp/ssh] succeeded!
    Connection to host.example.com 25 port [tcp/smtp] succeeded!
    指定掃描的埠:
    $ nc -zv host.example.com 80 20 22
    nc: connect to host.example.com 80 (tcp) failed: Connection refused
    nc: connect to host.example.com 20 (tcp) failed: Connection refused
    Connection to host.example.com port [tcp/ssh] succeeded!
    掃描通訊埠範圍取得 greeting banners 才斷開連線,可透過 -w 指定短 timeout 或送「QUIT」指令給伺服器:
    $ echo "QUIT" | nc host.example.com 20-30
    SSH-1.99-OpenSSH_3.6.1p2
    Protocol mismatch.
    220 host.example.com IMS SMTP Receiver Version 0.84 Ready
    使用 -uz 選項的 UDP port 掃描不論有沒有都會回報成功 (有送出就成功?),可用 traffic sniffer 查看封包。

    送測試 UDP 封包
    echo -n "foo" | nc -u -w1 host.example.com 1234
    接收:
    nc -lu 1234

    其它範例

    TCP 連線到 host.example.com:42,使用 31337 最為來源埠,timeout 5 秒:
    $ nc -p 31337 -w 5 host.example.com 42
    UDP 連線到 host.example.com:53:
    $ nc -u host.example.com 53
    TCP 連線到 host.example.com:42,使用 10.1.2.3 作為來源 IP:
    $ nc -s 10.1.2.3 host.example.com 42
    接收 UNIX-domain stream socket 的連線:
    $ nc -lU /var/tmp/dsocket
    透過 HTTP proxy 10.2.3.4:8080 連線到 host.example.com:42。見 ssh_config 的 ProxyCommand directive 搭配 ssh 使用。
    $ nc -x10.2.3.4:8080 -Xconnect host.example.com 42
    透過有認證的 HTTP proxy 連線:
    $ nc -x10.2.3.4:8080 -Xconnect -Pruser host.example.com 42

    其它選項說明

    • -4:只用 IPv4 位址
    • -6:只用 IPv6 位址
    • -b:允許廣播
    • -C:送 CRLF 作為 line-ending
    • -D:啟用 socket 除錯
    • -d:不嘗試讀取 stdin
    • -F:使用 sendmsg() Pass the first connected socket 到 stdout 後離開。使用 -X 選項跟 proxy 進行連線後,把連線留給其它程式,例如 ssh() 使用 ssh_config ProxyUseFdpass 選項。
    • -h:印出 help
    • -I length:指定 TCP 接收 buffer 大小。
    • -i interval:指定每行送收間的延遲時間。同時導致連線多個通訊埠的延遲時間。
    • -k:連線結束後持續等待其它連線,需搭配 datagram 選項 (-u) 使用。
    • -M ttl:設送出封包的 TTL。
    • -m minttl:請求 kernel 拋棄進來封包 TTL 小於 minttl 的。
    • -N:輸入 EOF 後 shutdown() 網路 socket。有些伺服器需要這樣才能完成工作。
    • -n:不對指定的位址、主機名稱、或通訊埠進行 DNS service lookup。
    • -O length:指定 TCP 傳送 buffer 大小。
    • -P proxy_username:指定 HTTP proxy 認證的使用者名稱。
    • -p source_port:指定使用的來源通訊埠。subject to privilege restrictions and availability。
    • -q seconds:在 stdin 的 EOF 後,等候後才離開 (implies -N)。如果是負數,wait forever。
    • -r:在範圍內,以亂數方式選擇通訊埠。
    • -S:啟用 RFC 2385 TCP MD5 signature 選項。
    • -s source:指定來源 IP 或 UNIX-domain socket 檔案。
    • -T keyword:設定 IPv4 ToS 值,可以是 critical、inetcontrol、lowcost、lowdelay、netcontrol、throughput、reliability、或 DiffServ Code Point (ef、af11、...、af43、cs0、...、cs7)、或十六進位或十進位數字。
    • -t:送 RFC 854 DON'T and WON'T response to RFC 854 DO and WILL 請求,讓 nc script telnet session。
    • -U:使用 UNIX-domain socket。
    • -u:使用 datagram。
    • -V rtable:設定使用的 routing table。
    • -v:verbose 輸出。
    • -w timeout:對外連線的 timeout。
    • -X proxy_protocol:使用的 proxy 協定,4 是 SOCKS v.4、5 是 SOCKS v.5、connect 是 HTTPS proxy。預設是使用 SOCKS v.5。
    • -x proxy_address[:port]:proxy 的位址。
    • -Z:DCCP 模式。
    • -z:進行掃描。

    參考來源

    1. man nc
    2. http://blog.gtwang.org/linux/linux-utility-netcat-examples/

    延伸閱讀

    2017年10月31日 星期二

    Bash hash 執行檔路徑的快取

    bash 會自動將透過 $PATH 找到的執行檔完整路徑存在 hash 表裡,下次使用就不用再找 $PATH 而直接採用 hash 表紀錄的完整路徑。

    內建指令 hash

    hash [-lr] [-p filename] [-dt] [name]
    • hashhast -d:印出 hash 表中所有記錄的完整路徑及使用次數
    • hash -d name:刪除 hash 表中 name 的紀錄 (可有多個 name)
    • hash -r:刪除 hash 表中所有的記錄
    • hosh -t name:印出 hash 表中 name 的完整路徑 (可有多個 name)
    • hash -p filename name:為 name 在 hash 表建立使用 filename 作為完整的檔名。可用來非標準路徑的執行檔
    • hash -l:印出 hash 表中所有的記錄的完整路徑,採用可輸入格式,可用來事先建立 hash 表用
     參考:
    • man bash
    • 內建指令 shopt 選項 checkhash
    • 內建指令 type
    • restricted shell
    • Shell 變數 BASH_CMDS

    Bash Quoting

    quoting 是引號的意思,有單引號「'」跟雙引號「"」,作用是跳脫特殊字元 (metacharacters, ...) 和保留字的解釋,或避免參數擴展。另外「\」也用來跳脫特殊字元,在此一併說明。
    • \<字元>:跳脫緊接著字元的特殊意義。除了「\<換行字元>」是連結到下一行,一般編輯器看到是行尾「\」,然後換了一行。
    • 單引號包起來:跳脫裡面所有字元及字的特殊意義。包括「\」,所以單引號無法巢狀使用。
    • 雙引號包起來:跳脫裡面所有字元及字的特殊意義,除了
      • 「$」及「`」的擴展仍進行
      • 「\」跳脫 $、`、"、\、<換行>
      • 「!」歷史擴展仍進行,但「\!」不進行歷史擴展。在 POSIX 模式「!」沒特殊意義。
      • 「*」及「@」.... (見 PARAMETERS).
    雙引號可以藉由「\"」跳脫來巢狀使用

    $'string':「$」後的單引號字串會轉換裡面的下列「\<字元>」成 ANSI C 標準字元,轉換後依照上述單引號方式解釋。
    \<字元>轉換後字元
    \aalert (bell)
    \bbackspace
    \e 或 \Eescape
    \fform feed
    \nnew line
    \rcarriage return
    \thorizontal tab
    \vvertical tab
    \\backslash
    \'single quote
    \"double quote
    \nnn用 1 到 3 位十進位數字表示 8-bit 字元
    \xHH用 1 到 2 位十六進位數字表 示8-bit 字元
    \uHHHH用 1 到 4 位十六進位數字表示 Unicode (ISO/IEC 10646) 字元
    \UHHHHHHHH用 1 到 8 位十六進位數字表示 Unicode (ISO/IEC 10646) 字元
    \cxcontrol-x 字元
    應用:Shell 工作完成自動發聲通知

    $"string":「$」後的雙引號字串依據 locale 轉換,轉換後依照上述雙引號方式解釋。

    延伸閱讀

    2013年11月25日 星期一

    regular expression

    正規表示式、字串樣本、字串比對

    正規表示式是一種進階的字串比對,用「符號」描述字串的樣式,說明某個位置可以是哪些字元、符合的次數等。只要了解這些特殊「符號」,英文稱 metacharacter,可翻作「字元符」,就可以了解正規表示式。正規表示式在許多地方都可以見到,例如 grepsed、vi、JavaScript、git grep、IMS PSI 等。

    字元描述

    大部分字元,包括英文字母及數字,代表的就是它自己。其它的是有特殊意義的符號,可描述字元、位置、次數等。
    • .:任何字元。
    • \:跳脫字元,跳脫下個字元原本的解釋,原本是 metacharacter,就不解釋為 metacharacter。原本不是 metacharacter,改解釋為 metacharacter。
    • \d:數字。
    • \D:非數字,和 \d 相反。
    • \s:
    • \S:
    • []: bracket 表示式,[] 包起來,內含比對單一字元符合的列表。但如果內容以 ^ 開頭,則為不包含的列表。
      • 可用「-」表示範圍。例如「a-d」相當於「abcd」(在有些 locale 的字典順序不同,會變成「aBbCcDd」)。
      • 列表中也可以包含特定事先定義的類別,包括 [:alnum:], [:alpha:], [:blank:], [:cntrl:], [:digit:], [:graph:],[:lower:], [:print:], [:punct:], [:space:], [:upper:], 和 [:xdigit:]。注意,這裡的 [] 是類別名稱的一部分,[[:alnum:]] 代表數字及英文字母。
      • 大多 metacharacter 在 [] 裡失去其原本的特殊意義。要解除 ] 特殊意義,可放在列表第一個,^ 就不要放在第一個,- 放在最後。
    • \w:底線、數字或英文字母,相當於 [_[:alnum:]]。
    • \W:和 \w 相反,相當於 [^_[:alnum:]]。

    位置描述

    代表位置
    • ^:行開頭
    • $:行結尾
    • \< 及 \>
    • \b
    • \B

    次數描述

    說明重複的次數,沒有的話就是一次。
    • { }:重複次數。{2} 表重複兩次,{2,5} 表重複 2 至 5 次,{2,} 表兩次以上
    • *:0 次以上,相當於 {0,}。
    • +:1 次以上,相當於 {1,}。
    • ?:0 次或 1 次,相當於 {0,1}。

    Alternation

    |

    subexpression

    ()

    返回參考

    \n:n 是一位數字,代表前面第 n 個 subexpression 符合的子字串。

    BRE 和 ERE

    一開始的正規表示式只支援 [、]、.、^、$、*,稱為 BRE (Basic Regular Expressions)。後來 POSIX 的 BRE 新增字元符來擴充功能,但為了相容,這些字元符前面需要加反斜線跳脫。而 POSIX ERE 則相反。
    ERE:chapter 9 in IEEE 1003.1-2004 Part 1

    BREPOSIX BRE
    ERE
    基本字元符支援支援支援
    跳脫基本字元符反斜線反斜線反斜線
    擴充字元符一般字元反斜線跳脫支援
    跳脫擴充字元符支援反斜線

    PCRE (Perl-compatible Regular Expressions)

    • 凡是標點符號, 加上倒斜線, 一定沒有特殊意義。
    • 常用的 [...] 定義了簡寫:
      • \d:[0-9], "任何一個數字"
      • \D:[^0-9], "任何一個非數字"
      • \w:[a-zA-Z0-9_], "任何一個文數字",不同 locale 有所不同。
      • \W:[^a-zA-Z0-9_], "任何一個非文數字"
      • \s:[ \t\n], "任何一個空白類字元"
      • \S:[^ \t\n], "任何一個非空白類字元"
    • ...

    參考

    1. https://www.cyut.edu.tw/~ckhung/b/re/
    2. http://blog.roodo.com/rocksaying/archives/2670695.html
    3. Shell Script 文章

    hex string to binary


    echo -ne '\x5a'
    echo -n 5a | perl -pe 's/([0-9a-fA-F]{2})/chr hex $1/gie'
    echo 5a | perl -ne 's/([0-9a-fA-F]{2})/print chr hex $1/gie'
    perl -lne 'print pack "H*", $_'
    echo -n 5a | sed 's/\([0-9A-F]\{2\}\)/\\\\\\x\1/gI' | xargs printf
    echo -n 5a | xxd -r -p
    
    
    $ a=5a
    $ printf "\x${a}"
    
    
    
    
    參考來源:
    1. linux shell scripting: hex string to bytes
    2. Shell Script 文章

    sed

    sed (stream editor) 是一個 stream 編輯軟體,直接對檔案一行一行處理。不像一般編輯軟體將檔案載入 buffer 後進行處理。sed 支援正規表示式及流程控制,可視為一種小型指令檔語言。

    指令格式
    • sed [選項] [-e] '編輯命令' [輸入檔]
    • sed [選項] -e '編輯命令1' -e '編輯命令2' [輸入檔]
    • sed [選項] -f 命令檔 [輸入檔]
    編輯命令放在選項 -e 之後,如果只有一個編輯命令可省略 -e。編輯命令也可以放在選項 -f 指定的命令檔裡。其它常用選項:
    • -n:不自動列印。預設除非刪除,不然每行都會印出。加了 -n 選項,
    • -i:直接修改檔案內容
    編輯命令格式:
    • [位址[,位址]]動作

    位址

    用來決定哪些行套用動作,不然每行都套用。有些動作不能有位址;有些可以有一個,指定符合的那些行;有些可以有兩個用「,」隔開,標示行的範圍。位址格式如下:

    • 數字:代表行數
    • 數字~step數字開始每 step 行。在 GNU 數字可以為 0。
    • /正規表示式/\c正規表示式c:比對符合的行,c 是任何字元。
    • $:最後一行
    • 整組位址後加「!」代表否定
    GNU 額外支援的位址:
    • 0,位址位址正規表示式的比對,讓第 1 行可作為結束。
    • 位址,+N位址到其之後 N 行。
    • 位址,~N位址到其之後行號為 N 倍數的行。

    動作

    不能有位址的動作
    • #comment:整行為註解。
    • : label:供動作 bt 跳躍的 label。
    • }:{ } 命令區塊的結束。
    沒位址或單一位址的動作
    • =:印出行號。
    • a[字串]:(append) 後面附加行放字串。新增多行,行尾用 \ 後換行。
    • i[字串]:(insert) 插入新行,類似 a,但是新增在前面。
    • q[結束碼]:
    • Q[結束碼]:
    • r檔名:後面附加檔案裡的內容。
    • R檔名:
    接受範圍的動作:
    • {:命令區塊開始。
    • b[label]:(branch) 跳到 label 或命令檔最後。
    • c[字串]:(change) 整行取代
    • d:(delete) 整行刪除
    • D: 
    • l:類似 p
    • l[width]:
    • n
    • N:合併下一行。例如 sed 'N;s/\n/ /' 合併下行,並把換行取代成空白
    • p:列印,通常搭配選項 -n 使用
    • P
    • s/正規表示式/替代文字/[取代選項]:(substitute) 取代,比對正規表示式符合的話用替代文字取代。
      • 「/」可以用其它符號代替,例如「,」。
      • 替代文字」可以包含的特殊符號
        • &:整個比對符合的部份
        • \1 到 \9:比對的群組
        • \L:改為小寫
        • \l:首字改為小寫
        • \U:改為大寫
        • \u:首字改為大寫
      • 取代選項
        • 未指定只取代一行中第一個符合
        • g:global,一行中全部的符合都取代
        • 數字:一行中第幾個符合才取代
        • w file:寫到檔案
      • 範例
        • s/^/#/:每行開頭插入 #。
    • t[label]:(test) 執行 s 如果成功則跳到 label 或命令檔最後。
    • T[label]:同 t,GNU 擴展。
    • w
    • W
    • y/source/dest/:

    使用保留空間的動作

    保留空間 (hold space) 是一個另外的儲存空間,用來記憶內容。這些動作都接受位址範圍。
    • g:取代為保留空間內容
    • G:後面附加保留空間內容
    • h:覆蓋保留空間
    • H:附加到保留空間
    • x:跟保留空間內容互相交換

    範例:pattern/hold space的處理

    一系列編輯命令用「;」隔開。 

    範例

    • sed 's/\(NAME=\).*/\1abc/g' config.file:將設定檔 config.file 中的 NAME= 設為 abc
    • sed -ne '/MHz/ { /disabled\|passive\|radar/d; s/.*\[//; s/\].*//; p; q }')
    • sed ':a;/0$/{N;s/\n//;ba}':迴圈執行,如果目前行以 '0' 結束,則合併下一行,並移除換行
    • Shell 變數字串處理
    • 目錄檔案字串替換
    • 多行處理:http://www.study-area.org/cyril/scripts/scripts/node57.html
    • 跳躍:http://www.study-area.org/cyril/scripts/scripts/node58.html
    • 多檔處理:http://www.study-area.org/cyril/scripts/scripts/node59.html

    參考來源

    延伸閱讀:
    http://www.tldp.org/LDP/abs/html/

    參考:Shell Script 文章

    awk

    以欄位為處理單位
    指令格式:awk '條件類型1{動作1} 條件類型2{動作2} ...' filename
    動作有 print 等
    變數
    • $0 代表「整列資料」,$1 代表其中第一欄,$2 代表第二欄,...
    • NF 代表目前行有多少欄位
    • NR 代表目前是第幾行
    • FS 代表目前欄位的分隔字元,預設是空白或 Tab
    一篇 awk 文章筆記
    取檔案大小
    ls -l $filename | awk '{print $5}'
    印出第 1 行及最後一行
    awk 'NR==1; END{print}' testing.txt
    應用:
    • OpenWrt 的 ipcalc.sh:用 awk 作 IP 位址相關計算,包括 broadcast 位址、network 位址、prefix、起始位址、及結束位址。

    參考:
    1. http://dywang.csie.cyut.edu.tw/dywang/linuxProgram/node37.html
    Shell Script 文章

    bash ARITHMETIC EVALUATION

    bash 的算術運算用在內建指令 letdeclare、複合指令 (( ))、和算術擴展,使用固定寬度的整數,不檢查溢位,除以 0 會補抓為錯誤。

    下列是運算子列表,以相同優先序為群組,越往下優先權越低 (優先序 和 C 語言一樣?)。括號裡的算式會先算。
    id++ id--post-increment and post-decrement
    ++id --idpre-increment and pre-decrement
    - +unary minus and plus
    ! ~logical and bitwise negation
    **exponentiation
    * / %multiplication, division, remainder
    + -addition, subtraction
    << >>left and right bitwise shifts
    <= >= < >comparison
    == !=equality and inequality
    &bitwise AND
    ^bitwise exclusive OR
    |bitwise OR
    &&logical AND
    ||logical OR
    expr?expr:exprconditional operator
    = *= /= %= += -= <<= >>= &= ^= |=assignment
    expr1 , expr2comma

    參考:
    1. osl3 Shell 設計入門: 10.算術運算 (另外還有 expr、$[]、let 三種,其中 expr 可攜性較好)
    2. Shell Script 文章
    3. bash man-page ARITHMETIC EVALUATION 

    SIP header Via

    所有 SIP 訊息 都要有 Via,縮寫 v。一開始的 UAC 和後續途經的每個 proxy 都會疊加一個 Via 放傳送的位址,依序作為回應的路徑。 格式 sent-protocol sent-by [ ;branch= branch ][ ; 參數 ...] s...