我需要创建一个自动向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
其他回答
如此:
#!/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
我有一个更好的解决方案,包括登录您的帐户,而不是更改为根用户。 它是一个bash脚本
http://felipeferreira.net/index.php/2011/09/ssh-automatic-login/
在寻找这个问题的答案几个月后,我终于找到了一个更好的解决方案:写一个简单的脚本。
#!/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>
完成了!
我使用下面的解决方案,但你必须安装sshpass如果它还没有安装,使用sudo apt install sshpass安装它
现在你可以这样做,
sshpass-p *YourPassword* ssh root@IP
您还可以创建一个bash别名,这样就不必一次又一次地运行整个命令。 遵循以下步骤
cd ~
Sudo nano .bash_profile
在文件末尾添加以下代码
mymachine() {sshpass -p *YourPassword* ssh root@IP}
源. bash_profile
现在只要在终端运行mymachine命令,你就会进入你的机器,没有密码提示。
注意:
我的机器可以是你选择的任何命令。 如果在这个任务中安全性对您来说不重要,而您只想自动化工作,您可以使用此方法。
在下面的例子中,我将写下我使用的解决方案:
场景:我想用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"