<p>Hello golang,
I've searched, but found only one related to windows (<a href="http://stackoverflow.com/questions/31558066/how-to-ask-for-administer-privileges-on-windows-with-go" rel="nofollow">http://stackoverflow.com/questions/31558066/how-to-ask-for-administer-privileges-on-windows-with-go</a>)</p>
<p>So I'm writing a cli app that has a task to update /etc/hosts. I was able to manage to do it like this for one liner:</p>
<pre><code>cmd := exec.Command("bash", "-c", "echo blah 127.0.0.1 | sudo tee -a /etc/hosts")
cmd.Start()
err := cmd.Wait()
if err != nil { fmt.Println("WHAT?") }
</code></pre>
<p>However, this time I need to add multiline string value to /etc/hosts and doing string manipulation through bufio package with some business logics that I have to implement, but have no luck yet.</p>
<p>Any direction or hint would be greatly appreciated.</p>
<hr/>**评论:**<br/><br/>jamesrr39: <pre><p>You can use <code>\n</code> to insert a line break: <code>line1\nline2</code></p>
<p>Do you need to shell out to bash? What about opening in append mode:</p>
<pre><code>filename := "/etc/hosts"
fileInfo, err := os.Stat(filename)
... handle err
handler, err := os.OpenFile(filename, os.O_APPEND|os.O_WRONLY, fileInfo.Mode())
... handle err
defer handler.Close()
f.WriteString(text)
</code></pre></pre>golangman: <pre><p>With os package, it wouldn't prompt for password and can't update /etc/hosts file. Only way that it was successful was through bash...</p></pre>golangman: <pre><p><code>\n</code> worked. Never thought about using that.
Thanks for your help!</p></pre>
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889
- 请尽量让自己的回复能够对别人有帮助
- 支持 Markdown 格式, **粗体**、~~删除线~~、
`单行代码`
- 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
- 图片支持拖拽、截图粘贴等方式上传