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

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

我已经试过了……

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

...但这并不奏效。

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


当前回答

这是我登录服务器的方式:

ssp <server_ip>

别名ssp = ' / home / myuser /文件/ ssh_script.sh” 猫/home/myuser/Documents/ssh_script.sh

ssp:

#!/bin/bash

sshpass -p mypassword ssh root@$1

因此:

ssp server_ip

其他回答

如此:

#!/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
# create a file that echo's out your password .. you may need to get crazy with escape chars or for extra credit put ASCII in your password...
echo "echo YerPasswordhere" > /tmp/1
chmod 777 /tmp/1

# sets some vars for ssh to play nice with something to do with GUI but here we are using it to pass creds.
export SSH_ASKPASS="/tmp/1"
export DISPLAY=YOURDOINGITWRONG
setsid ssh root@owned.com -p 22

参考:https://www.linkedin.com/pulse/youre-doing-wrong-ssh-plain-text-credentials-robert-mccurdy?trk=mp-reader-card

我设法让它工作了:

SSH_ASKPASS="echo \"my-pass-here\""
ssh -tt remotehost -l myusername

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

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

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