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

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

我已经试过了……

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

...但这并不奏效。

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


当前回答

我得到了这个工作如下

.ssh/config被修改以消除是/否提示-我在防火墙后面,所以我不担心欺骗ssh密钥

host *
     StrictHostKeyChecking no

为expect创建一个响应文件,即answer.expect

set timeout 20
set node [lindex $argv 0]
spawn ssh root@node service hadoop-hdfs-datanode restart

expect  "*?assword {
      send "password\r"   <- your password here.

interact

创建bash脚本并在文件中调用expect

#!/bin/bash
i=1
while [$i -lt 129]    # a few nodes here
  
  expect answer.expect hadoopslave$i

  i=[$i + 1]
  sleep 5

done

获取128个用新配置刷新的hadoop datanode -假设您正在为hadoop/conf文件使用NFS挂载

希望这能帮助到一些人——我是一个Windows傻瓜,这花了我大约5个小时才弄明白!

其他回答

如此:

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

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

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

使用公钥认证:https://help.ubuntu.com/community/SSH/OpenSSH/Keys

在源主机中只运行一次:

ssh-keygen -t rsa # ENTER to every field
ssh-copy-id myname@somehost

这就是全部,之后你就可以不用密码使用ssh了。

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

plink your_username@yourhost -pw your_password