Total Pageviews

Friday, 3 February 2012

ssh-tips-and-tricks

SSH is one of the most widely used protocols for connecting to remote shells. While there are numerous SSH clients the most-used still remains OpenSSH's ssh. OpenSSH has been the default ssh client for every major Linux operation, and is trusted by cloud computing providers such as Amazon's EC2 services and web hosting companies like MediaTemple. There is a plethora of tips and tricks that can be used to make your experience even better than it already is. Read on to discover some of the best tweaks to your favorite SSH client.

Adding A Keep-Alive

A keep-alive is a small piece of data transmitted between a client and a server to ensure that the connection is still open or to keep the connection open. Many protocols implement this as a way of cleaning up dead connections to the server. If a client does not respond, the connection is closed.
SSH does not enable this by default. There are pros and cons to this. A major pro is that under a lot of conditions if you disconnect from the Internet, your connection will be usable when you reconnect. For those who drop out of WiFi a lot, this is a major plus when you discover you don't need to login again.
For those who get the following message from their SSH client when they stop typing for a few minutes it's not as convenient:
symkat@symkat:~$ Read from remote host symkat.com: Connection reset by peer
Connection to symkat.com closed.
This happens because your router or firewall is trying to clean up dead connections. It's seeing that no data has been transmitted in N seconds and falsely assumes that the connection is no longer in use.
To rectify this you can add a Keep-Alive. This will ensure that your connection stays open to the server and the firewall doesn't close it.
To make all connections from your shell send a keepalive add the following to your ~/.ssh/config file:
KeepAlive yes
ServerAliveInterval 60
The con is that if your connection drops and a KeepAlive packet is sent SSH will disconnect you. If that becomes a problem, you can always actually fix the Internet connection.

Multiplexing Your Connection

Do you make a lot of connections to the same servers? You may not have noticed how slow an initial connection to a shell is. If you multiplex your connection you will definitely notice it though. Let's test the difference between a multiplexed connection using SSH keys and a non-multiplexed connection using SSH keys:
# Without multiplexing enabled:
$ time ssh symkat@symkat.com uptime
 20:47:42 up 16 days,  1:13,  3 users,  load average: 0.00, 0.01, 0.00

real    0m1.215s
user    0m0.031s
sys 0m0.008s

# With multiplexing enabled:
$ time ssh symkat@symkat.com uptime
 20:48:43 up 16 days,  1:14,  4 users,  load average: 0.00, 0.00, 0.00

real    0m0.174s
user    0m0.003s
sys 0m0.004s
We can see that multiplexing the connection is much faster, in this instance on an order of 7 times faster than not multiplexing the connection. Multiplexing allows us to have a “control” connection, which is your initial connection to a server, this is then turned into a UNIX socket file on your computer. All subsequent connections will use that socket to connect to the remote host. This allows us to save time by not requiring all the initial encryption, key exchanges, and negotiations for subsequent connections to the server.
To enable multiplexing do the following:
In a shell:
$ mkdir -p ~/.ssh/connections
$ chmod 700 ~/.ssh/connections
Add this to your ~/.ssh/config file:
Host *
ControlMaster auto
ControlPath ~/.ssh/connections/%r_%h_%p
A negative to this is that some uses of ssh may fail to work with your multiplexed connection. Most notably commands which use tunneling like git, svn or rsync, or forwarding a port. For these you can add the option -oControlMaster=no. To prevent a specific host from using a multiplexed connection add the following to your ~/.ssh/config file:
Host YOUR_SERVER_OR_IP
MasterControl no
There are security precautions that one should take with this approach. Let's take a look at what actually happens when we connect a second connection:
$ ssh -v -i /dev/null symkat@symkat.com
OpenSSH_4.7p1, OpenSSL 0.9.7l 28 Sep 2006
debug1: Reading configuration data /Users/symkat/.ssh/config
debug1: Reading configuration data /etc/ssh_config
debug1: Applying options for *
debug1: auto-mux: Trying existing master
Last login:
symkat@symkat:~$ exit
As we see no actual authentication took place. This poses a significant security risk if running it from a host that is not trusted, as a user who can read and write to the socket can easily make the connection without having to supply a password. Take the same care to secure the sockets as you take in protecting a private key.

Using SSH As A Proxy

Even Starbucks now has free WiFi in its stores. It seems the world has caught on to giving free Internet at most retail locations. The downside is that more teenagers with "Got Root?" stickers are camping out at these locations running the latest version of wireshark.
SSH's encryption can stand up to most any hostile network, but what about web traffic?
Most web browsers, and certainly all the popular ones, support using a proxy to tunnel your traffic. SSH can provide a SOCKS proxy on localhost that tunnels to your remote server with the -D option. You get all the encryption of SSH for your web traffic, and can rest assured no one will be capturing your login credentials to all those non-ssl websites you're using.
$ ssh -D1080 -oControlMaster=no symkat@symkat.com
symkat@symkat:~$
Now there is a proxy running on 127.0.0.1:1080 that can be used in a web browser or email client. Any application that supports SOCKS 4 or 5 proxies can use 127.0.0.1:1080 to tunnel its traffic.
$ nc -vvv 127.0.0.1 1080
Connection to 127.0.0.1 1080 port [tcp/socks] succeeded!

Using One-Off Commands

Often times you may want only a single piece of information from a remote host. "Is the file system full?" "What's the uptime on the server?" "Who is logged in?"
Normally you would need to login, type the command, see the output and then type exit (or Control-D for those in the know.) There is a better way: combine the ssh with the command you want to execute and get your result:
 $ ssh symkat@symkat.com uptime
 18:41:16 up 15 days, 23:07,  0 users,  load average: 0.00, 0.00, 0.00
This executed the ssh symkat.com, logged in as symkat, and ran the command uptime on symkat. If you're not using SSH keys then you'll be presented with a password prompt before the command is executed.
$ ssh symkat@symkat.com ps aux | echo $HOSTNAME
symkats-macbook-pro.local
This executed the command ps aux on symkat.com, sent the output to STDOUT, a pipe on my local laptop picked it up to execute echo $HOSTNAME locally. Although in most situations using auxiliary data processing like grep or awk will work flawlessly, there are many situations where you need your pipes and file IO redirects to work on the remote system instead of the local system. In that case you would want to wrap the command in single quotes:
$ ssh symkat@symkat.com 'ps aux | echo $HOSTNAME'
symkat.com
As a basic rule if you're using > >> < - or | you're going to want to wrap in single quotes.
It is also worth noting that in using this method of executing a command some programs will not work. Notably anything that requires a terminal, such as screen, irssi, less, or a plethora of other interactive or curses based applications. To force a terminal to be allocated you can use the -t option:
$ ssh symkat@symkat.com screen -r
Must be connected to a terminal.
$ ssh –t symkat@symkat.com screen -r
$ This worked!

Making SSH A Pipe

Pipes are useful. The concept is simple: take the output from one program's STDOUT and feed it to another program's STDIN. OpenSSH can be used as a pipe into a remote system. Let's say that we would like to transfer a directory structure from one machine to another. The directory structure has a lot of files and sub directories.
We could make a tarball of the directory on our own server and scp it over. If the file system this directory is on lacks the space though we may be better off piping the tarballed content to the remote system.
$ ls content/
1   18  27  36  45  54  63  72  81  90
10  19  28  37  46  55  64  73  82  91
100 2   29  38  47  56  65  74  83  92
11  20  3   39  48  57  66  75  84  93
12  21  30  4   49  58  67  76  85  94
13  22  31  40  5   59  68  77  86  95
14  23  32  41  50  6   69  78  87  96
15  24  33  42  51  60  7   79  88  97
16  25  34  43  52  61  70  8   89  98
17  26  35  44  53  62  71  80  9   99

$ tar -cz content | ssh symkat@symkat.com 'tar -xz'
$ ssh symcat@symkat
symkat@lazygeek:~$ ls content/
1    14  2   25  30  36  41  47  52  58  63  69  74  8   85  90  96
10   15  20  26  31  37  42  48  53  59  64  7   75  80  86  91  97
100  16  21  27  32  38  43  49  54  6   65  70  76  81  87  92  98
11   17  22  28  33  39  44  5   55  60  66  71  77  82  88  93  99
12   18  23  29  34  4   45  50  56  61  67  72  78  83  89  94
13   19  24  3   35  40  46  51  57  62  68  73  79  84  9   95
What we did in this example was to create a new archive (-c) and to compress the archive with gzip (-z). Because we did not use -f to tell it to output to a file, the compressed archive was send to STDOUT. We then piped STDOUT with | to ssh. We used a one-off command in ssh to invoke tar with the extract (-x) and gzip compressed (-z) arguments. This read the compressed archive from the originating server and unpacked it into our server. We then logged in to see the listing of files.
Additionally, we can pipe in the other direction as well. Take for example a situation where you with to make a copy of a remote database, into a local database:
symkat@chard:~$ echo "create database backup" | mysql -uroot -ppassword
symkat@chard:~$ ssh symkat@symkat.com 'mysqldump -udbuser -ppassword symkat' | \
> mysql -uroot -ppassword backup
symkat@chard:~$ echo "use backup;select count(*) from wp_links;" | mysql -uroot -ppassword
count(*)
12
symkat@chard:~$
What we did here is to create the database backup on our local machine. Once we had the database created we used a one-off command to get a dump of the database from symkat.com. The SQL Dump came through STDOUT and was piped to another command. We used mysql to access the database, and read STDIN (which is where the data now is after piping it) to create the database on our local machine. We then ran a MySQL command to ensure that there is data in the backup table. As we can see, SSH can provide a true pipe in either direction.

