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

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

我已经试过了……

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

...但这并不奏效。

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


当前回答

如此:

#!/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

其他回答

不同的我

sshpass -p PASSWORD ssh USER@SERVER

后缀II

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

在寻找这个问题的答案几个月后,我终于找到了一个更好的解决方案:写一个简单的脚本。

#!/usr/bin/expect

set timeout 20

set cmd [lrange $argv 1 end]
set password [lindex $argv 0]

eval spawn $cmd
expect "password:"
send "$password\r";
interact

把它放在/usr/bin/exp,所以你可以使用:

Exp <password> SSH <任何> Exp <password> SCP <anysrc> <anydst>

完成了!

Solution1:使用sshpass

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

您可以通过

# Ubuntu/Debian
$ sudo apt-get install sshpass

# Red Hat/Fedora/CentOS
$ sudo yum install sshpass

# Arch Linux
$ sudo pacman -S sshpass

#OS X
brew install https://raw.githubusercontent.com/kadwanev/bigboybrew/master/Library/Formula/sshpass.rb

或从这里下载源代码

tar xvzf sshpass-1.08.tar.gz 
cd sshpass-1.08.tar.gz 
./configure
sudo make install

解决方案2:设置SSH无密码登录

假设您需要使用密码2b2b2b从aaa@1.1.1.1(客户端服务器A) SSH到bbb@2.2.2.2(远程服务器B)。

在A中使用如下命令生成公钥(.ssh/id_rsa.pub)和私钥(.ssh/id_rsa)

ssh-keygen -t rsa
[Press enter key]
[Press enter key]
[Press enter key]

使用以下命令将生成的公钥(.ssh/id_rsa.pub)以文件名authorized_keys分发到bbb的.ssh目录下的服务器B

ssh-copy-id bbb@2.2.2.2

第一次ssh登录需要输入密码,以后会自动登录,不需要再次输入!

ssh bbb@2.2.2.2 [Enter]
2b2b2b

然后你的剧本就可以

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

如此:

#!/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