【发布时间】:2017-09-23 16:13:24
【问题描述】:
嗨,我正在使用 smbclient 在我的 C++ 代码中连接远程服务器,并查找远程连接的服务器上是否启用了写权限,我重定向到一个名为 tempfile 的文件,如下所示:
命令是
smbclient //服务器/文件夹 -u user%pass --directory=subfolder -c 'put file.txt' >tempfile
这个命令的输出是
将文件 file.txt 作为 \subfolder\tempfile.txt (2.0 kb/s)(平均 2.0 kb/s)
如果字符串 "putting file" 存在于重定向文件 tempfile 我确认它是 enable else not >.but tempfile 总是空不知道为什么?
下面是代码
#include<iostream>
#include<stdlib.h>
#include<fstream>
#define SMBCLIENT "smbclient "
#define TEMPFILE "tempfile"
#define search "putting file"
enum errcode
{
EMPTY,
internalError
}errCode;
void getUserCreditentail(std::string &username,std::string &password,std::string &server,std::string &folder,std::string &subfolder)
{
std::cin>>server;
std::cin>>folder;
std::cin>>subfolder;
std::cin>>username;
std::cin>>password;
}
void MakeCommand(std::string &command,const std::string server,const std::string folder,const std::string subfolder,const std::string username,const std::string password)
{
if(server.empty() ||folder.empty() || username.empty() || password.empty())
{
errCode=EMPTY;
return;
}
command= SMBCLIENT +server +"/"+ folder + " " + "-U"+ " " + username + "%" + password + " " + "--directory=" + subfolder + " " + "-c" + " " + "'put testfile.txt'" + " " + ">" + TEMPFILE;
}
bool executeCommand(const std::string command)
{
if(!command.empty())
{
if(system(command.c_str())<0)
{
std::cout<<"system call fails"<<std::endl;
errCode=internalError;
return false;
}
}
return true;
}
bool checkWritePermission()
{
std::ifstream fin(TEMPFILE);
std::string line;
if (fin.is_open())
{
std::string line;
while(getline(fin,line))
{
if (line.find(search, 0) != std::string::npos)
{
std::cout << "found: " << search << std::endl;
return true;
}
}
}
return false;
}
int main()
{
std::string command;
std::string username,password;
std::string server,folder,subfolder;
getUserCreditentail(username,password,server,folder,subfolder);
std::cout<<server<<" "<<folder<<" "<<username<<" "<<password<<""<<subfolder<<std::endl;
MakeCommand(command,server,folder,subfolder,username,password);
std::cout<<command<<std::endl;
if(executeCommand(command))
{
if(checkWritePermission())
std::cout<<"Write permission is enable"<<std::endl;
else
std::cout<<"write permission is disabled"<<std::endl;
}
return 0;
}
【问题讨论】:
-
请帮我理解为什么投反对票?
-
如果你在终端中执行,命令是否按预期工作?
-
是的,它可以工作,但输出不会重定向到文件,而是显示在终端上。不知道为什么
-
那么它可能打印在stderr而不是stdout上,你需要阅读如何重定向stderr。
-
我注意到当它失败时它被重定向到一个文件但是当它成功时它不会被重定向