简体   繁体   English

Bash 脚本 - 如果 SSH 连接由于无效 IP 而失败,请不要运行程序并打印错误消息

[英]Bash Script - If SSH connection fails due to invalid IP, don't run program and print error message

I'm trying to verify if an IP address is valid before starting the program.我正在尝试在启动程序之前验证 IP 地址是否有效。 The user has to enter an IP address and password, and if the connection is unable to happen, there should be some connection timeout or error message.用户必须输入 IP 地址和密码,如果无法连接,应该有一些连接超时或错误消息。 Is there a way to check if the ssh was successful before running a function in my program, and if not, the program should exit?有没有办法在我的程序中运行 function 之前检查 ssh 是否成功,如果没有,程序应该退出?

status=$(sshpass -p "$PASSWORD" ssh -o ConnectTimeout=5 root@"IP_ADDRESS" exit)

echo "Status: $status"

if [[ $status != 0]]; then
    echo "Connection failed. Re-check IP address or password."
else 
    startProgram
fi

I heard if the ssh was successful, it should return 0 - otherwise it would return a non-zero value.我听说如果 ssh 成功,它应该返回 0 - 否则它会返回一个非零值。 But, when I attempt to validate the connection this way, I always get the "Connect failed" message because status doesn't return any value.但是,当我尝试以这种方式验证连接时,我总是收到“连接失败”消息,因为状态不返回任何值。 The echo statement just prints "Status: " regardless of whether my login credentials were correct or not. echo 语句只打印“状态:”,无论我的登录凭据是否正确。

status only contains the standard output from your command. status 仅包含来自您的命令的标准 output。 You need to look at $?你需要看$? to get the return code.获取返回码。

status=$(sshpass -p "$PASSWORD" ssh -o ConnectTimeout=5 root@"IP_ADDRESS" exit)
retcode=$?
echo "Status: $status"

if [[ $retcode -ne 0 ]]; then
    echo "Connection failed. Re-check IP address or password."
else 
    startProgram
fi

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM