updating /etc/hosts but asks for sudo access after executing as a normal user

xuanbao · · 208 次点击    
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
<p>Hello golang, I&#39;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&#39;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(&#34;bash&#34;, &#34;-c&#34;, &#34;echo blah 127.0.0.1 | sudo tee -a /etc/hosts&#34;) cmd.Start() err := cmd.Wait() if err != nil { fmt.Println(&#34;WHAT?&#34;) } </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 := &#34;/etc/hosts&#34; 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&#39;t prompt for password and can&#39;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群:701969077

208 次点击  
加入收藏 微博
暂无回复
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传