Using a Non Standard Port

Many people run SSH on an alternate port for one reason or another. For instance, if outgoing port 22 is blocked at your college or place of employment you may have ssh listen on port 443.
Instead of saying ssh -p443 you@yourserver.com you can add a configuration option to your ~/.ssh/config file that is specific to yourserver.com:
Host yourserver.com
Port 443
You can extrapolate from this information further that you can make ssh configurations specific to a host. There is little reason to use all those -oOptions when you have a well-written ~/.ssh/config file.
What is your favorite SSH Tip or Trick?

from http://www.symkat.com/ssh-tips-and-tricks-you-need 
-------------------------------------------------

Call-home SSH scripts

Sometimes I need to set up quickly some presence in a customer network: to be able to access it remotely, or to run some network management scripts, and so on. Most of such networks are behind NAT or at least a firewall, and incoming connections from outside aren’t always easy.
But outgoing connections from a customer LAN are mostly not a problem at all. So, I bring my own small netbook and place it in the customer LAN. This netbook automatically makes an outgoing SSH connection to my central server (a VPS) and pulls an SSH tunnel so that I can access the netbook from outside.
This is a kind of a backdoor, and it makes sense to make your customer completely aware of what you’re doing.
For such purposes, I have a couple of cheapest 10″ netbooks. I’m using Acer AspireOne and some older eMachines netbooks because they were sold cheaply. Most other netbooks would fit too, but one should be careful about Linux compatibility (especially the video drivers might be a problem). They come with 1GB RAM and 160 or 250 GB hard drives. It’s quite trivial to upgrade them to 2GB RAM, although it’s not really necessary. You must only be careful about buying a new SODIMM with exactly the same clocking as the original one.
The netbooks run standard Ubuntu Linux, with SSH daemon enabled. If the user home directory is encrypted, you won’t be able to login with your public SSH keys, so better not encrypt it.

1. On my central VPS, in /etc/ssh/sshd_config I enabled the keepalives. This turns down a connection which is stalled because of network problems. As we’re setting up SSH tunnels with port mapping, the new tunnel will not be set up until the TCP socket is free. With keepalives, SSH daemon will automatically break the connection and free up the socket. Also I enable remote clients to open a listening socket on my central VPS:
ClientAliveInterval 5
ClientAliveCountMax 3
GatewayPorts yes
2. Create a user on the central VPS. “micro02″ is the host name for my micro-agent netbook. The user has /bin/false as a shell, because we don’t want it to do anything on the VPS:
$ grep micro02 /etc/passwd
micro02:x:1002:1003::/home/micro02:/bin/false
3. On micro02, generate the SSH keys for root, and add the public key to the autorized keys for the user “micro02″ on the VPS.
4. Create a DNS entry for callhome purpose. If your central server moves, you won’t have to reconfigure all your agents.
5. Here’s the script /root/ssh_tunnel.sh on the netbook. The infinite loop sets up an SSH connection with port forwarding. There’s a sleep command on purpose: if there’s no routing to the destination, SSH would exit immediately, and we don’t want the loop to hog all our CPU power. Server key checking is disabled, as the server may eventually change, and we don’t want to lose control of our agent.
#!/bin/sh
while true; do
  ssh -NC -o ServerAliveInterval=5 \
    -o UserKnownHostsFile=/dev/null \
    -o StrictHostKeyChecking=no \
    -R '*:2022:127.0.0.1:22' micro02@callhome.mydomain.net
  sleep 5
done
6. Here’s the startup script /etc/init.d/callhome_ssh_tunnel which brings up the tunnel at the computer boot:
#! /bin/sh
#
### BEGIN INIT INFO
# Provides:          k-open_ssh_tunnel
# Required-Start:    $local_fs $remote_fs $network $syslog
# Required-Stop:     $local_fs $remote_fs $network $syslog
# Default-Start:     2 3 4 5
# Default-Stop:      
# Short-Description: SSH tunnel to support.mydomain.com
### END INIT INFO

PATH=/sbin:/bin:/usr/sbin:/usr/bin
DAEMON="/bin/sh /root/ssh_tunnel.sh"
DESC="SSH tunnel to callhome.mydomain.net"
VERBOSE=yes

# Load the VERBOSE setting and other rcS variables
. /lib/init/vars.sh

# Define LSB log_* functions.
. /lib/lsb/init-functions

OPTIONS=""
#
# Function that starts the daemon/service
#
do_start()
{
        start-stop-daemon --start --background \
                --name ssh_tunnel.sh --exec $DAEMON \
                || return 1
}

case "$1" in
  start)
        [ "$VERBOSE" != no ] && log_daemon_msg "Starting $DESC" "$NAME"
        do_start
        case "$?" in
                0|1) [ "$VERBOSE" != no ] && log_end_msg 0 ;;
                2) [ "$VERBOSE" != no ] && log_end_msg 1 ;;
        esac
        ;;
  stop)
        echo not supported
        ;;
esac

exit 0
7. Test the connection script: SSH to port 2022 on your VPS should bring you to the netbook command prompt. Then enable the startup script:
update-rc.d callhome_ssh_tunnel enable
8. In Power Settings, set “do nothing” when the lid is closed.
9. Reboot the netbook and test
10. Disconnect a running netbook from the network, then connect again, and test.
11. Make a backup copy of your scripts. The best is to use Git with a private repository.

from http://txlab.wordpress.com/2012/01/25/call-home-ssh-scripts/
----------------------------------------------------
 ssh tricks - the usual and beyond

    SSH is an amazing beast. I nearly use it everyday and I'm amazed every time I learn something new. The following is a list of my tricks in the bag. It starts with the usual tricks that you find all over the place, but I hope there will be some new tricks for you too.

What's your best trick? Share it in the comments with the world. Nobody can know enough of ssh!
The basics:
Password-less login:

This is usually the first thing start doing when want automation with ssh

#Create a new keypair
$ ssh-keygen -t dsa
Generating public/private dsa key pair.
Enter file in which to save the key (/Users/patrick/.ssh/id_dsa):
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /Users/patrick/.ssh/id_dsa.
Your public key has been saved in /Users/patrick/.ssh/id_dsa.pub.
The key fingerprint is:
87:66:b7:a0:f6:0e:6a:71:2c:5d:ee:5f:17:2a:b7:2f patrick@localhost
The key's randomart image is:
+--[ DSA 1024]----+
|                 |
|                 |
|                 |
|        ..       |
|     o oS o   .  |
|    o ++.+ . . . |
|     ++.  o + .  |
|    .o o.  +Eo   |
|   ..  .o.. .o.  |
+-----------------+
$ cat ~/.ssh/id_dsa.pub | ssh user@remotehost "cat - >> ~/.ssh/authorized_keys"
$ ssh user@remotehost

Install your keys on a remote server:

$ ssh-copy-id -i ~/.ssh/id_dsa.pub user@remotehost
#Alternative
$ cat ~/.ssh/id_dsa.pub | ssh user@remotehost "cat - >> ~/.ssh/authorized_keys"

Passphrase automation:

If you have protected your keys with a passphrase (which you should), then it is annoying to re-enter that all the time. You can avoid that by running your environment inside an ssh-agent and using ssh-add to enter the passphrase once.

$ ssh-add ~/.ssh/id_dsa
Need passphrase for /home/mah/.ssh/id_dsa (you@example.com).
Enter passphrase:
$

Pseudo Terminal :

some commands like sudo require a pseudo terminal to be activated

$ ssh -t patrick@remotehost sudo cat /etc/passwd

Avoid lastlog:

Log in without appearing in lastlog/w and who output.

$ ssh -T user@hostname.com

Piping

Example of using piping to backup over the network

$ ufsdump 0uf - /dev/md/rdsk/d33 | ssh r280n "dd obs=32k ibs=32k of=/dev/rmt/0n"

Rsync over ssh

$ rsync -avz -e "ssh -i /home/thisuser/cron/thishost-rsync-key" remoteuser@remotehost:/remote/dir /this/dir/

Tunnels and firewall-piercings:
X-forwarding:

$ ssh -X patrick@remotehost
Warning: untrusted X11 forwarding setup failed: xauth key data not generated
Warning: No xauth data; using fake authentication data for X11 forwarding.
Last login: Fri Aug 27 20:27:40 2010

Port forwarding:

Set up a localforward from the remote machine port 25 to a local port 9025

$ ssh -L 9025:localhost:25 patrick@remotehost

No command:

Sometimes you just want to setup a forward with having a shell

$ ssh -N -L 9025:localhost:25 patrick@remotehost

KeepAlive:

Getting tired of those timeouts by the firewall? Have ssh send a keepalive/

Put the following options in your $HOME/.ssh/ssh_config

    KeepAlive yes
    ServerAliveInterval 60

Socks Daemon for proxying: (-D)

Sometimes it's interesting to start a socks daemon. You can configure this in your browser to surf as it seems to come from the remote machine.

$ ssh -D 9999 patrick@remotehost

Tunneling over an http proxy:

Corporate firewalls often only allow http to go outside. See corkscrew

ProxyCommand /usr/bin/corkscrew proxy-ip 8080 %h %p ~/.ssh/myauth

Chaining ssh hopping:

Host pc1.example.org pc2.example.org
ForwardAgent yes
ProxyCommand ssh -qax bastion.example.org /usr/bin/nc -w 120 %h %p

Netcat mode:

Starting from openssh 5.4: we can have ssh act as netcat. (-W) This connects stdio on the client to a single port forward on the server. This allows, for example, using ssh as a ProxyCommand to route connections via intermediate servers.”

