ssh, scp, sftp, ssh-agent

最後更新: 2018-07-01



Detect remote 's sshd is running


ssh -o StrictHostKeyChecking=no -o PasswordAuthentication=no -o ConnectTimeout=5 -- uptime


echo $?       # 255


run cmd on remote by ssh


# 用 -- 分隔要行的 command


ssh <IP>  -- uname -a

# pipe in remote

# Local

ssh -- df > test.txt

# Remote

ssh -- 'df > test.txt'


ssh 常用的 opts


# sudo 時會用到

-t        Force pseudo-tty allocation

# compression ( will only slow down things on fast networks )

-C      Requests compression(gzip) of all data (stdin, stdout, stderr, forwarded X11 and TCP connections)

# Default: ~/.ssh/id_rsa

-i identity_file

# Default 是當前 username

-l login_name

# 連去舊的 cisco router 要用到.

-c cipher_spec                          # 連去舊的 ssh server 時用到 ( 比如連去 Cisoc asa5500 )

# 設定加密的方式

ssh -oKexAlgorithms=+diffie-hellman-group1-sha1


ssh client hotkey


~?      # Help

~.       # 中斷當前 ssh session


Client Configure File:



 * not accessible by others

ssh obtains configuration data from the following

1. command-line options

2. user’s configuration file (~/.ssh/config)

3. system-wide configuration file (/etc/ssh/ssh_config)

 * For each parameter, the first obtained value will be used.


man 5 ssh_config


Host server1
  Port 2222
  ConnectTimeout 1200
  User admin
  IdentitiesOnly yes
  IdentityFile /root/.ssh/nginx.key



# Only use the authentication identity files; default: no

# This option is intended for situations where ssh-agent offers many different identities

Key Files Location:

version 1 default

  • ~/.ssh/identity

version 2 default

  • ~/.ssh/id_dsa
  • ~/.ssh/id_rsa

version 2 ECDSA:

  • ~/.ssh/id_ecdsa

multiple identity files

It is possible to have multiple identity files specified in configuration files

 * all these identities will be tried in sequence. (multiple identity files => tried in sequence)

