ssh, scp, sftp, ssh-agent

最後更新: 2018-07-01

目錄

 


Detect remote 's sshd is running

 

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

連線失敗時

echo $?       # 255

 


run cmd on remote by ssh

 

# 用 -- 分隔要行的 command

i.e.

ssh <IP>  -- uname -a

# pipe in remote

# Local

ssh 192.168.88.59 -- df > test.txt

# Remote

ssh 192.168.88.59 -- '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 123.123.123.123

 


ssh client hotkey

 

~?      # Help

~.       # 中斷當前 ssh session

 


Client Configure File

 

~/.ssh/config

 * 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.

Doc:

man 5 ssh_config

Example:

Host server1
  HostName example.dyndns.org
  Port 2222
  ServerAliveInterval 5
  ConnectTimeout 1200
  User admin
  IdentitiesOnly yes
  IdentityFile /root/.ssh/nginx.key

IdentityFile

IdentitiesOnly

# 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

Variable

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

ServerAliveInterval

ssh(1) will send a message through the encrypted channel to request a response from the server.

The default is 0, indicating that these messages will not be sent to the  server.

ConnectTimeout

This value is used only when the target is down or really unreachable

IdentitiesOnly

only use the authentication identity and certificate files explicitly configured in the ssh_config

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 *.co.uk
  # up to the next Host keyword, 所以 TAB 不是必須
  ...
Host 192.168.0.?
  ...
Host *                  # Default
  ...

Usage:

ssh server1

Other

SetEnv                  # Directly specify one or more environment variables

RemoteCommand   # Specifies a command to execute on the remote machine after successfully connecting to the  server.

PasswordAuthentication  # Default: yes

PreferredAuthentications # Default: gssapi-with-mic,hostbased,publickey,keyboard-interactive,password

LocalForward          # local tcp port -> remote tcp port ( [bind_address:]port host:hostport )

RemoteForward      # allows a remote client to connect to arbitrary destinations from the local machine.

 

Compression          # Efault: no

 


Environment Variables

 

帶 Env 到 remote 方法

  • SendEnv
  • SetEnv

Server

Server 指定可以帶什麼 Env 上來

/etc/ssh/sshd_config:

# 可以多行
# 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
  SetEnv [email protected]
  # 方法1
  SendEnv GIT_AUTHOR_NAME GIT_AUTHOR_EMAIL

[2] "-o"

export FOO=bar

ssh -o SendEnv=FOO remote.host

Note

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

 


ssh-agent

 

用圖:

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.)

Opts:

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

它會建立一個 UNIX-domain sockets:

$TMPDIR/ssh-XXXXXXXXXX/agent.<ppid>

start agent

ssh-agent

# output

SSH_AUTH_SOCK=/tmp/ssh-k9vI4ysMD75A/agent.14362; export SSH_AUTH_SOCK;
SSH_AGENT_PID=14363; export SSH_AGENT_PID;
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_AGENT_PID=14363; export SSH_AGENT_PID;

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

ssh-add

# 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

 


sshpass

 

Sshpass runs ssh in a dedicated tty, fooling it into thinking it is getting the password from an interactive user.

Options

  • -p password   # 最唔安全 (All system users can see the password)
  • -f filename     # 最好
  • -e                 # The password is taken from the environment variable "SSHPASS"
  • -P                 # Set  the  password prompt. Default: "assword:"

 


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

Usage:

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

 


複製檔案(scp)

 

URI in the form:  scp://[user@]host[:port][/path]

Options:

  • -P port
  • -i identity_file
    --------
  • -r                      Recursively copy entire directories
    --------
  • -C                      Compression enable
  • -l limit                specified in Kbit/s
    --------
  • -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

Example

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

scp /etc/apt/sources.list [email protected]:

#2 直接複製到目的地

scp /etc/apt/sources.list [email protected]:/etc/apt/

#3 Limit download speed

# 限速 4 Mbps

scp -r -l 40000 server:/path/to/folder ./

# 這裡的 unit 係 MiBps
filename                 1% 6074MB   4.9MB/s 22:55:39 ET

進階

-3      Copies between two remote hosts are transferred through the local host.

 

 


sftp

 

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.

Usage

sftp [user@]host[:path] <<< 'put filename'

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.

#!/bin/bash

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

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

INTERACTIVE COMMANDS

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

ln

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

df

-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.

mput, mget

 * mget works with a glob for the "source file" portion of the arguments

sftp> mget abc.PDF def.PDF ghi.PDF

Fetching /abc.PDF to def.PDF

sftp> mget *.pdf

Local

  • lls [ls-options [path]]            Display local directory listing
  • lmkdir path                        Create local directory

Example

#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 ./

#3 upload folder

sftp> put -r folder/


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

 

Client

# list of available ciphers

ssh -Q cipher

3des-cbc
blowfish-cbc
cast128-cbc
arcfour
...

# Selects the cipher specification for encrypting the session

-c  blowfish-cbc

# Server 不支援要求的 cipher

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

Server

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

Other

ciphers

 


Close Session

 

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

 

 

Creative Commons license icon Creative Commons license icon