$ ssh -p 443 -W remotehost2:23 patrick@remotehost
Trying remotehost2...
Connected to remotehost2.
Escape character is '^]'.

User Name : ^]
telnet> close
$


Mounting over ssh:

Sometimes it's nice to mount a remote directory over ssh. Fuse and sshfs are your friend

$ sshfs remote-user@remote.server:/remote/directory /mnt/remote-fs/

http://fuse.sourceforge.net/sshfs.html
VPN Tunneling:

Did you know that ssh can do layer 2 and 3 VPN tunneling?

Check out ssh -w. Example from manpage:

$ ssh -f -w 0:1 192.168.1.15 true
$ ifconfig tun0 10.0.50.1 10.0.99.1 netmask 255.255.255.252

SSH http multiplexer:

sslh lets one accept both HTTPS and SSH connections on the same port. It makes it possible to connect to an SSH server on port 443 (e.g. from inside a corporate firewall) while still serving HTTPS on that port. http://www.rutschle.net/tech/sslh.shtml
Speed
Compression

If you are working on a slow link, compression (-C) and using a simple cipher (-c blowfish) saves you speed

$ ssh -C -c blowfish patrick@remotehost

Multiplexing - ControlMaster:

Another great way to speed up ssh is to re-use the same connection when you connect multiple times to the same host

$ mkdir –p ~/.ssh/connections
$ chmod 700 ~/.ssh/connections

Add this to your ~/.ssh/config file:
Host *
ControlMaster auto
ControlPath ~/.ssh/connections/%r_%h_%p

Managing keys
Ignore Hostkeys:

When you're re-installing a machine over and over again, you often want to get rid of the hostfile key verification. This is what you need:

$ ssh user@host -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null

Check if hostkey exists:

k$ ssh-keygen -F 192.168.2.152
# Host 192.168.2.152 found: line 31 type RSA
192.168.2.152 ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEAwHH15HpeJo21wyqpe2iFM8/0CtoYnE9DDXfCewws7iMhM+vgp7pjnaC83IgAt7G/x/VDHcbnyuI4odrGSEAE5wm7LNuT6uSfQMbXCayE+uoOIrAVhf41ZnAFQrs/+Mutk5LFEjPPNhuriq5ltBT4UwMlYQMa5z/SzmxV0ZAGXks5GMDz0o89yUwRarRfsGudASEtzUxgnxnOo5STBMZOdQ0GNEVdfJDgfJDAOi34T1FidpCqAtm8akYuB+Qsj3/hDQmIT+GsKYaGNZvz8ZNnPBAc9kWlS6VqXXNreyEeu7AmHDWXjMP3NW1tsibmZ8zeOSZdmEVEiuaYCIvERDq3MQ==

Remove a hostkey:

$ ssh-keygen -R 192.168.2.152
/Users/patrick/.ssh/known_hosts updated.
Original contents retained as /Users/patrick/.ssh/known_hosts.old

Get hostkey of remote server:

$ ssh-keyscan remotehost
# remotehost SSH-2.0-OpenSSH_5.2
remotehost ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEAyREFGMBB6Qi1uoEYIk4GlqLXdS26moAxmV69UX0icQjp0Rw53xZ/2L0ZQwhsUiFV1vq4QfZNeUO142IzBgSspgsJZ7wJq213tsE7WIJGIBqvWnhU3vJuL9wgYT8f6BAvLoEfapFhLy24TDmn2DXldJAYgo8MnUbRrJlvnhQZPpd5cDWCXkzPGQE8r7REZsAWbWNlVOFRvZioPoGCGYMtsDWSBelBISGkedoNpTSpRkMmBAnsHBfvIzDPoTDYL4PZR0jJ8MaJrDhRtD4caRw4HVyhzSa3/FCpcm09PyBRabH/CyxNSOZjLc2+N9Ph9AKeTNgvmxP70wx668XaGYwCrQ==

SSH DNS Keys

Instead of using your local hostfile, you can store your keys in DNS. Have a look at sshfp to do the job. Then you can specify that ssh needs to

$ ssh localhost -o "VerifyHostKeyDNS=yes"
yes authenticity of host 'localhost (127.0.0.1)' can't be established.
RSA key fingerprint is 2d:d3:29:bd:4d:e2:7d:a3:b0:15:96:26:d4:60:13:34.
Matching host key fingerprint found in DNS.
Are you sure you want to continue connecting (yes/no)?

SSH Escape Sequences:

It often happens to me that I'm working into an ssh shell that used forwarding. I always thought there was no way to change the forwarding rules and that I had to logout. It seems not! SSh has an internal shell activated by a tilde. Seeing is believing!

Escape sequences are only recognized after a newline and are initiated with a tilde (~) unless you modify it with the -e flag.

Hit ENTER ~? on a running ssh session to see a list of escapes:

Supported escape sequences:

~. – terminate connection
~B – send a BREAK to the remote system
~C – open a command line
~R – Request rekey (SSH protocol 2 only)
~^Z – suspend ssh
~# – list forwarded connections
~& – background ssh (when waiting for connections to terminate)
~? – this message
~~ – send the escape character by typing it twice
(Note that escapes are only recognized immediately after newline.)
~. and ~# are particularly useful.

Visualize hostkeys:

Every host key has it's own visual fingerprint

$ ssh -o VisualHostKey=yes patrick@localhost
Host key fingerprint is 9f:a0:03:c1:63:8b:b8:c6:d6:83:cb:22:33:cb:83:cc
+--[ RSA 2048]----+
|                 |
|   .             |
|    =            |
| . o +           |
|. . o   S        |
|..o  . . o .     |
|== o  o   o      |
|@E. .  .         |
|+B.              |
+-----------------+

Security hacks
Local Password sniffing:

If you have process that connects to your ssh and you want to see the password it's using, then strace is your friend.

$ ps axuww | egrep 'PID|ssh'
#Now become root and attach to the running daemon with strace, changing the PID as appropriate:

$ sudo strace -f -e 'read,write' -p12345

Remote Password sniffing:

A more passive way of listening into ssh sessions (v1) is using dsniff - Dsniff
Fingerprint fuzzing:

This one is to lure a lazy administrator into accepting your certificate. It generates keys with an almost similar fingerprint. http://freeworld.thc.org/papers/ffp.html
SSH Honeypot:

And to go totally security. Launch your own ssh honeypot and capture all the remote commands (and typos) with Kippo
    http://code.google.com/p/kippo/
    http://www.securitytube.net/SSH-Password-Capture-using-Kippo-video.aspx
from http://www.jedi.be/blog/2010/08/27/ssh-tricks-the-usual-and-beyond/
--------------------------------------------------------------------------------------------

通过http代理服务器登录自己的ssh服务器

 (如果你处于公司局域网内,公司局域网一般是通过一台http代理服务器连接internet,那么请看本文)
  1. 找个Tunnel,比如corkscrew,然后解开tar包,编译安装
     ./configure
     make & make install
    
  2. 设置ssh,编辑ssh配置文件,/etc/ssh/sshd_config
     vi /etc/ssh/sshd_config
    
    然后加入
     Host *
     ProxyCommand corkscrew proxy_server proxy_port %h %p
    
    如果需要验证文件的话,还要在后面加入验证文件,如下
        ProxyCommand corkscrew proxy_server proxy_port %h %p authfile
ok,现在可以直接ssh了:

    ssh username@server

--------------------------------------------------------------------------------------------
50 SSH Helper tools - OMG!


 Secure Shell (SSH) is an awesome protocol that has been around for years now and has replaced all the insecure ways of communication between different network devices.  It uses a secure, encrypted channel between the devices it communicates with thus making network sniffers useless to grab account credentials or other sensitive content.

