ssh带登陆

本文介绍如何在命令行中带着密码登陆ssh,基于ubuntu 16.04 64bit系统。

使用sshpass

安装:

1
sudo apt install sshpass

使用格式:

1
sshpass -p <密码> ssh <用户名>@<IP或域名> -o StrictHostKeyChecking=no [在远程服务器执行的命令]

<>为必填项,[]为可选项。-o StrictHostKeyChecking=no表示不检查key,因为首次登陆时,会出现:

1
2
3
The authenticity of host 'XXX (120.XX.237.XX)' can't be established.
ECDSA key fingerprint is SHA256:hBonkc1ZLbAPrT1HB47asdf3CjvLSKN4PGIcS5BSSDX3YY.
Are you sure you want to continue connecting (yes/no)?

此时,必须手动输入yes或no才能输入密码。

使用示例:

1
sshpass -p 123456 ssh latelee@192.168.28.131 -o StrictHostKeyChecking=no "echo hello > /tmp/foo"

注:使用复杂的密码(有特殊符号)测试时,发现-p后的密码需要使用双引号即-p "1234"

密码使用环境变量保存,不在命令中出现:

1
2
export SSHPASS="123456" # 设置环境变量,SSHPASS为sshpass固定的变量
sshpass -e ssh latelee@192.168.28.131 -o StrictHostKeyChecking=no "echo hello123 > /tmp/foo" # -e表示从环境变量中读取

如果执行的命令出错,会有相应的提示(命令找不到,或命令使用非法)。如下:

1
2
sshpass -p 123456 ssh latelee@192.168.28.131 -o StrictHostKeyChecking=no "echo111 hello > /tmp/foo"
bash: echo111: command not found

即主机上有错误命令的提示,
在命令最后添加>/dev/null 2>&1,将错误信息重定向到/dev/null中。则在主机不会显示。

1
sshpass -p 123456 ssh latelee@192.168.28.131 -o StrictHostKeyChecking=no "echo111 hello > /tmp/foo  >/dev/null 2>&1"

注:命令执行出错会返回错误码,使用echo $?可查看。

在本地(Windows或Linux)生成公钥、私钥。
命令为ssh-keygen -t rsa,其输出信息及操作(中文表示)如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
Generating public/private rsa key pair.
Enter file in which to save the key (/root/.ssh/id_rsa): 保存目录,默认,直接回车即
Enter passphrase (empty for no passphrase): 不输入密码,直接回车即可
Enter same passphrase again: 直接回车
Your identification has been saved in /root/.ssh/id_rsa.
Your public key has been saved in /root/.ssh/id_rsa.pub.
The key fingerprint is:
SHA256:7PSMhZ5+ocFnRLSLDYrJFtCp2PfO5CNwQMYmnJHCqYo root@ecs-cba4-0002.novalocal
The key's randomart image is:
+---[RSA 2048]----+
|oo*. . .. |
|o*=.o .. |
|oB .. ... |
|o +..+ o =.. |
|o o=...S.+ |
|E ... o+o*+ |
| o = ==o. |
| . =.. . |
| . ... |
+----[SHA256]-----+

产生文件:id_rsa为私钥,id_rsa.pub为公钥。

将公钥文件id_rsa.pub的内容放到远程服务器的~/.ssh/authorized_keys中(可以同时存在多个,按顺排好即可),示例:
echo "公钥内容" >> ~/.ssh/authorized_keys