c++ - How to run SSH with system() in C++
问题描述
I've written a simple program to connect to a Linux server using SSH via my C++ program. Here's the code:
#include <iostream>
#include <cstring>
#include <stdlib.h>
using namespace std;
int main()
{
string hostIP;
string username;
string password;
cout << "Welcome to SSH Program" << endl;
cout << "----------------------" << endl;
cout << "\nEnter host ip or name Example: \"capa.its.uow.edu.au\": ";
cin >> hostIP;
cout << "Enter username: ";
cin >> username;
cout << "\nConnecting...\n" << endl;
string composite = "ssh " + username + "@" + hostIP;
char command[100];
strcpy(command, composite.c_str());
system(command);
system("pause");
}
It runs well on Ubuntu, but when I compile this same code on Visual Studio in Windows and execute it, the console present me with this error: 'ssh.exe' is not recognized as an internal or external command, operable program or batch file.
This didn't make sense to me because OpenSSH Client is clearly installed on my computer and I'm able to establish an SSH connection if I directly enter ssh username@server.ip.address
in the command prompt.
I thought it might be an issue with the environment paths and so in Visual Studio, I checked Project>Properties>VC++ Directories>Executable Directories
. There I found C:\WINDOWS\System32\OpenSSH\
among other paths, located in the Evaluated value:
box.
Doesn't this mean everything should run fine since the OpenSSH directory is located in the path? Also, like I said, I am able to connect via SSH if I enter the command directly into the command prompt instead of the program.
Please help. I've been really scratching my head over this since last night.
解决方案
我已经设法解决了这个问题。在 Visual Studio 中选择的平台似乎有问题。最初,该项目的平台设置为 x86 架构。这就是为什么 ssh.exe 无法访问的原因,即使它存在于环境路径中。
通过在项目属性中将平台更改为 64 位架构,程序可以引用正确的环境变量并按预期执行 ssh.exe。
推荐阅读
- swift - UI 测试:如何在表单中查询选择器值
- security - kubernetes securitycontext runAsNonRoot 不工作
- c# - 为什么 Parallel 类的 For 方法会随着时间的推移变得更快?
- javascript - 函数值是在使用 return console.log 时定义的,而不是简单的 return 语句
- grafana - 我们可以在 Grafana 混合数据源(MS SQL Server)中将一个数据源查询的输出设置为其他数据源查询的输入吗
- javascript - 想要使用拼接方法从对象数组中删除动态附加的卡片,但循环迭代得到错误的值
- python - 在 Python 中将图形对象附加到 networkx 列表的问题
- python - 进行反箱考克斯变换时获取 *nan* 值
- javascript - 在特定位置写入 JSON 数据
- vue.js - Storybook 和 Vuetify 的未知自定义元素