Many of us don’t realize that SSH is beyond just connecting between two devices.  For example, it can be setup as a proxy server, use various services in an encrypted tunnel, reverse proxy, secure backup/restore and so much more.  In this article, I’ve listed over 50 different tools that either manages or makes use of SSH to extend it’s usability beyond it’s original purpose.
  1. Sshguard -  Sshguard monitors services through their logging activity. It reacts to messages about dangerous activity by blocking the source address with the local firewall. Sshguard employs a clever parser that can transparently recognize several logging formats at once (syslog, syslog-ng, metalog, multilog, raw messages), and detects attacks for many services out of the box, including SSH, several ftpds, and dovecot. It can operate all the major firewalling systems, and features support for IPv6, whitelisting, suspension, and log message authentication.
  2. PAC -  PAC provides a GUI to configure SSH and Telnet connections, including usernames, passwords, EXPECT regular expressions, and macros. It is similar in function to SecureCRT or Putty. It is intended for people who connect to many servers through SSH. It can automate logins and command executions.
  3. csshX -  csshX is a tool to allow simultaneous control of multiple SSH sessions. csshX will attempt to create an SSH session to each remote host in separate Terminal.app windows. A master window will also be created. All keyboard input in the master will be sent to all the slave windows.
  4. tlssh -  tlssh is like SSH, but based on TLS. With tlssh, users log in using client certificates, never usernames or passwords.
  5. libssh -  libssh is a C library to access SSH services from a program. It can remotely execute programs, transfer files, and serve as a secure and transparent tunnel for remote programs. Its Secure FTP implementation can play with remote files easily, without third-party programs other than libcrypto (from OpenSSL) or libgcrypt.
  6. Digmia Enterprise SSH -  DSSH was written as a direct replacement for the OpenSSH client. It adds SSH over SSH tunneling capabilities (for example, to log in to a network hidden by a firewall), scripting support (using BeanShell), an advanced agent (which allows storing of passwords) and “su -” interactive logging for machines that have disabled direct root login. All of this was done to enable automated scripting and logging to many machines based on a few simple rules.
  7. SSH Keys exchange -  SshKeysExchange is a Korn shell script to create, exchange, and remove ssh keys between hosts within seconds rather than minutes. This tool is also included in DynDNSToolKit and oraToolKit project.
  8. CocTunnel -   CocTunnel is a simple SSH manager.
  9. Config::Model::OpenSsh -   Config::Model::OpenSsh is a graphical configuration editor for OpenSSH configuration files (e.g. /etc/ssh/sshd_config, /etc/ssh/ssh_config, or ~/.ssh/config). Other user interfaces (curses and terminal) are also available. Programmers can choose to use the Perl API to modify or validate OpenSSH configuration. This program is based on Config::Model.
  10. MindTerm -  MindTerm is a complete ssh-client in pure Java. It can be used either as a standalone Java application or as a Java applet.
  11. bcvi -   Bcvi is a tool that works with SSH to provide a secure “back channel” for sending commands back from the server to your workstation. For example, using bcvi and a shell alias, you can log into a server and type “vi filename”. Instead of running vi in the terminal window, on the remote server, bcvi will send a message back to your workstation, where a listener process will invoke gvim (a GUI version of vim) and pass it an scp://… URL for the remote file. Bcvi has a plugin architicture that allows you to add support for any process you want to launch on your workstation by running a command on the server.
  12. sshdfilter -  sshdfilter automatically blocks ssh brute force attacks by reading sshd log output in real time and adding iptables rules based on authentication failures.
  13. keychain -  keychain helps you to manage ssh keys in a convenient and secure manner. It acts as a frontend to ssh-agent and gpg-agent, but allows you to easily have one long running ssh-agent process per system, rather than the norm of one ssh-agent per login session.
  14. Meerkat -  Meerkat is an easy to use SSH tunnel manager built specifically for the Mac. It includes features such as application triggers, automatic reconnection on system sleep and network change, Growl integration, Bonjour support, command line and AppleScript integration, and much more.
  15. OmniSSH -  OmniSSH is a program that is used to execute a command or upload files on many servers in a cluster in a parallel, reliable, and well-documented fashion.
  16. lshell – lshell lets you restrict a user’s shell environment to limited sets of commands, choose to enable or disable any command over SSH (e.g. SCP, SFTP, rsync, etc.), log user’s commands, implement timing restrictions, and more.
  17. Orion SSH2 – Orion SSH2 is a library that implements the SSH-2 protocol in pure Java. It allows one to connect to SSH servers from within Java programs, for remote shell and command execution, local and remote port forwarding, local stream forwarding, X11 forwarding, and file transfer using SCP and SFTP.
  18. chain-ssh – This package provides a tool for ‘chained’ SSH access to remote hosts via a number of proxy hosts. It can be used for ssh, scp, and as a transport for rsync.
  19. secpanel – secpanel provides a GUI for managing SSH connection profiles. It supports handling of ssh-agents and the generation and distribution of public keys. It integrates SFTP using different file browsers and can use different X terminals.
  20. ccgfs – ccgfs is a transport-agnostic network filesystem using FUSE. Transport is arranged by helper programs, such as SSH. The PUSH transport mode acts like a “reverse” NFS and makes it possible to export a filesystem from a firewalled host without defeating the security model.
  21. Ganymed SSH-2 for Java – Ganymed SSH-2 for Java is a library that implements the SSH-2 protocol in pure Java (tested on J2SE 1.4.2, 5, and 6). It allows one to connect to SSH servers from within Java programs.
  22. pssh – pssh provides parallel versions of the OpenSSH tools that are useful for controlling large numbers of machines simultaneously. It includes parallel versions of ssh, scp, and rsync, as well as a parallel kill command.
  23. remote-ssh-access – remote-ssh-access is an application for creating handy SSH client shortcuts. It allows varying remote SSH keys, SSH protocol versions, remote target hosts, and remote commands for automated processes.
  24. Kippo – Kippo is a medium interaction SSH honeypot designed to log brute force attacks and, most importantly, the entire shell interaction performed by the attacker.
  25. sslh – sslh lets one accept both HTTPS and SSH connections on the same port. It makes it possible to connect to an SSH server on port 443 (e.g. from inside a corporate firewall) while still serving HTTPS on that port.
  26. ssh-multiadd – ssh-multiadd adds multiple ssh keys to the ssh authentication agent. These may use the same passphrase. When run without arguments, it adds $HOME/.ssh/identity and $HOME/.ssh/id_dsa.
  27. SSHatter – SSHatter uses a brute force technique to determine the how to log into an SSH server. It simply tries each combination in a list of usernames and passwords to determine which ones successfully log in.
  28. classh – classh is yet another wrapper around ssh for running commands on a number of hosts concurrently.
  29. sshutout – sshutout is a daemon that periodically monitors log files, looking for multiple failed login attempts via the Secure Shell daemon.
  30. Tunnel Manager – Tunnel Manager is a program that manages regularly used SSH tunnels. It supports both SSHv1 and SSHv2 tunnels and can be configured to manage the keys in your ssh-agent.
  31. sshdo – sshdo issues remote commands or puts or gets files to multiple hosts sequentially. Hosts are read from stdin (one per line). sshdo will use SSH key agent, if available, to avoid repetitive password entry.
  32. Cluster SSH - Cluster SSH opens terminal windows with connections to specified hosts and an administration console. Any text typed into the administration console is replicated to all other connected and active windows. This tool is intended for, but not limited to, cluster administration where the same configuration or commands must be run on each node within the cluster. Performing these commands all at once via this tool ensures all nodes are kept in sync.
  33. FastSSHer – Provides fast connections to Linux/Unix hosts over the SSH protocol. You don’t need to remember the IP address, hostname, login, or password. Just select a server from the list and press “Connect”.
  34. Dropbear SSH – Dropbear is an SSH 2 server and client that is designed to be small enough to be used in low-memory embedded environments, while still being functional and secure for general use.
  35. SSHMenu – SSHMenu is a GNOME panel applet that makes starting up a new terminal window with an SSH connection to a remote host just a click away.
  36. spread – spread provides SSH based Unix mass administration. It distributes commands or files from one central administration server onto classes of hosts.
  37. mpssh – mpssh is a program that can execute commands on many machines via SSH and get nicely formatted output.
  38. yessh – Yessh is a bash program that uses the SSH client. It provides fast connections to Linux/Unix hosts. Just type the name you have chosen for a host, and yessh will connect you via SSH.
  39. ssh-curse – intended to be a simple but enhancing GUI for using SSH on the terminal.
  40. SSH Askpass Keyring – SSH Askpass Keyring is an alternative ssh-askpass utility with support for the gnome-keyring.
  41. shmux – shmux is a program for executing the same command on many hosts in parallel.
  42. yaSSH – The yaSSH software package is a fast, dual-licensed implementation of SSH. It will include an SSH client, a client library, a server, and a server library. It is focused on speed, limited memory requirements, a simple API, portability, and use in an embedded setting.
  43. SSH Filesystem – SSH Filesystem uses the SSH File Transfer Protocol (SFTP), which is supported by most SSH servers. It is based on Filesystem in Userspace (FUSE), and hence root privilege is not required for mounting a remote filesystem. No setup is necessary and it is very easy to use.
  44. sshpass – Sshpass is a tool for non-interactivly performing password authentication with SSH’s so called “interactive keyboard password authentication”. Most users should use SSH’s more secure public key authentication instead.
  45. Autossh – Autossh is a program to monitor and automatically reestablish SSH connections.
  46. Proxytunnel – Proxytunnel is a program that connects stdin and stdout to a server somewhere in the Internet through an industry standard HTTPS proxy. It’s mostly used as a backend for OpenSSH’s ProxyCommand, and as a proxy backend for Putty. It can also be used for other proxy-traversing purposes.
  47. SSH Factory - SSH Factory is a set of Java based client components for communicating with SSH and telnet servers.
  48. sshfp – sshfp generates DNS SSHFP records from SSH public keys. sshfp can take public keys from a knownhosts file or from scanning the host’s sshd daemon.
  49. SSH Enchanter – Enchanter is a small library that helps you script SSH sessions in a manner similar to Expect.
  50. MySecureShell – MySecureShell is a secure FTP server that uses SSH. It is easy to install and manage.
----------------------------------------------------------------------------------
Here’s another one I found useful: http://code.google.com/p/sshpt/
The SSH Power Tool (sshpt) enables you to execute commands and upload files to many servers simultaneously via SSH without using pre-shared keys. Uploaded files and commands can be executed directly or via sudo.

sshpt-SSH Power Tool 

Description

The SSH Power Tool (sshpt) enables you to execute commands and upload files to many servers simultaneously via SSH without using pre-shared keys. Uploaded files and commands can be executed directly or via sudo. Connection and command execution results are output in standard CSV format for easy importing into spreadsheets, databases, or data mining applications.

Advantages

Since sshpt does not utilize pre-shared SSH keys it will use provided credentials for all outgoing SSH connections. This has many advantages:
  • Can be used immediately: No need to spend enormous amounts of time setting up pre-shared keys.
  • More secure: A server with pre-shared keys is a huge security risk. It literally holds the keys to the castle! With sshpt you can perform all the same tasks as with pre-shared keys with less risk to your infrastructure.
  • More compliant: Executing commands as root via pre-shared keys makes it hard to figure out after-the-fact who did what (root as a shared account). When an administrator (or user!) uses sshpt to execute commands it is much easier to figure out "who did what and when" from an auditing standpoint.

