首页 > 解决方案 > 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.

标签: c++visual-studiossh

解决方案


我已经设法解决了这个问题。在 Visual Studio 中选择的平台似乎有问题。最初,该项目的平台设置为 x86 架构。这就是为什么 ssh.exe 无法访问的原因,即使它存在于环境路径中。

通过在项目属性中将平台更改为 64 位架构,程序可以引用正确的环境变量并按预期执行 ssh.exe。


推荐阅读