我需要创建一个自动向OpenSSH ssh客户端输入密码的脚本。

假设我需要使用密码a1234b SSH到myname@somehost。

我已经试过了……

#~/bin/myssh.sh
ssh myname@somehost
a1234b

...但这并不奏效。

如何将此功能放入脚本中?


当前回答

这基本上是abbotto的答案的扩展,有一些额外的步骤(针对初学者),使启动你的服务器,从你的linux主机,非常容易:

编写一个简单的bash脚本,例如:

#!/bin/bash

sshpass -p "YOUR_PASSWORD" ssh -o StrictHostKeyChecking=no <YOUR_USERNAME>@<SEVER_IP>

保存文件,例如'startMyServer',然后在你的终端上运行这个命令使文件可执行:

sudo chmod +x startMyServer

将文件移动到“PATH”变量中的文件夹(在终端中运行“echo $PATH”查看这些文件夹)。例如,将它移动到'/usr/bin/'。

瞧,现在你可以通过在终端中输入'startMyServer'进入服务器。

P.S.(1)这不是很安全,请查看ssh密钥以获得更好的安全性。

附注(2)SMshrimant的答案很相似,对一些人来说可能更优雅。但我个人更喜欢使用bash脚本。

其他回答

Sshpass + autossh

前面提到的sshpass的一个好处是,您可以将它与autossh一起使用,从而消除了更多交互效率低下的问题。

sshpass -p mypassword autossh -M0 -t myusername@myserver.mydomain.com

这将允许自动重新连接,如果你的wifi被打断,关闭你的笔记本电脑。

有一个跳转主机

sshpass -p `cat ~/.sshpass` autossh -M0 -Y -tt -J me@jumphost.mydomain.com:22223 -p 222 me@server.mydomain.com

@abbotto的答案对我不起作用,不得不做一些不同的事情:

Yum install sshpass更改为- RPM -ivh http://dl.fedoraproject.org/pub/epel/6/x86_64/sshpass-1.05-1.el6.x86_64.rpm 使用sshpass的命令修改为- sshpass -p "pass" SSH user@mysite -p 2122

如此:

#!/usr/bin/expect -f
spawn ssh USERNAME@SERVER "touch /home/user/ssh_example"
expect "assword:"
send "PASSWORD\r"
interact

但是! !如果出现如下错误,只需使用expect而不是bash启动脚本,如下所示 而不是bash mysh .sh

/bin/myssh.sh: 2: spawn: not found /bin/myssh.sh: 3: expect: not found /bin/myssh.sh: 4: send: not found /bin/myssh.sh: 5: expect: not found /bin/myssh.sh: 6: send: not found

您可以使用expect脚本。我没有写一个在相当长的一段时间,但它应该如下所示。您需要在脚本前面加上#!/usr/bin/expect

#!/usr/bin/expect -f
spawn ssh HOSTNAME
expect "login:" 
send "username\r"
expect "Password:"
send "password\r"
interact

如果您在Windows系统上执行此操作,您可以使用Plink (PuTTY的一部分)。

plink your_username@yourhost -pw your_password