Requirements

The SSH Power Tool requires Python 2.5+ (not 3.0+ yet) and the following Python modules:
  • Paramiko - SSH implementation in Python.
  • pycrypto - Python Cryptography Toolkit (required by Paramiko).

Also A Module

sshpt is designed to be easily imported as a module so that any Python application can quickly and easily be given the ability to SSH into a large number of hosts to gather information or perform administrative tasks.

Report Format (CSV)

Execution results are reported in RFC 4180-compliant CSV format...
"host","connection result","datetime","command","command output"
  1. "host" - IP or hostname of the host in question.
  2. "connection result" - reports SUCCESS if sshpt was able to successfully connect and authenticate to the host in question, FAILED otherwise.
  3. "datetime" - The exact date and time the command was executed on the host.
  4. "command" - The command that was executed.
  5. "command output" - The output of the executed command. Right now this is just stdout but adding support for recording stderr is in the TODO list.
In the case that multiple commands were passed to sshpt the report will prepend 'index: ' before each command and each result respectively. Example:
./sshpt -f ../testhosts.txt "echo foo" "echo bar"
Username: myuserPassword:
"devhost","SUCCESS","2009-02-20 16:20:10.997818","0: echo foo
1: echo bar","0: foo
1: bar"
"prodhost","SUCCESS","2009-02-20 16:20:11.990142","0: echo foo
1: echo bar","0: foo
1: bar"

Use Cases

The following are examples of how sshpt might be used.

Run Commands

Your boss has asked you to provide a list of Linux servers that have a certain package installed (e.g. wget). You don't have root access to all systems but you do have the ability to log in...
IMPORTANT: Always make sure to surround your commands in quotes!
$ ./sshpt.py -f hostlist.txt -o wget_report.csv "rpm -q wget"
Username: myuserPassword:
"devhost","SUCCESS","2009-02-19 15:07:57.078446","rpm -q wget","wget-1.9.1-17"
"prodhost","SUCCESS","2009-02-19 15:07:58.663611","rpm -q wget","Package wget is not installed"
"blah","FAILED","2009-02-19 15:07:59.134068","rpm -q wget","(-5, 'No address associated with hostname')"
...
In this example the results were output to stdout and to an outfile (-o), wget_report.csv.

Upload Files

You've just got some new DNS servers in and you need to configure all of your servers to use them. Your task is to replace the existing resolv.conf on all of your servers with a modified one...
$ ./sshpt.py -f hostlist.txt -u myuser -s --copy-file=resolv.conf --dest=/etc/resolv.confPassword:
"blah","FAILED","2009-02-19 15:20:14.134068","sudo -u root sshpt: sftp.put /etc/resolv.conf blah:/tmp/resolv.conf)","(-5, 'No address associated with hostname')"
"devhost","SUCCESS","2009-02-19 15:20:15.401703","sudo -u root sshpt: sftp.put /etc/resolv.conf devhost:/tmp/resolv.conf)","-rw-r--r-- 1 root root 72 2009-02-19 15:20 /tmp/resolv.conf"
"prodhost","SUCCESS","2009-02-19 15:20:15.691474","sudo -u root sshpt: sftp.put /etc/resolv.conf prodhost:/tmp/resolv.conf)","-rw-r--r-- 1 root root 72 2009-02-19 15:20 /tmp/resolv.conf"
...
This example is kind of complicated so here's a detailed rundown of what happened:
  1. The file, resolv.conf was copied to each host in the hostlist.
  2. Since the sudo switch (-s) was used the file was SFTP'd to /tmp and then copied to the supplied destination (--dest) using the sudo command ("sudo -u user" is automatically prepended to the CSV output when the sudo switch is used).
  3. Since a username was supplied on the command line (-u) sshpt only asked for a password.
Note: If the sudo switch (-s) was not set the file would have been copied directly to the supplied destination (and owned by the username that was used to connect). In this case the command output would have reported "Permission Denied" since /etc/resolv.conf can only be edited/replaced by root.

Command Line Help

SSHPT Help Text

./sshpt.py --helpUsage: sshpt.py [options] [command] [arguments...]
Options:
  --version             show program's version number and exit
  -h, --help            show this help message and exit
  -f <file>, --file=<file>
                        Location of the file containing the host list.
  -o <file>, --outfile=<file>
                        Location of the file where the results will be saved.
  -a <file>, --authfile=<file>
                        Location of the file containing the credentials to be
                        used for connections (format is "username:password").
  -t <int>, --threads=<int>
                        Number of threads to spawn for simultaneous connection
                        attempts [default: 10].
  -p <port>, --port=<port>
                        The port to be used when connecting.  Defaults to 22.
  -u <username>, --username=<username>
                        The username to be used when connecting.
  -P <password>, --password=<password>
                        The password to be used when connecting (not
                        recommended--use an authfile unless the username and
                        password are transient
  -q, --quiet           Don't print status messages to stdout (only print
                        errors).
  -c <file>, --copy-file=<file>
                        Location of the file to copy to and optionally execute
                        (-x) on hosts.
  -D <path>, --dest=<path>
                        Path where the file should be copied on the remote
                        host (default: /tmp/).
  -x, --execute         Execute the copied file (just like executing a given
                        command).
  -r, --remove          Remove (clean up) the SFTP'd file after execution.
  -T <seconds>, --timeout=<seconds>
                        Timeout (in seconds) before giving up on an SSH
                        connection (default: 30)
  -s, --sudo            Use sudo to execute the command (default: as root).
  -U <username>, --sudouser=<username>
                        Run the command (via sudo) as this user.

Notes On Usage

Always make sure to put your commands in quotes like so:
./sshpt.py -f hostlist.txt "ls -l /tmp/foo" "cat /tmp/foo"
Otherwise the shell will think that '-l' is just another command line argument being passed to sshpt.py and this has the potential to cause serious problems (e.g. running 'rm -rf' on your local machine by accident)

from http://code.google.com/p/sshpt/
--------------------------------------------------------

CentOS vps中,用dropbear替换OpenSSH


dropbear是轻量的sshd服务器,与OpenSSH相比,他更简洁,更小巧,运行起来占用的内存也更少。如果你的VPS只有128M内存, 甚至64M内存,而你又比较喜欢开多个ssh终端,或者开一些ssh账号给其他同学用的话,还是比较有必要的,因为,每一个普通用户登录,OpenSSH 会开两个sshd进程,而dropbear只开一个进程,这样算起来,OpenSSH内存占用是dropbear的5-6倍。
好了,不说了,开弄。

1. 下载dropbear

wget http://matt.ucc.asn.au/dropbear/dropbear-0.52.tar.gz
tar -xvzf dropbear-0.52.tar.gz
cd dropbear-0.52
./configure
#先不要急于make和make install

2. 编译安装dropbear

OpenSSH不要马上停掉,否则,一量dropbear安装失败就连不上vps了(有console access的除外)。先把OpenSSH换个端口:
vi /etc/ssh/sshd_config
找到Port 22换成Port 2200
再执行:
service sshd restart
于是OpenSSH就监听2200端口了,好了,下面可以编译安装dropbear了:
make && make install

3. 配置dropbear

sshd服务器都需要公钥啊啥啥的,下面就来生成一下:
mkdir /etc/dropbear
/usr/local/bin/dropbearkey -t dss -f /etc/dropbear/dropbear_dss_host_key
/usr/local/bin/dropbearkey -t rsa -s 4096 -f /etc/dropbear/dropbear_rsa_host_key
这就配置完成了,启动就更简单了:
/usr/local/sbin/dropbear
设置成开机自动启动:
vi /etc/rc.local
在最后加一行:
/usr/local/sbin/dropbear

4. dropbear的补充说明

dropbear默认的安装路径是:/usr/local/sbin
如果想监听特定的端口,按如下格式执行,如果不加此参数则会监听默认端口:
/usr/local/sbin/dropbear –p 2222
更改默认监听的端口方法:
在编译dropbear之前,先执行(把2222换成您希望的端口即可):
sed -i ‘s/22/2222/g’ options.h
安装需要以下的包,在安装之前可以先执行一下:
yum install zlib* gcc make
还有其他问题的,可以:
/usr/local/sbin/dropbear -h
自己看帮助去吧。
原文:http://kangzj.net/centos-change-openssh-to-dropbear/

Debian系统的看下面
# touch /etc/ssh/sshd_not_to_be_run
# apt-get install dropbear
# vi /etc/default/dropbear
# /etc/init.d/dropbear start
------------------------------------------------------------------------------------

16 条技巧让你更高效使用 SSH

来源:16 条技巧让你更高效使用 SSH [黑客志] / 翻译及整理:@yuanyiz
原文:SSH Can Do That? Productivity Tips for Working with Remote Servers / 作者:Smylers
SSH有很多非常酷的特性,如何它是你每天的工作伴侣,那么我想你有必要了解以下16条高效使用SSH的秘籍,它们帮你节省的时间肯定会远远大于你用来配置它们的时间。

1. 多条连接共享

