Ssh command from Qt

2019-07-10 11:04发布

问题:

I have a problem with ssh in my Qt application. I need to run a command which removes a file on a remote server. I tried to use a QProcess class to achieve it. So I pass "ssh" as a name of command and necessary args. In common it looks like this:

QStringList params;    
params.append(" user@" + ::host +
              " \"rm /tmp/" + ::fileName + "\"");
d->impDelProcess->start("ssh", params);

But after all it keeps asking a password, though I generated ssh keys and copied a public key to the remote server. Moreover, when I run the command above in the terminal like this:

ssh user@host "rm /path/fileName"

it works perfect. The file is deleted and no password is asked. So, the problem is somwhere in QProcess. Is any way to get rid of asking a password? Thank you!

回答1:

Those are separate arguments, when you use string list. Try this:

params.append("user@" + ::host");
params.append("rm /tmp/" + ::fileName);

That will make Qt pass two arguments for ssh, the login string and the command to execute at remote host.

Important note! Above assumes ::filename does not contain spaces or anything else nasty!. You can get around spaces with this:

params.append("rm '/tmp/" + ::fileName + "'");

But it won't help against wild cards or .. in path... Imagine if file name was ../home/user/* for example... So that is better be trusted input, or you need to sanitize it (but that is beyond scope of this answer).


What you do in the question code is to construct a single argument, equivalent to this shell command line:

ssh 'user@host "rm /path/filename"'


标签: c++ qt ssh