首页 > 解决方案 > 在 Node.js 中执行 bash 脚本时,SSH 连接被拒绝

问题描述

所以我的结构是这样的:

main.js
folder1/
   jsFile1.js
folder2/
   jsFile2.js
   bashFile.sh

main.jsrequires jsFile1.js,然后 requires 并运行jsFile2.js. jsFile2.js然后最终bashFile.sh使用 ShellJS 运行并传递三个参数。

shell.exec(`bash utils/sshAndCreate.sh ${ip} ${encryptedUser} ${encryptedPw}`);

bashFile.sh:

#!/bin/bash

# Variables
host=$1
user=$2
pw=$3

# Postdata
postdata="someUnfinishedStuff"

# Download the file to the server
ssh root@$host -o StrictHostKeyChecking=no wget http://myOtherServer/api --post-data $postdata -O bash.sh

我的问题是,当我手动开始bashFile.sh使用它时,它工作得很好并且符合预期,但是当我运行它最终也运行脚本bash bashFile.sh parameter1 parameter2 parameter3时它不起作用。main.js我只是得到

ssh: connect to host myServerIpHere port 22: Connection refused

还有什么奇怪的,我把shell.exec部件移到了jsFile1.js它,它工作了几次,但是当我再次尝试时,我的连接也被拒绝了。

注意 1:我以前从未连接到服务器,所以它不在我的known_hosts.

注 2: child_process 产生相同的错误。

标签: node.jsbashsshshelljs

解决方案


我现在找到了解决方案。即使服务器应该准备好它有时也不是。所以我通过重复连接过程直到服务器接受连接来解决它。

until ssh root@$host command
do
    sleep 10
done

推荐阅读