如果你需要在多个窗口中打开到同一个服务器的连接,而不想每次都输入用户名,密码,或是等待连接建立,那么你可以配置SSH的连接共享选项,在本地打开你的SSH配置文件,通常它们位于~/.ssh/config,然后添加下面2行:
ControlMaster auto
ControlPath /tmp/ssh_mux_%h_%p_%r
现在试试断开你与服务器的连接,并建立一条新连接,然后打开一个新窗口,再创建一条连接,你会发现,第二条连接几乎是在瞬间就建立好了。
Windows用户
如果你是Windows用户,很不幸,最流行的开源SSH客户端Putty并不支持这个特性,但是Windows上也有OpenSSH的实现,比如这个Copssh,如果你觉得下面的一些技巧对你很有帮助,或许你应该试试Copssh。
文件传输
连接共享不止可以帮助你共享多个SSH连接,如果你需要通过SFTP与服务器传输文件,你会发现,它们使用的依然是同一条连接,如果你使用的 Bash,你会发现,你甚至SSH甚至支持Tab对服务器端文件进行自动补全,共享连接选项对于那些需要借助SSH的工具,比如rsync,git等等也 同样有效。

2. 长连接

如果你发现自己每条需要连接同一个服务器无数次,那么长连接选项就是为你准备的:
ControlPersist 4h
现在你每次通过SSH与服务器建立连接之后,这条连接将被保持4个小时,即使在你退出服务器之后,这条连接依然可以重用,因此,在你下一次(4小时 之内)登录服务器时,你会发现连接以闪电般的速度建立完成,这个选项对于通过scp拷贝多个文件提速尤其明显,因为你不在需要为每个文件做单独的认证了。

3. 别再输入密码

如果你还在通过密码方式登录SSH,那么你或许应该试试SSH Keys,首先使用OpenSSH为自己声称一对密钥:
$ ssh-keygen
跟随指示,完成之后,你应该可以在你的.ssh目录下看到两个文件,id_rsa就是你的私钥,而id_ras.pub则是你的公钥,现在你需要将你的公钥拷贝到服务器上,如果你的系统有ssh-copy-id命令,拷贝会很简单:
$ ssh-copy-id smylers@compo.example.org
否则,你需要手动将你的私钥拷贝的服务器上的~/.ssh/authorized_keys文件中:
$ < ~/.ssh/id_rsa.pub ssh clegg.example.org ‘mkdir -p .ssh; cat >> .ssh/authorized_keys; chmod go-w .ssh .ssh/authorized_keys’
现在试试重新连接到SSH服务器,或是拷贝文件,是不是已经不需要再输入密码了?
为Putty配置SSH Key
Putty也可以使用SSH Key,从Putty网站下载PuttyGen和Pageant,然后使用PuttyGen生成你的密钥,将公钥拷贝到服务器 的’.ssh/authorized_keys’目录,然后运行Pageant,导入你的私钥,让它在后台运行,险隘你就可以使用Putty通过公钥直接 登录服务器了,你可以在Putty手册的第8,9章了解关于这一特性的详细介绍。

4. 连接中转

有时候你可能需要从一个服务器连接另外一个服务器,比如在两个服务器之间直接传输数据,而不用通过本地电脑中转:
www1 $ scp -pr templates www2:$PWD
(顺便说一下,当你需要在两台服务器间拷贝文件时,$PWD变量时非常有用的),因为即使你已经在两台服务器上添加了你本地电脑的公钥,scp默认 仍然会提示你输入密码:这是因为你用来作为跳板的那台服务器上并没有你的私钥,所以,第二胎服务器会拒绝你的公钥,但是一定不要通过将你的私钥拷贝到中转 服务器上来解决这个问题,你可以使用agent forwarding来解决这个问题,只要在你的.ssh/config文件中加入下面这行代码就可以了:
ForwardAgent yes
或者是在Putty中勾上“Allow agent forwarding”选项,现在你的本地SSH就变成了第一台服务器的SSH代理,从第一台服务器在连接其它服务器就变和和在你本地一样简单,注意,如果要开启这个选项,前提是这个中间服务器值得你信任。

5. 省略主机名

输入服务器的完整主机名来建立一个新的SSH连接实在是太乏味无聊了,尤其是当你有一组拥有相同域名但是子域名不同的服务器需要管理时,比如下面这样:
  • www1.example.com
  • www2.example.com
  • mail.example.com
  • intranet.internal.example.com
  • backup.internal.example.com
  • dev.internal.example.com
或许你的网络已经配置了可以直接使用短域名,比如intranet,但是如果你的网络不支持,实际上你可以自己搞定这个问题,而不用求助网络管理员。
解决办法根据你用的操作系统而略有差异,下面是我的Ubuntu系统的配置:
prepend domain-search “internal.example.com”, “example.com”;
然后你需要重启网络:$ sudo restart network-manager
不同的系统,这两条命令可能会略有差异。

6. 主机别名

你也可以在你的SSH配置中直接定义主机别名,就像下面这样:
Host dev
HostName dev.internal.example.com
你还可以使用通配符来进行分组:
Host dev intranet backup
HostName %h.internal.example.com

Host www* mail
HostName %h.example.com
在Putty中你可以为每个主机名保存单独的session,然后双击建立连接(但是它可能没办法支持通配符)。

7. 省去用户名

如果你在远程服务器上的用户名和你本地的用户名不同,你同样可以在SSH配置中进行设置:
Host www* mail
HostName %h.example.com
User simon
现在就算我的本地用户名是 smylers,我仍然可以这样连接我的服务器:
$ ssh www2
SSH会使用simon账户连接你的服务器,同样,Putty可以保存这个信息在你的session中。

8. 在服务器间跳转

有些时候,你可能没法直接连接到某台服务器,而需要使用一台中间服务器进行中转,这个过程也可以自动化。首先确保你已经为服务器配置了公钥访问,并开启了agent forwarding,现在你就可以通过2条命令来连接目标服务器,不会有任何提示输入:
$ ssh gateway
gateway $ ssh db
然后在你的本地SSH配置中,添加下面这条配置:
Host db
HostName db.internal.example.com
ProxyCommand ssh gateway netcat -q 600 %h %p
现在你就可以通过一条命令来直接连接目标服务器了:
$ ssh db
这里你可能会需要等待长一点的时间,因为SSH需要进行两次认证,,注意netcat也有可能被写成nc或者ncat或者前面还需要加上g,你需要检查你的中间服务器来确定实际的参数。

9. 突破网络封锁

有些时候,你使用的网络可能只开放了80端口,或者它们封锁了SSH端口(默认的22端口),这种情况下,你可以通过配置SSH服务器在80或者443端口进行监听来突破封锁,只需要编辑你的服务器的/etc/ssh/sshd_config文件:
Port 443
然后重启SSH服务器:
$ sudo reload ssh
当然这样做的前提是你的服务器没有使用HTTS服务,但是实际上你只需要设置一台服务器使用https端口就够了,你但你可以访问这台服务器,你就 可以使用我们前面提到的技术利用它作为跳板来访问其它服务器,但是记住,你需要提前配置好这台服务器(现在怎么样?),这样万一当你身处一个只能访问 Web的网络环境时,就可以省掉打电话让其他人帮你配置中间服务器的麻烦了。

10. 穿越Web代理

有些时候,你所在的网络不止封锁SSH端口,它们有可能更进一步,只让你通过Web代理来访问网络,幸运的是我们有一个叫做Corkscrew的程 序可以通过Web代理在发送SSH数据。Corkscrew的使用非常简单,一般我都是在需要时搜索,然后直接下载,跟随网站上的指示,然后就搞定了,一 般你需要这样一条配置:
ProxyCommand corkscrew proxy.example.org 8080 %h %p

11. 远程GUI

有时候通过本地的GUI程序来访问远程服务器的文件会非常有用,比如,编辑一副图片,或者查看一个PDF文件,或者只是简单的通过一个非命令行的编 辑器来修改代码,我发现GVim要比终端里的Vim更有用,因为我可以通过gvimopens打开一个新窗口来编辑文件,而用当前的SSH窗口继续执行其 它操作,不要要这样做,你需要先在你的SSH配置中开启一个叫做X forwarding的选项:
ForwardX11 yes
这个选项需要服务器配置才能起作用,服务器也需要开启X forwarding,你可以在服务器的/etc/ssh/sshd_config中添加下面这个命令:
X11Forwarding yes
同时你还需要确保安装了xauth,编辑器,图片查看器以及其它的你需要运行的图形化程序,这种方式只有在支持本地X服务器的操作提供才可以工 作,mac和Windows上都有免费的X Server,你可能需要花些时间配置它们,相比之下,切换到Linux相对会更容易一下。

12.本地操作远程文件

另一种让远程GUI程序显示在本地的替代方案就是让本地的GUI程序可以直接操作远程文件,你可以通过SSHFS来实现,只需要创建一个空目录,然后使用SSHFS将一个远程目录mount到这个目录就可以了:
$ mkdir gallery_src
$ sshfs dev:projects/gallery/src gallery_src
$ cd gallery_src
$ ls
现在你就可以使用任何你喜欢的本地程序来便捷这个目录中的文件了,它们看起来是在你的本地,但其实时远程服务器上的文件,你可以使用fusermount命令来unmount这些文件,不要担心记不住,它们就在sshfs手册的顶上:
$ cd ..
$ fusermount -u gallery_src
SSHFS可以在Linux和OSX上工作,Windows用户我目前还没找到什么好办法。

13. 通过Vim访问远程文件

Vim有一个内置的功能可以直接编辑远程文件,需要借助SCP URL:
$ gvim scp://dev/projects/gallery/src/templates/search.html.tt
这中方式明显不如SSHFS灵活,但是如果你只需要对远程服务器的1,2个文件进行编辑时,这条命令就要更灵活一些了,并且可以在Windows上你也可以这样做:
:help netrw-problems

14. 使用本地App连接远程服务器

