ssh 无疑是linux 用户使用的最频繁的命令之一。 linux 下的ssh 命令在这里理解为ssh 客户端。ssh 提供了一种加密的网络通信方式。同时在linux 下,提供了一系列基于ssh 的管理工具。
ssh 常用用法
ssh 远程登录
ssh youname@targethost
ssh 远程执行命令
ssh yourname@targethost yourcommand
ssh 免密码登录
我们可以通过以下几个步骤实现免密码(执行ssh 命令时,自动登录,不会停在密码输入界面)登录, 在下面S 表示server 机器, C表示client 机器
1. 在C 生成一个密码为空的 公私 密钥对(公约和私钥是同时生成的,分别在加密和解密的时候使用)
2. 将C 生成的公钥拷贝到S 的 用户目录下的 `.ssh/authorized_keys 文件中( 如果没有,新建之)
这样用户 就可从C 使用免密码的方式登录到S 了。
# 生成密钥对
ssh-keygen
Generating public/private rsa key pair.
Enter file in which to save the key (/Users/peanut/.ssh/id_rsa): 输入密钥文件名(e.g.这里使用test)
#然后一直拍 Enter 键
#直到命令执行结束, 可以执行 *ls* 查看生成文件
#将#1 中后缀为.pub(test.pub) 的文件中的文本内容copy 到S 的authorized_keys 文件(放在新的一行),
#如果要新创建 authorized_keys, 需要设置权限 chmod 600 authorized_keys (其他用户不可见)
基于ssh 实现的其他工具
sftp
基于ssh 的ftp
sftp user@targethost
#进入之后,就是ftp的操作命令了
scp
基于ssh 的远程拷贝(也可以用于本地操作)
#拷贝文件
#scp localpath user@targethost:/remotepath
scp test.pub peanut@172.30.1.1:/home/peanut/tmp/
#拷贝目录
#scp localpath user@targethost:/remotepath
scp -r ./test/ peanut@172.30.1.1:/home/peanut/tmp/
rsync
基于ssh 的同步指令, 可以用来实现scp 的功能,以及其他的复杂功能
#简单拷贝文件
rsync test.pub peanut@172.30.1.1:/home/peanut/tmp/
#拷贝目录,把test目录下的内容拷贝到tmp目录下
rsync -r ./test/ peanut@172.30.1.1:/home/peanut/tmp/
#拷贝目录, 注意,和上面的命令不一样, 会把test 目录,拷贝到tmp 目录下
scp -r ./test peanut@172.30.1.1:/home/peanut/tmp/
#拷贝目录的时候,检查冲突(不会实际执行拷贝),结果会罗列出相同路径, 但内容不一样的文件(包括目录)
# n 是dry run 模式,可以按not 记忆,便于理解 v 表示显示详细信息
scp -rvn ./test/ peanut@172.30.1.1:/home/peanut/tmp/
#通过checksum 来检查文件是否一致
scp -rvnc ./test/ peanut@172.30.1.1:/home/peanut/tmp/