[英]How to execute shell commands and interact with the output on linux using C++?
I use Eclipse and I try to execute shell commands
written in a cpp-file. 我使用Eclipse,并尝试执行用cpp文件编写的
shell commands
。
As far as I know, I can use the system()
function to execute a shell command
in cpp, but how can I respond to a prompt in the terminal? 据我所知,我可以使用
system()
函数在cpp中执行shell command
,但是如何响应终端中的提示?
I know that after a certain command the shell will ask for a password and I have to put it in there. 我知道在执行某些命令后,shell会要求输入密码,因此我必须将其放入其中。 At first I tried to put my password into a second
system()
function but it didn't work. 最初,我尝试将密码放入第二个
system()
函数,但此方法无效。 Although I put a sleep
call between both system()
function calls, it doesn't work: 尽管我在两个
system()
函数调用之间都添加了sleep
调用,但它不起作用:
system(DO)// after this command the shell asks for a password
sleep(10)
system(Password)`
How can I enter the password? 如何输入密码?
You can pass the password in your first system
instruction. 您可以在第一条
system
说明中输入密码。 If your command is something like getPassword
then it will be: 如果您的命令类似于
getPassword
则它将为:
system("echo yourPassword | getPassword");
Although including the plain password in the program is dangerous. 尽管在程序中包含普通密码是危险的。
UPDATE: 更新:
For SSH it will not work, but for common commands that get arguments from console like apt-get
it will work. 对于SSH,它将不起作用,但对于从控制台获取参数(如
apt-get
常用命令,它将起作用。 Using sshpass
turns it back to getting password argument from stdin as normal. 使用
sshpass
可以正常返回标准输入。 Another alternative is expect
in Tcl
that can enter password for SSH automatically and conditional. 另一种选择是
expect
中Tcl
,可以为SSH自动和有条件的进入密码。
Again, using plain text for password is not recommended at all. 同样,完全不建议使用纯文本作为密码。 consider using public key authentication instead.
考虑改用公共密钥身份验证。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.