有时可能有些服务,比如数据库或是Web服务器,它们运行在远程服务器上,但是如果有用方式可以直接从本地程序连接它们,那会非常有用,要做到这一 点,你需要用到端口转发(port forwarding),举个例子,如果你的服务器运行Postgres(并且只允许本地访问),那么你就可以在你的SSH配置中加入:
Host db
LocalForward 5433 localhost:5432
现在当你连接你的SSH服务器时,它会在你本地电脑打开一个5433端口(我随便挑的),并将所有发送到这个端口的数据转发到服务器的5432端口 (Postgres的默认端口),然后,只要你和服务器建立了连接,你就可以通过5433端口来访问服务器的Postgres了。
$ ssh db
现在打开另外一个窗口,你就可以通过下面这条命令在本地连接你的Postgres数据库了:
$ psql -h localhost -p 5443 orders
如果你想要使用服务器不支持的图形化Postgres客户端时,这条命令会显得尤其有用:
$ pgadmin3 &
或者你有一个后台的Web服务器,你不希望直接通过Internet访问它,你也可以通过端口转发来访问它:
Host api
LocalForward 8080 localhost:80
现在连接到服务器:
$ ssh api
然后将浏览器指向你选择的端口号:
$ firefox http://localhost:8080/

15. 减少延迟

如果每次连接服务器都意味着你需要等待几十秒而无所事事,那么你或许应该试试在你的SSH配置中加入下面这条:
GSSAPIAuthentication no
如果这条命令有效的话,你应该通知你的系统管理员让他在服务器上禁用这个选项,这样其他人就不用再分别添加这条配置到它们的本地配置了。

16. 加速连接

如果你确保你和某个服务器之间的连接是安全的(比如通过公司内网连接),那么你就可以通过选择arcfourencryption算法来让数据传输更快一些:
Host dev
Ciphers arcfour
注意这个加速是以牺牲数据的“加密”性为代价的,所以如果你连接的是位于网上的服务器,千万不要打开这个选项,并且确保你是通过VPN建立的连接。
开始行动吧!
以上就是我收集的高效使用SSH的技巧合集了,如果你还有更多技巧想要分享,记得通过Smylers@cpan.org或是通过@Smylers2来和我联系。
现在就赶紧行动试试通过这些技巧来让你的SSH更有效率吧!
-------------------------------------------------------------------------

Imagine you want to connect via SSH to remote systems hostB and hostC on an intranet behind hostA. This could be achieved easily using port forwarding via hostA, just pick two arbitrary ports on the local machine and forward them to ports 22 of hostB and hostC. This works very well for a small amount of intranet hosts, but it get's quite messy as the list of hosts grows. After some time you'll have a rather huge amount of local ports to remember (or to lookup in your port forwarding script several times a day). It'd certainly be easier to just type ssh hostB and have the tunnel setup automatically.
Fortunately that is very well possible and quite easy to achieve using the ProxyCommand directive. Assuming hostA has nc installed, you can just add the following lines to your $HOME/.ssh/config.
Host hostB
    HostKeyAlias hostB
    ProxyCommand ssh hostA 'nc hostB 22'

Host hostC
    HostKeyAlias hostC
    ProxyCommand ssh hostA 'nc hostC 22'
Once done, you can easily connect to hostB via ssh hostB, or hostC via ssh hostC. No need to setup the tunnel first, it'll be set up and teared down automagically as needed.

from http://benediktmeurer.de/2011/09/07/ssh-via-ssh-tunnel/
---------------------------------------------------------------------------

Six things I wish Mom told me (about ssh)


If you've ever seriously used a Linux system, you're probably already familiar with at least the basics of ssh. But you're hungry for more. In this post, we'll show you six ssh tips that'll help take you to the next level. (We've also found that they make for excellent cocktail party conversation talking points.)

(1) Take command!

Everyone knows that you can use ssh to get a remote shell, but did you know that you can also use it to run commands on their own? Well, you can--just stick the command name after the hostname! Case in point:
wdaher@rocksteady:~$ ssh bebop uname -a
Linux bebop 2.6.32-24-generic #39-Ubuntu SMP Wed Jul 28 05:14:15 UTC 2010 x86_64 GNU/Linux
Combine this with passwordless ssh logins, and your shell scripting powers have just leveled up. Want to figure out what version of Python you have installed on each of your systems? Just stick ssh hostname python -V in a for loop, and you're done!
Some commands, however, don't play along so nicely:
wdaher@rocksteady:~$ ssh bebop top
TERM environment variable not set.
What gives? Some programs need a pseudo-tty, and aren't happy if they don't have one (anything that wants to draw on arbitrary parts of the screen probably falls into this category). But ssh can handle this too--the -t option will force ssh to allocate a pseudo-tty for you, and then you'll be all set.
# Revel in your process-monitoring glory
wdaher@rocksteady:~$ ssh bebop -t top
# Or, resume your session in one command, if you're a GNU Screen user
wdaher@rocksteady:~$ ssh bebop -t screen -dr

(2) Please, try a sip of these ports

But wait, there's more! ssh's ability to forward ports is incredibly powerful. Suppose you have a web dashboard at work that runs at analytics on port 80 and is only accessible from the inside the office, and you're at home but need to access it because it's 2 a.m. and your pager is going off.
Fortunately, you can ssh to your desktop at work, desktop, which is on the same network as analytics. So if we can connect to desktop, and desktop can connect to analytics, surely we can make this work, right?
Right. We'll start out with something that doesn't quite do what we want:
wdaher@rocksteady:~$ ssh desktop -L 8080:desktop:80
OK, the ssh desktop is the straightforward part. The -L port:hostname:hostport option says "Set up a port forward from port (in this case, 8080) to hostname:hostport (in this case, desktop:80)."
So now, if you visit http://localhost:8080/ in your web browser at home, you'll actually be connected to port 80 on desktop. Close, but not quite! Remember, we wanted to connect to the web dashboard, running on port 80, on analytics, not desktop.
All we do, though, is adjust the command like so:
wdaher@rocksteady:~$ ssh desktop -L 8080:analytics:80
Now, the remote end of the port forward is analytics:80, which is precisely where the web dashboard is running. But wait, isn't analytics behind the firewall? How can we even reach it? Remember: this connection is being set up on the remote system (desktop), which is the only reason it works.
If you find yourself setting up multiple such forwards, you're probably better off doing something more like:
wdaher@rocksteady:~$ ssh -D 8080 desktop
This will set up a SOCKS proxy at localhost:8080. If you configure your browser to use it, all of your browser traffic will go over SSH and through your remote system, which means you could just navigate to http://analytics/ directly.

(3) Til-de do us part

Riddle me this: ssh into a system, press Enter a few times, and then type in a tilde. Nothing appears. Why?
Because the tilde is ssh's escape character. Right after a newline, you can type ~ and a number of other keystrokes to do interesting things to your ssh connection (like give you 30 extra lives in each continue.) ~? will display a full list of the escape sequences, but two handy ones are ~. and ~^Z.
~. (a tilde followed by a period) will terminate the ssh connection, which is handy if you lose your network connection and don't want to wait for your ssh session to time out.  ~^Z (a tilde followed by Ctrl-Z) will put the connection in the background, in case you want to do something else on the host while ssh is running. An example of this in action:
wdaher@rocksteady:~$ ssh bebop
wdaher@bebop:~$ sleep 10000
wdaher@bebop:~$ ~^Z [suspend ssh]

[1]+  Stopped                 ssh bebop
wdaher@rocksteady:~$ # Do something else
wdaher@rocksteady:~$ fg # and you're back!

(4) Dusting for prints

