SSHPASS|SSH登录自动键入密码

cera cera

最近在搞一个SHELL脚本的时候,需要去其它服务器拉取文件,可是发现在脚本里用SSH命令登录的时候,需要交互式的输入密码,这就造成了不能完成大叔所需要的任务,于是,大叔去谷歌了一下,发现了好几个可以非交互式远程登录的工具,大叔就是用了Sshpass完成的。大叔就简单说一下这个工具的用法吧。

大叔多说几句,如果是经常使用的服务器,还是推荐大家使用密钥登录,这样不但可以省去这些麻烦也更安全,大叔这是临时的测试服务器,所以没有使用密钥登录。

安装

  • Ubuntu/Debian: apt-get install sshpass
  • Fedora/CentOS: yum install sshpass
  • Arch: pacman -S sshpass

使用方法

NAME
       sshpass - noninteractive ssh password provider

SYNOPSIS
       sshpass [-ffilename|-dnum|-ppassword|-e] [options] command arguments

Options
       -p password
       The password is given on the command line. Please note the section titled "SECURITY CONSIDERATIONS".

       -f filename
       The password is the first line of the file filename.

       -e     The password is taken from the environment variable "SSHPASS".

基本上常用的就这几个命令,大叔直接举例来说明

-p 后面直接跟密码

    [root@10-46-164-253 ~]sshpass -p '123456' ssh ubuntu@103.72.246.237
    Welcome to Ubuntu 16.04.5 LTS (GNU/Linux 4.4.0-112-generic x86_64)
    Last login: Wed Feb 13 20:47:59 2019 from 117.50.53.210
    ubuntu@10-8-167-221:~$ exit
    logout
    Connection to 103.72.246.237 closed.
    
      

-f 后面跟密码文件

#vim pass.txt
123456

sshpass -f pass.txt ssh ubuntu@103.72.246.237

-e 需要配合指定环境变量,变量为SSHPASS

export SSHPASS=123456
sshpass -e ssh ubuntu@103.72.246.237

说一下SCP拉取文件吧

sshpass -p '123456' scp ubuntu@103.72.246.237:/home/fklds.txt ~/

另外,需要注意三点

1、如果是自定义端口,可以直接在主机后面加,也可以使用ssh的-p 参数

sshpass -p '123456' ssh ubuntu@103.72.246.237:6666
或者
sshpass -p '123456' ssh -p 6666 ubuntu@103.72.246.237

2、如果是首次连接的远程主机,并且需要下载公钥的话,需要配合ssh参数使用,否则会没有任合反馈

sshpass -p '123456' ssh -o StrictHostKeyChecking=no ubuntu@103.72.246.237

3、-p 参数的密码不可以含有特殊字符,需要转义,因此建议使用文件方式。

大叔结语

大叔只是在测试服务器,因此只是用了最直接的方式来解决,要在脚本中处理大量的交互的话,还是要用expect,大家有兴趣的可以多看看,大叔有时间再整理一下。

本文转自:fx.fklds.com

cera cloudiplc tengxunyun

相关推荐

mjjping.com cera cera cloudiplc