# 同時設定幾個 IdentityFile
IdentityFile ~/.ssh/k1.key
IdentityFile ~/.ssh/k2.key
IdentityFile ~/.ssh/k3.key


  • %d’ (local user's home directory)
  • ‘%u’ (local user name)
  • ‘%l’ (local host name)
  • ‘%h’ (remote host name)
  • ‘%r’ (remote user name)

Host Patterns:

Since the first obtained value for each parameter is used,

more host-specific declarations should be given near the beginning of the file,

and general defaults at the end.

Host *
  # up to the next Host keyword, 所以 TAB 不是必須
Host 192.168.0.?
Host *                  # Default


ssh server1



Environment Variables


帶 Env 到 remote 方法

  • SendEnv
  • SetEnv


Server 指定可以帶什麼 Env 上來


# 可以多行
# Variables are specified by name, which may contain wildcard characters.
# Multiple environment variables may be separated by whitespace or spread across multiple SendEnv directives.
AcceptEnv MyEnv
AcceptEnv LANG LC_* FOO

Client Setting

[1] ~/.ssh/config

Host *
  # 方法1
  # It is possible to clear previously set SendEnv variable names by prefixing patterns with -. 
  SetEnv GIT_AUTHOR_NAME=datahunter
  # 方法1

[2] "-o"

export FOO=bar

ssh -o SendEnv=FOO


The TERM environment variable is always sent whenever a pseudo-terminal is requested as it is required by the protocol.





hold private keys used for public key authentication


all other windows or programs are started as clients to the ssh-agent program

ssh(1) looks at these variables (SSH_AUTH_SOCK) and uses them to establish a connection to the agent

operations that require a private key will be performed by the agent, and the result will be returned to the requester

(This way, private keys are not exposed to clients using the agent.)


  • -k              Kill the current agent
  • -t life         lifetime of identities added to the agent. Default: forever.

它會建立一個 UNIX-domain sockets:


start agent


# output

SSH_AUTH_SOCK=/tmp/ssh-k9vI4ysMD75A/agent.14362; export SSH_AUTH_SOCK;
echo Agent pid 14363;

方法1: If a commandline is given, this is executed as a subprocess of the agent.

ssh-agent bash

* 一定要用 ssh-agent 去獨立開個 shell 才可以直接使用 ssh-add

# 否則行 ssh-add 會出 "Could not open a connection to your authentication agent."

*  The agent exits automatically when the command given on the command line terminates.

方法2: 人手執行 ssh-agent output 的 cmd

SSH_AUTH_SOCK=/tmp/ssh-k9vI4ysMD75A/agent.14362; export SSH_AUTH_SOCK;

SSH_AUTH_SOCK: This method is easily abused by root or another instance of the same user.


# without arguments, ssh-add(1) adds the files

  • ~/.ssh/id_rsa
  • ~/.ssh/id_dsa
  • ~/.ssh/id_ecdsa

# displays the identities currently held by the agent

ssh-add -l

2048 3d:04:35:41:3f:17:b5:77:f1:b2:9f:fb:3d:22:a8:38 /root/.ssh/id_rsa (RSA)

# Lists public key parameters

ssh-add -L

ssh-rsa AAA ...
... XYSpT /root/.ssh/id_rsa

Useful Otps

-D      Deletes all identities from the agent

All identities removed.

-d      Delete identity

-X      Unlock the agent

-x      Lock the agent with a password


key fingerprint


Key type:

  • ECDSA key fingerprint
  • RSA key fingerprint

Elliptic Curve Digital Signature Algorithm

 * ECDSA is the new default

 * As of April 2013, the Windows SSH client PuTTY does not support ECDSA


ssh  -oHostKeyAlgorithms='ssh-rsa'   <IP>





  • -P port
  • -r                      Recursively copy entire directories
  • -C                      Compression enable
  • -l limit                specified in Kbit/s
  • -i identity_file
  • -B                      batch mode (prevents asking for passwords or passphrases)
  • -q                      Quiet mode (disables the progress meter)
  • -v                      Verbose mode
  • -p                      only preserves timestamps and permissions, not the file ownership


#1 將檔案(/etc/apt/sources.list) upload 到 的帳戶root的家目錄裡複製到

scp /etc/apt/sources.list root@

#2 直接複製到目的地

scp /etc/apt/sources.list root@




sftp - all operations over an encrypted ssh transport.


  • public key authentication
  • compression

sftp 它是與 scp 一齊來的, 在 Centos 上同在 openssh-clients Package 內

它們有的 Opts 亦差不多.

常用 Opts:

-P port

-r                       # Recursively copy entire directories

-C                      # Enables compression

-B buffer_size     # Default is 32768 bytes. Larger buffers require fewer round trips

-R num_requests #  The default is 64 outstanding requests. how many requests may be outstanding at any one time.


sftp -b batchfile [user@]host          # necessary to configure non-interactive authentication

sftp [user@]host[:file ...]

sftp [user@]host[:dir[/]]

Batch mode

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.


# 方法 1
export SSHPASS=your-password-here
sshpass -e sftp sftp-user@remote-host << !
   put your-log-file.log

# 方法 2
export SSHPASS=your-password-here
sshpass -e sftp -oBatchMode=no -b - sftp-user@remote-host << !
   put your-log-file.log


  • ls, df, bye, exit,
  • cd, mkdir, rmdir
  • get, put, reget, reput, rename, ln, rm
  • chgrp, chmod, chown
  • version, progress


If the -s flag is specified the created link is a symbolic link, otherwise it is a hard link.


-i flag:  requests display of inode information

-h flag: human-readable

reget, reput

Resume. Equivalent to "-a" flag set

put, get

local-path may contain glob

-a:  attempt to resume partial transfers of existing files

If the local file contents differ from the remote local copy then the resultant file is likely to be corrupt.

-P or -p flag is specified, then full file permissions and access times are copied too.

-r flag is specified then directories will be copied recursively.


#1 sftp shell

# check version

sftp> version

SFTP protocol version 3

# show hide file

sftp> ls -a

#2 在 ./ 下會有 public_html folder

sftp -r user@remote:/public_html ./


Login with password instead of key


[方法 1]

ssh -i /dev/null host

[方法 2]

ssh -o PubkeyAuthentication=no host


clone disk by ssh


# Source

dd bs=16M if=/dev/sda | pv | ssh -C root@dest_ip "dd bs=16M of=/dev/sda"

-C option to the SSH command to enable gzip compression


dd bs=16M if=/root/tmp/send/vda.qcow2 | ssh -C root@localhost "dd bs=16M of=/root/tmp/receive/vda.qcow2"

2023161856 bytes (2.0 GB, 1.9 GiB) copied, 89.4027 s, 22.6 MB/s

* 其中一個 CPU core 在 90%

沒有加 -C

2023161856 bytes (2.0 GB, 1.9 GiB) copied, 32.7042 s, 61.9 MB/s

* CPU 用得很小(30%)


Change Cipher



# list of available ciphers

ssh -Q cipher


# Selects the cipher specification for encrypting the session

-c  blowfish-cbc

# Server 不支援要求的 cipher

Unable to negotiate with port 22: no matching cipher found. Their offer: ...


Multiple ciphers must be comma-separated. If the specified value begins with a ‘+’ character,

then the specified ciphers will be appended to the default set instead of replacing them.

Ciphers         +arcfour,blowfish-cbc

Copy file test

# blowfish-cbc (cpu 60%)

2023161856 bytes (2.0 GB, 1.9 GiB) copied, 34.4005 s, 58.8 MB/s

# arcfour (cpu 20%)

2023161856 bytes (2.0 GB, 1.9 GiB) copied, 35.6266 s, 56.8 MB/s




Close Session


You can type Enter "~ ." to close the connection.