I'm sure you've seen this a million times, and you probably just type "yes" without thinking twice:
wdaher@rocksteady:~$ ssh bebop
The authenticity of host 'bebop (192.168.1.106)' can't be established.
RSA key fingerprint is a2:6d:2f:30:a3:d3:12:9d:9d:da:0c:a7:a4:60:20:68.
Are you sure you want to continue connecting (yes/no)?
What's actually going on here? Well, if this is your first time connecting to bebop, you can't really tell whether the machine you're talking to is actually bebop, or just an impostor pretending to be bebop. All you know is the key fingerprint of the system you're talking to.  In principle, you're supposed to verify this out-of-band (i.e. call up the remote host and ask them to read off the fingerprint.)
Let's say you and your incredibly security-minded friend actually want to do this. How does one actually find this fingerprint? On the remote host, have your friend run:
sbaker@bebop:~$ ssh-keygen -l -f /etc/ssh/ssh_host_rsa_key.pub
2048 a2:6d:2f:30:a3:d3:12:9d:9d:da:0c:a7:a4:60:20:68 /etc/ssh/ssh_host_rsa_key.pub (RSA)
Tada! They match, and it's safe to proceed. From now on, this is stored in your list of ssh "known hosts" (in ~/.ssh/known_hosts), so you don't get the prompt every time. And if the key ever changes on the other end, you'll get an alert--someone's trying to read your traffic! (Or your friend reinstalled their system and didn't preserve the key.)

(5) Losing your keys

Unfortunately, some time later, you and your friend have a falling out (something about Kirk vs. Picard), and you want to remove their key from your known hosts. "No problem," you think, "I'll just remove it from my list of known hosts." You open up the file and are unpleasantly surprised: a jumbled file full of all kinds of indecipherable characters. They're actually hashes of the hostnames (or IP addresses) that you've connected to before, and their associated keys.
Before you proceed, surely you're asking yourself: "Why would anyone be so cruel? Why not just list the hostnames in plain text, so that humans could easily edit the file?" In fact, that's actually how it was done until very recently. But it turns out that leaving them in the clear is a potential security risk, since it provides an attacker a convenient list of other places you've connected (places where, e.g., an unwitting user might have used the same password).
Fortunately, ssh-keygen -R <hostname> does the trick:
wdaher@rocksteady:~$ ssh-keygen -R bebop
/home/wdaher/.ssh/known_hosts updated.
Original contents retained as /home/wdaher/.ssh/known_hosts.old
I'm told there's still no easy way to remove now-bitter memories of your friendship together, though.

(6) A connection by any other name...

If you've read this far, you're an ssh pro. And like any ssh pro, you log into a bajillion systems, each with their own usernames, ports, and long hostnames. Like your accounts at AWS, Rackspace Cloud, your dedicated server, and your friend's home system.
And you already know how to do this. username@host or -l username to specify your username, and -p portnumber to specify the port:
wdaher@rocksteady:~$ ssh -p 2222 bob.example.com
wdaher@rocksteady:~$ ssh -p 8183 waseem@alice.example.com
wdaher@rocksteady:~$ ssh -p 31337 -l waseemio wsd.example.com
But this gets really old really quickly, especially when you need to pass a slew of other options for each of these connections. Enter .ssh/config, a file where you specify convenient aliases for each of these sets of settings:
Host bob
    HostName bob.example.com
    Port 2222
    User wdaher

Host alice
    HostName alice.example.com
    Port 8183
    User waseem

Host self
    HostName wsd.example.com
    Port 31337
    User waseemio
So now it's as simple as:
wdaher@rocksteady:~$ ssh bob
wdaher@rocksteady:~$ ssh alice
wdaher@rocksteady:~$ ssh self
And yes, the config file lets you specify port forwards or commands to run as well, if you'd like--check out the ssh_config manual page for the details.

ssh! It's (not) a secret.

FROM https://blogs.oracle.com/ksplice/entry/six_things_i_wish_mom

--------------------------------------

 SSH - Port Forwarding Overview

本文试图整理 openssh(before v8.0) 的几种流量转发模式。

Local Forward

本地转发

CLI Options

ssh -L [bind-address:]bind-port:target-host:target-port
ssh -L [bind-address:]bind-port:target-unix-socket
ssh -L bind-unix-socket:target-host:target-port
ssh -L bind-unix-socket:target-unix-socket

Configuration File

LocalForward [bind-address:]bind-port target-host:target-port

Description

ssh 客户端会在本地监听一个端口,即参数中的 bind-port 字段。发往该端口的流量会被封装在 ssh 流量中发往远程 sshd 服务端,再由服务端转发至目标地址,即参数中的 target-host:target-port 字段。这个功能在客户端无法直接访问目标地址时非常有用,可以透明得将目标端口“移动”到本地。

在不指定 bind-address  时,默认监听地址根据 ssh_config 文件中的 GatewayPorts 选项决定,若为 no 则默认监听在本地 loopback 上,否则默认监听在泛地址。若需要指定监听地址可以设置参数中的 bind-address 字段,比如想把其他子网中的某个服务暴露给本地网络的其他机器时可以监听在本机的内网地址上。参数为 unix domain socket 时效果类似。

缺点即是一个本地端口只能绑定一个目标地址。

Remote Forward

远程转发

CLI Options

ssh -R [bind-address:]bind-port:local-host:local-port  #1
ssh -R [bind-address:]bind-port:local-unix-socket      #2
ssh -R bind-unix-socket:local-host:local-port          #3
ssh -R bind-unix-socket:local-unix-socket              #4
ssh -R [bind-address:]port                             #5

Configuration File

# Equivalent to CLI option #1
RemoteForward [bind-address:]port local-host:local-port
# Equivalent to CLI option #5
RemoteForward [bind-address:]port

Description

    对于命令行参数的 #1-4,sshd 服务端会在远程监听在 bind-port 上。发往该端口的流量会被封装在 ssh 流量中发往本地 ssh 客户端,再由客户端转发给位于本地的目标。可以看到该过程和上述本地转发相反,这个功能在本地目标对外部不可访问时非常有用,比如把内网的某个服务暴露给其他子网(即内网穿透),相当于透明得把本地端口“移动”到远程。这种配置一次也只能绑定一个目标地址。

    对于命令行参数的 #5,sshd 服务端同样会在远程监听在 bind-port 上。但运行在该端口的是一个 socks4/socks5 代理,该代理会把目标地址和发往目标地址的流量一起转发给本地的 ssh 客户端,再由客户端转发给目标地址。可以看到,与 #1-4 的区别是在参数中没有指明目的地址,目的地址是由每个发往代理的连接动态决定的,即该选项会将本地网络完全地暴露在 sshd 所在服务器上。该选项的优点是配置一次可以转发所有流量给本地(虽然容易造成安全性问题)。缺点就是这种转发不再是透明的,想要访问位于本地的目标的应用需要设置自己的代理为远程服务器的 socket 地址。

为了增强安全性,在不指定 bind-address 时 sshd 会监听在服务器的 loopback 上。客户端也可以指定监听地址,但是一定要在 ssh_config 中添加 GatewayPorts yes 才能监听成功。

Dynamic Forward

动态转发

CLI Options

ssh -D [bind-address:]bind-port

Configuration File

DynamicForward [bind-address:]bind-port

Description

类似 Remote Forward 中的 #5 配置,ssh 客户端在本地监听在 bind-port 上,在这个端口上运行 socks4/socks5 代理,该代理会把目的地址和发往目的地址的流量一起转发给远程的 sshd 服务端,再由服务端去访问目的地址。这个选项可以用来建立一条 ssh 加密隧道,可能是最方便的 bypass 防火墙(你懂的)技术。

可以该选项即是动态版的本地转发,不知道为什么 openssh 不把这个功能集成到 Local Forward 里去。

Standard I/O Forward

转发标准输入输出

CLI Options

ssh -W target-host:target-port

Description

该选项将 ssh 客户端的标准输入输出通过 ssh 协议转发到 sshd 服务端,再由服务端转发给目标地址。功能上即是一个 ssh 版的 netcat 命令,可以用来简化 ssh 跳板机的配置,详见下面的文章。
---------------------------

SSH - Jump Server Configuration

本文介绍两种在 openssh 下方便地配置跳板机的方式。

ProxyCommand Option

通过 ~/.ssh/config 中配置 ProxyCommand 选项来实现跳板效果。
 
Configuration File

ProxyCommand command

Description

ssh 客户端在连接服务器之前会先使用 command 作为 exec 的参数启动一个进程,接下来把本该发往 ssh 服务器的流量发往该进程的标准输入,并将该进程的标准输出视作 ssh 服务器回复的流量。简单的来说就是通过新启动的进程来连接服务器。

选项的 command 参数支持使用标记符号(TOKEN),支持的符号如下:
TOKEN    Description
%h    远程服务器地址或域名
%p    远程服务器端口号
%r    远程服务器用户名
%%    字符 ‘%’

例如,设置 ProxyCommand nc %h %p 后, ssh user@1.2.3.4 -p 22334 会在连接远程服务器之前启动进程 nc 1.2.3.4 22334 ,再将 ssh 流量通过该进程的标准输入输出发送给远程服务器。在这个例子中 nc 并没有起到什么效果。但是通过设置不同的命令,可以通过该选项来实现跳板机机制。

Jump via ProxyCommand

假定跳板机的 ip 地址 1.2.3.4,端口为 12322,实际要连接的远程服务器为 10.0.0.1:23322。我们可以设置 ProxyCommand ssh -W %h:%p -p12322 user@1.2.3.4 。 -W 参数的说明可以见上一篇文章。为方便使用,我们可以在 ~/.ssh/config 中添加跳板机配置:

Host jumpserver
    Hostname 1.2.3.4
    Port 12322
    User user

再添加跳板机后面的实际目标服务器:

Host target
    Hostname 10.0.0.1
    Port 23322
    User user
    ProxyCommand ssh -W %h:%p jumpserver

注意 target 配置中的 ProxyCommand 字段使用了前面定义的 jumpserver 来简化配置。接下来可以直接在命令行中执行 ssh target 来一键通过跳板机连接远程服务器。

若想用临时配置,不想修改 ~/.ssh/config 文件,可以执行以下命令来连接远程服务器:

ssh -o'ProxyCommand ssh -W %h:%p -p12322 user@1.2.3.4' -p23322 user@10.0.0.1

ProxyJump Option

上述方式实现跳板机仍然有些复杂,在较新版本的 openssh(>=7.3) 中可以使用 -J 命令行参数或者 ProxyJump 配置来实现跳板机机制。

CLI Options

ssh -J jump-host[[,jump-host]*]

可以使用逗号来分割多个跳板机,ssh 会顺次通过跳板机来访问远程目标。

Configuration File

ProxyJump jump-host[[,jump-host]*]

同样可以使用逗号来分割多个跳板机。

Jump via ProxyJump

通过该选项可以方便地配置跳板机,假设跳板机和目标的信息和前述例子中的一样。
在 ~/.ssh/config 中添加跳板机配置:

Host jumpserver
    Hostname 1.2.3.4
    Port 12322
    User user

再添加目标服务器配置:

Host target
    Hostname 10.0.0.1
    Port 23322
    User user
    ProxyJump jumpserver

现在即可在命令行中执行 ssh target 连接目标服务器。

若想临时通过跳板机 jumpserver 连接某台新服务器 user@10.0.0.2:23333 ,可以通过在命令行中执行 ssh -J jumpserver -p23333 user@10.0.0.2 来连接。

---------------------------------------------------------------------

related post: 
 
http://briteming.blogspot.co.uk/2012/03/ssh-tricks.html 
 
https://web.archive.org/web/20121129122828/http://ymsdblog.appspot.com/log/425.html