Openssh 常见用法

用法:

usage: ssh [-1246AaCfgKkMNnqsTtVvXxYy] [-b bind_address] [-c cipher_spec]
           [-D [bind_address:]port] [-e escape_char] [-F configfile]
           [-I pkcs11] [-i identity_file]
           [-L [bind_address:]port:host:hostport]
           [-l login_name] [-m mac_spec] [-O ctl_cmd] [-o option] [-p port]
           [-R [bind_address:]port:host:hostport] [-S ctl_path]
           [-W host:port] [-w local_tun[:remote_tun]]
           [[email protected]]hostname [command]

常见参数:

创建密钥对

推荐 ed25519,已在 OpenSSH 6.5 中加入支持

ssh-keygen -t ed25519 -C "[email protected]"
ssh-keygen -t rsa -b 4096 -C "[email protected]"
ssh-keygen -t ecdsa -b 521 -C "[email protected]"

验证公钥指纹

ssh-keygen -E md5 -lf ~/.ssh/your_pubkey

从私钥创建公钥

ssh-keygen -y -f ~/.ssh/id_rsa > ~/.ssh/your_pubkey

修改私钥口令

ssh-keygen -p -f ~/.ssh/your_pubkey

重新生成服务器密钥

rm -v /etc/ssh/ssh_host_*
ssh-keygen -A
systemctl restart ssh

或者手动生成各自需要的服务器密钥

ssh-keygen -q -N "" -t ed25519 -f /etc/ssh/ssh_host_ed25519_key
ssh-keygen -q -N "" -t rsa -b 4096 -f /etc/ssh/ssh_host_rsa_key
ssh-keygen -q -N "" -t ecdsa -b 521 -f /etc/ssh/ssh_host_ecdsa_key
ssh-keygen -q -N "" -t dsa -f /etc/ssh/ssh_host_dsa_key
systemctl restart ssh

debian 用户可以用如下方式

rm -v /etc/ssh/ssh_host_*
dpkg-reconfigure openssh-server  # debian
systemctl restart ssh

普通的登录

ssh [email protected]
or
ssh -l user remotehost

一般而言,对于常用参数,我们将之写入到 .ssh/config 文件中是个很常用的做法

Host hostname
    IdentityFile    ~/.ssh/your-private-key
    HostName        ip or domain
    Port            port
    User            username

Host *
    Compression     yes

如此,连接的时候只要如下即可

ssh hostname

proxy

ssh -C -N -D localport [email protected] -p remoteport

mount

sshfs -p remoteport [email protected]:/remotepath localpath

将远程主机的 remotepath 挂载到本地 localpath

umount

fusermount -u localpath

卸载挂载文件

scp

上传本地 file 到远程的 remotepath

scp localpath/file [email protected]:/remotepath

下载远程 file 文件到本地

scp [email protected]:/remotepath/file localpath

传输远端服务器文件给另一个远端服务器,通过本地

scp -3rp [email protected]:/path/file [email protected]:/path/

ssh-agent

ssh-agent 一般人用不到,不过还是挺有用的,概念不介绍了。用法也是很简单,Mac 用户编辑 .ssh/config 文件

Host host1
    IdentityFile    ~/.ssh/your-private-key
    HostName        ip/domain
    ForwardAgent    yes
    Port            port
    User            username

Host *
    AddKeysToAgent  yes
    UseKeychain     yes
    Protocol        2
    Compression     yes

ProxyCommand

不过,并不是所有的机子的公钥是一致的,但是有不得不使用其中一台作为跳板,那么我们就使用这个参数了

Host host1
    IdentityFile    ~/.ssh/your-private-key1
    HostName        ip1/domain1
    Port            port1
    User            username1

Host host2
    IdentityFile    ~/.ssh/your-private-key2
    HostName        ip2/domain2
    port            port2
    User            username2
    ProxyCommand    ssh host1 -W %h:%p

如此,直接 ssh host2 时,是通过host1作为跳板的,当然,如果只是临时的话,就没必要配置 ~/.ssh/config 了,直接命令行

ssh [email protected]_ip -p port -o ProxyCommand='ssh host1 -W %h:%p'

也能临时达到要求,至于记不住参数什么的,直接 alias 吧。