我需要创建一个自动向OpenSSH ssh客户端输入密码的脚本。
假设我需要使用密码a1234b SSH到myname@somehost。
我已经试过了……
#~/bin/myssh.sh
ssh myname@somehost
a1234b
...但这并不奏效。
如何将此功能放入脚本中?
我需要创建一个自动向OpenSSH ssh客户端输入密码的脚本。
假设我需要使用密码a1234b SSH到myname@somehost。
我已经试过了……
#~/bin/myssh.sh
ssh myname@somehost
a1234b
...但这并不奏效。
如何将此功能放入脚本中?
当前回答
安全性更高的Sshpass
我在寻找ssh进入瘫痪服务器的方法时偶然发现了这个线程——处理ssh连接尝试花了一分钟多,在我输入密码之前超时了。在本例中,我希望能够在提示可用时立即提供我的密码。
(如果还不清楚的话:服务器处于这种状态,再设置公钥登录就太迟了。)
Sshpass来救援。但是,有比sshpass -p更好的方法。
我的实现直接跳到交互式密码提示(不会浪费时间查看是否可以进行公钥交换),并且从不以纯文本的形式显示密码。
#!/bin/sh
# preempt-ssh.sh
# usage: same arguments that you'd pass to ssh normally
echo "You're going to run (with our additions) ssh $@"
# Read password interactively and save it to the environment
read -s -p "Password to use: " SSHPASS
export SSHPASS
# have sshpass load the password from the environment, and skip public key auth
# all other args come directly from the input
sshpass -e ssh -o PreferredAuthentications=keyboard-interactive -o PubkeyAuthentication=no "$@"
# clear the exported variable containing the password
unset SSHPASS
其他回答
使用公钥认证:https://help.ubuntu.com/community/SSH/OpenSSH/Keys
在源主机中只运行一次:
ssh-keygen -t rsa # ENTER to every field
ssh-copy-id myname@somehost
这就是全部,之后你就可以不用密码使用ssh了。
我得到了这个工作如下
.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个小时才弄明白!
通过shell脚本连接远程机器,使用以下命令:
sshpass -p PASSWORD ssh -o StrictHostKeyChecking=no USERNAME@IPADDRESS
其中IPADDRESS, USERNAME和PASSWORD是需要在脚本中提供的输入值,或者如果我们想在运行时提供,使用“read”命令。
首先需要安装sshpass。
Ubuntu/Debian: apt-get安装sshpass Fedora/CentOS: yum安装sshpass Arch:吃豆人-S sshpass
例子:
sshpass -p "YOUR_PASSWORD" ssh -o StrictHostKeyChecking=no YOUR_USERNAME@SOME_SITE.COM
自定义端口示例:
sshpass -p "YOUR_PASSWORD" ssh -o StrictHostKeyChecking=no YOUR_USERNAME@SOME_SITE.COM:2400
注:
当传递-f标志时,Sshpass还可以从文件中读取密码。 使用-f可以防止在执行ps命令时密码显示。 存储密码的文件应具有安全权限。
在下面的例子中,我将写下我使用的解决方案:
场景:我想用sh脚本从服务器复制文件:
#!/usr/bin/expect
$PASSWORD=password
my_script=$(expect -c "spawn scp userName@server-name:path/file.txt /home/Amine/Bureau/trash/test/
expect \"password:\"
send \"$PASSWORD\r\"
expect \"#\"
send \"exit \r\"
")
echo "$my_script"